2 * io.c: File, console and find handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002 Ximian, Inc.
8 * Copyright (c) 2002-2006 Novell, Inc.
9 * Copyright 2011 Xamarin Inc (http://www.xamarin.com).
19 #ifdef HAVE_SYS_STATVFS_H
20 #include <sys/statvfs.h>
22 #if defined(HAVE_SYS_STATFS_H)
23 #include <sys/statfs.h>
25 #if defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H)
26 #include <sys/param.h>
27 #include <sys/mount.h>
29 #include <sys/types.h>
33 #include <sys/ioctl.h>
35 #include <mono/utils/linux_magic.h>
38 #include <mono/io-layer/wapi.h>
39 #include <mono/io-layer/wapi-private.h>
40 #include <mono/io-layer/handles-private.h>
41 #include <mono/io-layer/io-private.h>
42 #include <mono/io-layer/timefuncs-private.h>
43 #include <mono/io-layer/thread-private.h>
44 #include <mono/io-layer/io-portability.h>
45 #include <mono/utils/strenc.h>
48 #define DEBUG(...) g_message(__VA_ARGS__)
49 #define DEBUG_ENABLED 1
54 static void file_close (gpointer handle, gpointer data);
55 static WapiFileType file_getfiletype(void);
56 static gboolean file_read(gpointer handle, gpointer buffer,
57 guint32 numbytes, guint32 *bytesread,
58 WapiOverlapped *overlapped);
59 static gboolean file_write(gpointer handle, gconstpointer buffer,
60 guint32 numbytes, guint32 *byteswritten,
61 WapiOverlapped *overlapped);
62 static gboolean file_flush(gpointer handle);
63 static guint32 file_seek(gpointer handle, gint32 movedistance,
64 gint32 *highmovedistance, WapiSeekMethod method);
65 static gboolean file_setendoffile(gpointer handle);
66 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
67 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
68 WapiFileTime *last_access,
69 WapiFileTime *last_write);
70 static gboolean file_setfiletime(gpointer handle,
71 const WapiFileTime *create_time,
72 const WapiFileTime *last_access,
73 const WapiFileTime *last_write);
74 static guint32 GetDriveTypeFromPath (const gchar *utf8_root_path_name);
76 /* File handle is only signalled for overlapped IO */
77 struct _WapiHandleOps _wapi_file_ops = {
78 file_close, /* close */
82 NULL, /* special_wait */
86 void _wapi_file_details (gpointer handle_info)
88 struct _WapiHandle_file *file = (struct _WapiHandle_file *)handle_info;
90 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
92 file->fileaccess&GENERIC_READ?'R':'.',
93 file->fileaccess&GENERIC_WRITE?'W':'.',
94 file->fileaccess&GENERIC_EXECUTE?'X':'.',
95 file->sharemode&FILE_SHARE_READ?'R':'.',
96 file->sharemode&FILE_SHARE_WRITE?'W':'.',
97 file->sharemode&FILE_SHARE_DELETE?'D':'.',
101 static void console_close (gpointer handle, gpointer data);
102 static WapiFileType console_getfiletype(void);
103 static gboolean console_read(gpointer handle, gpointer buffer,
104 guint32 numbytes, guint32 *bytesread,
105 WapiOverlapped *overlapped);
106 static gboolean console_write(gpointer handle, gconstpointer buffer,
107 guint32 numbytes, guint32 *byteswritten,
108 WapiOverlapped *overlapped);
110 /* Console is mostly the same as file, except it can block waiting for
113 struct _WapiHandleOps _wapi_console_ops = {
114 console_close, /* close */
118 NULL, /* special_wait */
122 void _wapi_console_details (gpointer handle_info)
124 _wapi_file_details (handle_info);
127 /* Find handle has no ops.
129 struct _WapiHandleOps _wapi_find_ops = {
134 NULL, /* special_wait */
138 static void pipe_close (gpointer handle, gpointer data);
139 static WapiFileType pipe_getfiletype (void);
140 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
141 guint32 *bytesread, WapiOverlapped *overlapped);
142 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
143 guint32 numbytes, guint32 *byteswritten,
144 WapiOverlapped *overlapped);
148 struct _WapiHandleOps _wapi_pipe_ops = {
149 pipe_close, /* close */
153 NULL, /* special_wait */
157 void _wapi_pipe_details (gpointer handle_info)
159 _wapi_file_details (handle_info);
162 static const struct {
163 /* File, console and pipe handles */
164 WapiFileType (*getfiletype)(void);
166 /* File, console and pipe handles */
167 gboolean (*readfile)(gpointer handle, gpointer buffer,
168 guint32 numbytes, guint32 *bytesread,
169 WapiOverlapped *overlapped);
170 gboolean (*writefile)(gpointer handle, gconstpointer buffer,
171 guint32 numbytes, guint32 *byteswritten,
172 WapiOverlapped *overlapped);
173 gboolean (*flushfile)(gpointer handle);
176 guint32 (*seek)(gpointer handle, gint32 movedistance,
177 gint32 *highmovedistance, WapiSeekMethod method);
178 gboolean (*setendoffile)(gpointer handle);
179 guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
180 gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
181 WapiFileTime *last_access,
182 WapiFileTime *last_write);
183 gboolean (*setfiletime)(gpointer handle,
184 const WapiFileTime *create_time,
185 const WapiFileTime *last_access,
186 const WapiFileTime *last_write);
187 } io_ops[WAPI_HANDLE_COUNT]={
188 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
191 file_read, file_write,
192 file_flush, file_seek,
198 {console_getfiletype,
201 NULL, NULL, NULL, NULL, NULL, NULL},
203 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
205 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
207 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
209 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
210 /* socket (will need at least read and write) */
211 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
213 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
215 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
220 NULL, NULL, NULL, NULL, NULL, NULL},
223 static mono_once_t io_ops_once=MONO_ONCE_INIT;
224 static gboolean lock_while_writing = FALSE;
226 static void io_ops_init (void)
228 /* _wapi_handle_register_capabilities (WAPI_HANDLE_FILE, */
229 /* WAPI_HANDLE_CAP_WAIT); */
230 /* _wapi_handle_register_capabilities (WAPI_HANDLE_CONSOLE, */
231 /* WAPI_HANDLE_CAP_WAIT); */
233 if (g_getenv ("MONO_STRICT_IO_EMULATION") != NULL) {
234 lock_while_writing = TRUE;
238 /* Some utility functions.
242 * Check if a file is writable by the current user.
244 * This is is a best effort kind of thing. It assumes a reasonable sane set
245 * of permissions by the underlying OS.
247 * We assume that basic unix permission bits are authoritative. Which might not
248 * be the case under systems with extended permissions systems (posix ACLs, SELinux, OSX/iOS sandboxing, etc)
250 * The choice of access as the fallback is due to the expected lower overhead compared to trying to open the file.
252 * The only expected problem with using access are for root, setuid or setgid programs as access is not consistent
253 * under those situations. It's to be expected that this should not happen in practice as those bits are very dangerous
254 * and should not be used with a dynamic runtime.
257 is_file_writable (struct stat *st, const char *path)
259 /* Is it globally writable? */
260 if (st->st_mode & S_IWOTH)
263 /* Am I the owner? */
264 if ((st->st_uid == geteuid ()) && (st->st_mode & S_IWUSR))
267 /* Am I in the same group? */
268 if ((st->st_gid == getegid ()) && (st->st_mode & S_IWGRP))
271 /* Fallback to using access(2). It's not ideal as it might not take into consideration euid/egid
272 * but it's the only sane option we have on unix.
274 return access (path, W_OK) == 0;
278 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
285 /* FIXME: this could definitely be better, but there seems to
286 * be no pattern to the attributes that are set
289 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
290 if (S_ISSOCK (buf->st_mode))
291 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
293 filename = _wapi_basename (pathname);
295 if (S_ISDIR (buf->st_mode)) {
296 attrs = FILE_ATTRIBUTE_DIRECTORY;
297 if (!is_file_writable (buf, pathname)) {
298 attrs |= FILE_ATTRIBUTE_READONLY;
300 if (filename[0] == '.') {
301 attrs |= FILE_ATTRIBUTE_HIDDEN;
304 if (!is_file_writable (buf, pathname)) {
305 attrs = FILE_ATTRIBUTE_READONLY;
307 if (filename[0] == '.') {
308 attrs |= FILE_ATTRIBUTE_HIDDEN;
310 } else if (filename[0] == '.') {
311 attrs = FILE_ATTRIBUTE_HIDDEN;
313 attrs = FILE_ATTRIBUTE_NORMAL;
318 if (S_ISLNK (lbuf->st_mode)) {
319 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
329 _wapi_set_last_error_from_errno (void)
331 SetLastError (_wapi_get_win32_file_error (errno));
334 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
337 if (errno == ENOENT) {
338 /* Check the path - if it's a missing directory then
339 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
345 dirname = _wapi_dirname (path);
347 dirname = g_strdup (dir);
350 if (_wapi_access (dirname, F_OK) == 0) {
351 SetLastError (ERROR_FILE_NOT_FOUND);
353 SetLastError (ERROR_PATH_NOT_FOUND);
358 _wapi_set_last_error_from_errno ();
364 static void file_close (gpointer handle, gpointer data)
366 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
367 int fd = file_handle->fd;
369 DEBUG("%s: closing file handle %p [%s]", __func__, handle,
370 file_handle->filename);
372 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
373 _wapi_unlink (file_handle->filename);
375 g_free (file_handle->filename);
377 if (file_handle->share_info)
378 _wapi_handle_share_release (file_handle->share_info);
383 static WapiFileType file_getfiletype(void)
385 return(FILE_TYPE_DISK);
388 static gboolean file_read(gpointer handle, gpointer buffer,
389 guint32 numbytes, guint32 *bytesread,
390 WapiOverlapped *overlapped)
392 struct _WapiHandle_file *file_handle;
396 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
397 (gpointer *)&file_handle);
399 g_warning ("%s: error looking up file handle %p", __func__,
401 SetLastError (ERROR_INVALID_HANDLE);
405 fd = file_handle->fd;
406 if(bytesread!=NULL) {
410 if(!(file_handle->fileaccess & GENERIC_READ) &&
411 !(file_handle->fileaccess & GENERIC_ALL)) {
412 DEBUG("%s: handle %p doesn't have GENERIC_READ access: %u",
413 __func__, handle, file_handle->fileaccess);
415 SetLastError (ERROR_ACCESS_DENIED);
420 ret = read (fd, buffer, numbytes);
421 } while (ret == -1 && errno == EINTR &&
422 !_wapi_thread_cur_apc_pending());
427 DEBUG("%s: read of handle %p error: %s", __func__,
428 handle, strerror(err));
429 SetLastError (_wapi_get_win32_file_error (err));
433 if (bytesread != NULL) {
440 static gboolean file_write(gpointer handle, gconstpointer buffer,
441 guint32 numbytes, guint32 *byteswritten,
442 WapiOverlapped *overlapped G_GNUC_UNUSED)
444 struct _WapiHandle_file *file_handle;
447 off_t current_pos = 0;
449 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
450 (gpointer *)&file_handle);
452 g_warning ("%s: error looking up file handle %p", __func__,
454 SetLastError (ERROR_INVALID_HANDLE);
458 fd = file_handle->fd;
460 if(byteswritten!=NULL) {
464 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
465 !(file_handle->fileaccess & GENERIC_ALL)) {
466 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
468 SetLastError (ERROR_ACCESS_DENIED);
472 if (lock_while_writing) {
473 /* Need to lock the region we're about to write to,
474 * because we only do advisory locking on POSIX
477 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
478 if (current_pos == -1) {
479 DEBUG ("%s: handle %p lseek failed: %s", __func__,
480 handle, strerror (errno));
481 _wapi_set_last_error_from_errno ();
485 if (_wapi_lock_file_region (fd, current_pos,
486 numbytes) == FALSE) {
487 /* The error has already been set */
493 ret = write (fd, buffer, numbytes);
494 } while (ret == -1 && errno == EINTR &&
495 !_wapi_thread_cur_apc_pending());
497 if (lock_while_writing) {
498 _wapi_unlock_file_region (fd, current_pos, numbytes);
502 if (errno == EINTR) {
505 _wapi_set_last_error_from_errno ();
507 DEBUG("%s: write of handle %p error: %s",
508 __func__, handle, strerror(errno));
513 if (byteswritten != NULL) {
519 static gboolean file_flush(gpointer handle)
521 struct _WapiHandle_file *file_handle;
525 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
526 (gpointer *)&file_handle);
528 g_warning ("%s: error looking up file handle %p", __func__,
530 SetLastError (ERROR_INVALID_HANDLE);
534 fd = file_handle->fd;
536 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
537 !(file_handle->fileaccess & GENERIC_ALL)) {
538 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
540 SetLastError (ERROR_ACCESS_DENIED);
546 DEBUG("%s: fsync of handle %p error: %s", __func__, handle,
549 _wapi_set_last_error_from_errno ();
556 static guint32 file_seek(gpointer handle, gint32 movedistance,
557 gint32 *highmovedistance, WapiSeekMethod method)
559 struct _WapiHandle_file *file_handle;
561 gint64 offset, newpos;
565 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
566 (gpointer *)&file_handle);
568 g_warning ("%s: error looking up file handle %p", __func__,
570 SetLastError (ERROR_INVALID_HANDLE);
571 return(INVALID_SET_FILE_POINTER);
574 fd = file_handle->fd;
576 if(!(file_handle->fileaccess & GENERIC_READ) &&
577 !(file_handle->fileaccess & GENERIC_WRITE) &&
578 !(file_handle->fileaccess & GENERIC_ALL)) {
579 DEBUG ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
581 SetLastError (ERROR_ACCESS_DENIED);
582 return(INVALID_SET_FILE_POINTER);
596 DEBUG("%s: invalid seek type %d", __func__, method);
598 SetLastError (ERROR_INVALID_PARAMETER);
599 return(INVALID_SET_FILE_POINTER);
602 #ifdef HAVE_LARGE_FILE_SUPPORT
603 if(highmovedistance==NULL) {
605 DEBUG("%s: setting offset to %lld (low %d)", __func__,
606 offset, movedistance);
608 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
610 DEBUG("%s: setting offset to %lld 0x%llx (high %d 0x%x, low %d 0x%x)", __func__, offset, offset, *highmovedistance, *highmovedistance, movedistance, movedistance);
616 DEBUG ("%s: moving handle %p by %lld bytes from %d", __func__,
617 handle, (long long)offset, whence);
619 #ifdef PLATFORM_ANDROID
620 /* bionic doesn't support -D_FILE_OFFSET_BITS=64 */
621 newpos=lseek64(fd, offset, whence);
623 newpos=lseek(fd, offset, whence);
626 DEBUG("%s: lseek on handle %p returned error %s",
627 __func__, handle, strerror(errno));
629 _wapi_set_last_error_from_errno ();
630 return(INVALID_SET_FILE_POINTER);
633 DEBUG ("%s: lseek returns %lld", __func__, newpos);
635 #ifdef HAVE_LARGE_FILE_SUPPORT
636 ret=newpos & 0xFFFFFFFF;
637 if(highmovedistance!=NULL) {
638 *highmovedistance=newpos>>32;
642 if(highmovedistance!=NULL) {
643 /* Accurate, but potentially dodgy :-) */
648 DEBUG ("%s: move of handle %p returning %d/%d", __func__,
649 handle, ret, highmovedistance==NULL?0:*highmovedistance);
654 static gboolean file_setendoffile(gpointer handle)
656 struct _WapiHandle_file *file_handle;
662 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
663 (gpointer *)&file_handle);
665 g_warning ("%s: error looking up file handle %p", __func__,
667 SetLastError (ERROR_INVALID_HANDLE);
670 fd = file_handle->fd;
672 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
673 !(file_handle->fileaccess & GENERIC_ALL)) {
674 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
676 SetLastError (ERROR_ACCESS_DENIED);
680 /* Find the current file position, and the file length. If
681 * the file position is greater than the length, write to
682 * extend the file with a hole. If the file position is less
683 * than the length, truncate the file.
686 ret=fstat(fd, &statbuf);
688 DEBUG ("%s: handle %p fstat failed: %s", __func__,
689 handle, strerror(errno));
691 _wapi_set_last_error_from_errno ();
694 size=statbuf.st_size;
696 pos=lseek(fd, (off_t)0, SEEK_CUR);
698 DEBUG("%s: handle %p lseek failed: %s", __func__,
699 handle, strerror(errno));
701 _wapi_set_last_error_from_errno ();
705 #ifdef FTRUNCATE_DOESNT_EXTEND
706 /* I haven't bothered to write the configure.ac stuff for this
707 * because I don't know if any platform needs it. I'm leaving
708 * this code just in case though
711 /* Extend the file. Use write() here, because some
712 * manuals say that ftruncate() behaviour is undefined
713 * when the file needs extending. The POSIX spec says
714 * that on XSI-conformant systems it extends, so if
715 * every system we care about conforms, then we can
719 ret = write (fd, "", 1);
720 } while (ret == -1 && errno == EINTR &&
721 !_wapi_thread_cur_apc_pending());
724 DEBUG("%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
726 _wapi_set_last_error_from_errno ();
730 /* And put the file position back after the write */
731 ret = lseek (fd, pos, SEEK_SET);
733 DEBUG ("%s: handle %p second lseek failed: %s",
734 __func__, handle, strerror(errno));
736 _wapi_set_last_error_from_errno ();
742 /* Native Client has no ftruncate function, even in standalone sel_ldr. */
743 #ifndef __native_client__
744 /* always truncate, because the extend write() adds an extra
745 * byte to the end of the file
748 ret=ftruncate(fd, pos);
750 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
752 DEBUG("%s: handle %p ftruncate failed: %s", __func__,
753 handle, strerror(errno));
755 _wapi_set_last_error_from_errno ();
763 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
765 struct _WapiHandle_file *file_handle;
772 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
773 (gpointer *)&file_handle);
775 g_warning ("%s: error looking up file handle %p", __func__,
777 SetLastError (ERROR_INVALID_HANDLE);
778 return(INVALID_FILE_SIZE);
780 fd = file_handle->fd;
782 if(!(file_handle->fileaccess & GENERIC_READ) &&
783 !(file_handle->fileaccess & GENERIC_WRITE) &&
784 !(file_handle->fileaccess & GENERIC_ALL)) {
785 DEBUG("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
787 SetLastError (ERROR_ACCESS_DENIED);
788 return(INVALID_FILE_SIZE);
791 /* If the file has a size with the low bits 0xFFFFFFFF the
792 * caller can't tell if this is an error, so clear the error
795 SetLastError (ERROR_SUCCESS);
797 ret = fstat(fd, &statbuf);
799 DEBUG ("%s: handle %p fstat failed: %s", __func__,
800 handle, strerror(errno));
802 _wapi_set_last_error_from_errno ();
803 return(INVALID_FILE_SIZE);
806 /* fstat indicates block devices as zero-length, so go a different path */
808 if (S_ISBLK(statbuf.st_mode)) {
810 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
811 DEBUG ("%s: handle %p ioctl BLKGETSIZE64 failed: %s",
812 __func__, handle, strerror(errno));
814 _wapi_set_last_error_from_errno ();
815 return(INVALID_FILE_SIZE);
818 size = bigsize & 0xFFFFFFFF;
819 if (highsize != NULL) {
820 *highsize = bigsize>>32;
823 DEBUG ("%s: Returning block device size %d/%d",
824 __func__, size, *highsize);
830 #ifdef HAVE_LARGE_FILE_SUPPORT
831 size = statbuf.st_size & 0xFFFFFFFF;
832 if (highsize != NULL) {
833 *highsize = statbuf.st_size>>32;
836 if (highsize != NULL) {
837 /* Accurate, but potentially dodgy :-) */
840 size = statbuf.st_size;
843 DEBUG ("%s: Returning size %d/%d", __func__, size, *highsize);
848 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
849 WapiFileTime *last_access,
850 WapiFileTime *last_write)
852 struct _WapiHandle_file *file_handle;
855 guint64 create_ticks, access_ticks, write_ticks;
858 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
859 (gpointer *)&file_handle);
861 g_warning ("%s: error looking up file handle %p", __func__,
863 SetLastError (ERROR_INVALID_HANDLE);
866 fd = file_handle->fd;
868 if(!(file_handle->fileaccess & GENERIC_READ) &&
869 !(file_handle->fileaccess & GENERIC_ALL)) {
870 DEBUG("%s: handle %p doesn't have GENERIC_READ access: %u",
871 __func__, handle, file_handle->fileaccess);
873 SetLastError (ERROR_ACCESS_DENIED);
877 ret=fstat(fd, &statbuf);
879 DEBUG("%s: handle %p fstat failed: %s", __func__, handle,
882 _wapi_set_last_error_from_errno ();
886 DEBUG("%s: atime: %ld ctime: %ld mtime: %ld", __func__,
887 statbuf.st_atime, statbuf.st_ctime,
890 /* Try and guess a meaningful create time by using the older
893 /* The magic constant comes from msdn documentation
894 * "Converting a time_t Value to a File Time"
896 if(statbuf.st_atime < statbuf.st_ctime) {
897 create_ticks=((guint64)statbuf.st_atime*10000000)
898 + 116444736000000000ULL;
900 create_ticks=((guint64)statbuf.st_ctime*10000000)
901 + 116444736000000000ULL;
904 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
905 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
907 DEBUG("%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
908 access_ticks, create_ticks, write_ticks);
910 if(create_time!=NULL) {
911 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
912 create_time->dwHighDateTime = create_ticks >> 32;
915 if(last_access!=NULL) {
916 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
917 last_access->dwHighDateTime = access_ticks >> 32;
920 if(last_write!=NULL) {
921 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
922 last_write->dwHighDateTime = write_ticks >> 32;
928 static gboolean file_setfiletime(gpointer handle,
929 const WapiFileTime *create_time G_GNUC_UNUSED,
930 const WapiFileTime *last_access,
931 const WapiFileTime *last_write)
933 struct _WapiHandle_file *file_handle;
935 struct utimbuf utbuf;
937 guint64 access_ticks, write_ticks;
940 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
941 (gpointer *)&file_handle);
943 g_warning ("%s: error looking up file handle %p", __func__,
945 SetLastError (ERROR_INVALID_HANDLE);
948 fd = file_handle->fd;
950 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
951 !(file_handle->fileaccess & GENERIC_ALL)) {
952 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
954 SetLastError (ERROR_ACCESS_DENIED);
958 if(file_handle->filename == NULL) {
959 DEBUG("%s: handle %p unknown filename", __func__, handle);
961 SetLastError (ERROR_INVALID_HANDLE);
965 /* Get the current times, so we can put the same times back in
966 * the event that one of the FileTime structs is NULL
968 ret=fstat (fd, &statbuf);
970 DEBUG("%s: handle %p fstat failed: %s", __func__, handle,
973 SetLastError (ERROR_INVALID_PARAMETER);
977 if(last_access!=NULL) {
978 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
979 last_access->dwLowDateTime;
980 /* This is (time_t)0. We can actually go to INT_MIN,
981 * but this will do for now.
983 if (access_ticks < 116444736000000000ULL) {
984 DEBUG ("%s: attempt to set access time too early",
986 SetLastError (ERROR_INVALID_PARAMETER);
990 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
992 utbuf.actime=statbuf.st_atime;
995 if(last_write!=NULL) {
996 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
997 last_write->dwLowDateTime;
998 /* This is (time_t)0. We can actually go to INT_MIN,
999 * but this will do for now.
1001 if (write_ticks < 116444736000000000ULL) {
1002 DEBUG ("%s: attempt to set write time too early",
1004 SetLastError (ERROR_INVALID_PARAMETER);
1008 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1010 utbuf.modtime=statbuf.st_mtime;
1013 DEBUG ("%s: setting handle %p access %ld write %ld", __func__,
1014 handle, utbuf.actime, utbuf.modtime);
1016 ret = _wapi_utime (file_handle->filename, &utbuf);
1018 DEBUG ("%s: handle %p [%s] utime failed: %s", __func__,
1019 handle, file_handle->filename, strerror(errno));
1021 SetLastError (ERROR_INVALID_PARAMETER);
1028 static void console_close (gpointer handle, gpointer data)
1030 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1031 int fd = console_handle->fd;
1033 DEBUG("%s: closing console handle %p", __func__, handle);
1035 g_free (console_handle->filename);
1040 static WapiFileType console_getfiletype(void)
1042 return(FILE_TYPE_CHAR);
1045 static gboolean console_read(gpointer handle, gpointer buffer,
1046 guint32 numbytes, guint32 *bytesread,
1047 WapiOverlapped *overlapped G_GNUC_UNUSED)
1049 struct _WapiHandle_file *console_handle;
1053 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1054 (gpointer *)&console_handle);
1056 g_warning ("%s: error looking up console handle %p", __func__,
1058 SetLastError (ERROR_INVALID_HANDLE);
1061 fd = console_handle->fd;
1063 if(bytesread!=NULL) {
1067 if(!(console_handle->fileaccess & GENERIC_READ) &&
1068 !(console_handle->fileaccess & GENERIC_ALL)) {
1069 DEBUG ("%s: handle %p doesn't have GENERIC_READ access: %u",
1070 __func__, handle, console_handle->fileaccess);
1072 SetLastError (ERROR_ACCESS_DENIED);
1077 ret=read(fd, buffer, numbytes);
1078 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1081 DEBUG("%s: read of handle %p error: %s", __func__, handle,
1084 _wapi_set_last_error_from_errno ();
1088 if(bytesread!=NULL) {
1095 static gboolean console_write(gpointer handle, gconstpointer buffer,
1096 guint32 numbytes, guint32 *byteswritten,
1097 WapiOverlapped *overlapped G_GNUC_UNUSED)
1099 struct _WapiHandle_file *console_handle;
1103 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1104 (gpointer *)&console_handle);
1106 g_warning ("%s: error looking up console handle %p", __func__,
1108 SetLastError (ERROR_INVALID_HANDLE);
1111 fd = console_handle->fd;
1113 if(byteswritten!=NULL) {
1117 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1118 !(console_handle->fileaccess & GENERIC_ALL)) {
1119 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, console_handle->fileaccess);
1121 SetLastError (ERROR_ACCESS_DENIED);
1126 ret = write(fd, buffer, numbytes);
1127 } while (ret == -1 && errno == EINTR &&
1128 !_wapi_thread_cur_apc_pending());
1131 if (errno == EINTR) {
1134 _wapi_set_last_error_from_errno ();
1136 DEBUG ("%s: write of handle %p error: %s",
1137 __func__, handle, strerror(errno));
1142 if(byteswritten!=NULL) {
1149 static void pipe_close (gpointer handle, gpointer data)
1151 struct _WapiHandle_file *pipe_handle = (struct _WapiHandle_file*)data;
1152 int fd = pipe_handle->fd;
1154 DEBUG("%s: closing pipe handle %p", __func__, handle);
1156 /* No filename with pipe handles */
1161 static WapiFileType pipe_getfiletype(void)
1163 return(FILE_TYPE_PIPE);
1166 static gboolean pipe_read (gpointer handle, gpointer buffer,
1167 guint32 numbytes, guint32 *bytesread,
1168 WapiOverlapped *overlapped G_GNUC_UNUSED)
1170 struct _WapiHandle_file *pipe_handle;
1174 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1175 (gpointer *)&pipe_handle);
1177 g_warning ("%s: error looking up pipe handle %p", __func__,
1179 SetLastError (ERROR_INVALID_HANDLE);
1182 fd = pipe_handle->fd;
1184 if(bytesread!=NULL) {
1188 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1189 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1190 DEBUG("%s: handle %p doesn't have GENERIC_READ access: %u",
1191 __func__, handle, pipe_handle->fileaccess);
1193 SetLastError (ERROR_ACCESS_DENIED);
1197 DEBUG ("%s: reading up to %d bytes from pipe %p", __func__,
1201 ret=read(fd, buffer, numbytes);
1202 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1205 if (errno == EINTR) {
1208 _wapi_set_last_error_from_errno ();
1210 DEBUG("%s: read of handle %p error: %s", __func__,
1211 handle, strerror(errno));
1217 DEBUG ("%s: read %d bytes from pipe", __func__, ret);
1219 if(bytesread!=NULL) {
1226 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1227 guint32 numbytes, guint32 *byteswritten,
1228 WapiOverlapped *overlapped G_GNUC_UNUSED)
1230 struct _WapiHandle_file *pipe_handle;
1234 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1235 (gpointer *)&pipe_handle);
1237 g_warning ("%s: error looking up pipe handle %p", __func__,
1239 SetLastError (ERROR_INVALID_HANDLE);
1242 fd = pipe_handle->fd;
1244 if(byteswritten!=NULL) {
1248 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1249 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1250 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, pipe_handle->fileaccess);
1252 SetLastError (ERROR_ACCESS_DENIED);
1256 DEBUG ("%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1260 ret = write (fd, buffer, numbytes);
1261 } while (ret == -1 && errno == EINTR &&
1262 !_wapi_thread_cur_apc_pending());
1265 if (errno == EINTR) {
1268 _wapi_set_last_error_from_errno ();
1270 DEBUG("%s: write of handle %p error: %s", __func__,
1271 handle, strerror(errno));
1276 if(byteswritten!=NULL) {
1283 static int convert_flags(guint32 fileaccess, guint32 createmode)
1287 switch(fileaccess) {
1294 case GENERIC_READ|GENERIC_WRITE:
1298 DEBUG("%s: Unknown access type 0x%x", __func__,
1303 switch(createmode) {
1305 flags|=O_CREAT|O_EXCL;
1308 flags|=O_CREAT|O_TRUNC;
1315 case TRUNCATE_EXISTING:
1319 DEBUG("%s: Unknown create mode 0x%x", __func__,
1328 static mode_t convert_perms(guint32 sharemode)
1332 if(sharemode&FILE_SHARE_READ) {
1335 if(sharemode&FILE_SHARE_WRITE) {
1343 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1345 struct _WapiFileShare **share_info)
1347 gboolean file_already_shared;
1348 guint32 file_existing_share, file_existing_access;
1350 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);
1352 if (file_already_shared) {
1353 /* The reference to this share info was incremented
1354 * when we looked it up, so be careful to put it back
1355 * if we conclude we can't use this file.
1357 if (file_existing_share == 0) {
1358 /* Quick and easy, no possibility to share */
1359 DEBUG ("%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
1361 _wapi_handle_share_release (*share_info);
1366 if (((file_existing_share == FILE_SHARE_READ) &&
1367 (fileaccess != GENERIC_READ)) ||
1368 ((file_existing_share == FILE_SHARE_WRITE) &&
1369 (fileaccess != GENERIC_WRITE))) {
1370 /* New access mode doesn't match up */
1371 DEBUG ("%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
1373 _wapi_handle_share_release (*share_info);
1378 if (((file_existing_access & GENERIC_READ) &&
1379 !(sharemode & FILE_SHARE_READ)) ||
1380 ((file_existing_access & GENERIC_WRITE) &&
1381 !(sharemode & FILE_SHARE_WRITE))) {
1382 /* New share mode doesn't match up */
1383 DEBUG ("%s: Access mode prevents open: requested share: 0x%x, file has access: 0x%x", __func__, sharemode, file_existing_access);
1385 _wapi_handle_share_release (*share_info);
1390 DEBUG ("%s: New file!", __func__);
1398 share_allows_delete (struct stat *statbuf, struct _WapiFileShare **share_info)
1400 gboolean file_already_shared;
1401 guint32 file_existing_share, file_existing_access;
1403 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);
1405 if (file_already_shared) {
1406 /* The reference to this share info was incremented
1407 * when we looked it up, so be careful to put it back
1408 * if we conclude we can't use this file.
1410 if (file_existing_share == 0) {
1411 /* Quick and easy, no possibility to share */
1412 DEBUG ("%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
1414 _wapi_handle_share_release (*share_info);
1419 if (!(file_existing_share & FILE_SHARE_DELETE)) {
1420 /* New access mode doesn't match up */
1421 DEBUG ("%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
1423 _wapi_handle_share_release (*share_info);
1428 DEBUG ("%s: New file!", __func__);
1433 static gboolean share_check (struct stat *statbuf, guint32 sharemode,
1435 struct _WapiFileShare **share_info, int fd)
1437 if (share_allows_open (statbuf, sharemode, fileaccess,
1438 share_info) == TRUE) {
1442 /* Got a share violation. Double check that the file is still
1443 * open by someone, in case a process crashed while still
1444 * holding a file handle. This will also cope with someone
1445 * using Mono.Posix to close the file. This is cheaper and
1446 * less intrusive to other processes than initiating a handle
1450 _wapi_handle_check_share (*share_info, fd);
1451 if (share_allows_open (statbuf, sharemode, fileaccess,
1452 share_info) == TRUE) {
1456 /* Still violating. It's possible that a process crashed
1457 * while still holding a file handle, and that a non-mono
1458 * process has the file open. (For example, C-c mcs while
1459 * editing a source file.) As a last resort, run a handle
1460 * collection, which will remove stale share entries.
1462 _wapi_handle_collect ();
1464 return(share_allows_open (statbuf, sharemode, fileaccess, share_info));
1469 * @name: a pointer to a NULL-terminated unicode string, that names
1470 * the file or other object to create.
1471 * @fileaccess: specifies the file access mode
1472 * @sharemode: whether the file should be shared. This parameter is
1473 * currently ignored.
1474 * @security: Ignored for now.
1475 * @createmode: specifies whether to create a new file, whether to
1476 * overwrite an existing file, whether to truncate the file, etc.
1477 * @attrs: specifies file attributes and flags. On win32 attributes
1478 * are characteristics of the file, not the handle, and are ignored
1479 * when an existing file is opened. Flags give the library hints on
1480 * how to process a file to optimise performance.
1481 * @template: the handle of an open %GENERIC_READ file that specifies
1482 * attributes to apply to a newly created file, ignoring @attrs.
1483 * Normally this parameter is NULL. This parameter is ignored when an
1484 * existing file is opened.
1486 * Creates a new file handle. This only applies to normal files:
1487 * pipes are handled by CreatePipe(), and console handles are created
1488 * with GetStdHandle().
1490 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1492 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1493 guint32 sharemode, WapiSecurityAttributes *security,
1494 guint32 createmode, guint32 attrs,
1495 gpointer template G_GNUC_UNUSED)
1497 struct _WapiHandle_file file_handle = {0};
1499 int flags=convert_flags(fileaccess, createmode);
1500 /*mode_t perms=convert_perms(sharemode);*/
1501 /* we don't use sharemode, because that relates to sharing of
1502 * the file when the file is open and is already handled by
1503 * other code, perms instead are the on-disk permissions and
1504 * this is a sane default.
1510 struct stat statbuf;
1512 mono_once (&io_ops_once, io_ops_init);
1514 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1517 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1518 SetLastError (ERROR_ENCRYPTION_FAILED);
1519 return INVALID_HANDLE_VALUE;
1523 DEBUG ("%s: name is NULL", __func__);
1525 SetLastError (ERROR_INVALID_NAME);
1526 return(INVALID_HANDLE_VALUE);
1529 filename = mono_unicode_to_external (name);
1530 if (filename == NULL) {
1531 DEBUG("%s: unicode conversion returned NULL", __func__);
1533 SetLastError (ERROR_INVALID_NAME);
1534 return(INVALID_HANDLE_VALUE);
1537 DEBUG ("%s: Opening %s with share 0x%x and access 0x%x", __func__,
1538 filename, sharemode, fileaccess);
1540 fd = _wapi_open (filename, flags, perms);
1542 /* If we were trying to open a directory with write permissions
1543 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1544 * EISDIR. However, this is a bit bogus because calls to
1545 * manipulate the directory (e.g. SetFileTime) will still work on
1546 * the directory because they use other API calls
1547 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1548 * to open the directory again without write permission.
1550 if (fd == -1 && errno == EISDIR)
1552 /* Try again but don't try to make it writable */
1553 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1557 DEBUG("%s: Error opening file %s: %s", __func__, filename,
1559 _wapi_set_last_path_error_from_errno (NULL, filename);
1562 return(INVALID_HANDLE_VALUE);
1565 if (fd >= _wapi_fd_reserve) {
1566 DEBUG ("%s: File descriptor is too big", __func__);
1568 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1573 return(INVALID_HANDLE_VALUE);
1576 ret = fstat (fd, &statbuf);
1578 DEBUG ("%s: fstat error of file %s: %s", __func__,
1579 filename, strerror (errno));
1580 _wapi_set_last_error_from_errno ();
1584 return(INVALID_HANDLE_VALUE);
1586 #ifdef __native_client__
1587 /* Workaround: Native Client currently returns the same fake inode
1588 * for all files, so do a simple hash on the filename so we don't
1589 * use the same share info for each file.
1591 statbuf.st_ino = g_str_hash(filename);
1594 if (share_check (&statbuf, sharemode, fileaccess,
1595 &file_handle.share_info, fd) == FALSE) {
1596 SetLastError (ERROR_SHARING_VIOLATION);
1600 return (INVALID_HANDLE_VALUE);
1602 if (file_handle.share_info == NULL) {
1603 /* No space, so no more files can be opened */
1604 DEBUG ("%s: No space in the share table", __func__);
1606 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1610 return(INVALID_HANDLE_VALUE);
1613 file_handle.filename = filename;
1615 if(security!=NULL) {
1616 //file_handle->security_attributes=_wapi_handle_scratch_store (
1617 //security, sizeof(WapiSecurityAttributes));
1620 file_handle.fd = fd;
1621 file_handle.fileaccess=fileaccess;
1622 file_handle.sharemode=sharemode;
1623 file_handle.attrs=attrs;
1625 #ifdef HAVE_POSIX_FADVISE
1626 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1627 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1628 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1629 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1633 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1635 if (S_ISFIFO (statbuf.st_mode)) {
1636 handle_type = WAPI_HANDLE_PIPE;
1637 } else if (S_ISCHR (statbuf.st_mode)) {
1638 handle_type = WAPI_HANDLE_CONSOLE;
1640 handle_type = WAPI_HANDLE_FILE;
1643 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1644 if (handle == _WAPI_HANDLE_INVALID) {
1645 g_warning ("%s: error creating file handle", __func__);
1649 SetLastError (ERROR_GEN_FAILURE);
1650 return(INVALID_HANDLE_VALUE);
1653 DEBUG("%s: returning handle %p", __func__, handle);
1660 * @name: a pointer to a NULL-terminated unicode string, that names
1661 * the file to be deleted.
1663 * Deletes file @name.
1665 * Return value: %TRUE on success, %FALSE otherwise.
1667 gboolean DeleteFile(const gunichar2 *name)
1671 gboolean ret = FALSE;
1674 struct stat statbuf;
1675 struct _WapiFileShare *shareinfo;
1679 DEBUG("%s: name is NULL", __func__);
1681 SetLastError (ERROR_INVALID_NAME);
1685 filename=mono_unicode_to_external(name);
1686 if(filename==NULL) {
1687 DEBUG("%s: unicode conversion returned NULL", __func__);
1689 SetLastError (ERROR_INVALID_NAME);
1693 attrs = GetFileAttributes (name);
1694 if (attrs == INVALID_FILE_ATTRIBUTES) {
1695 DEBUG ("%s: file attributes error", __func__);
1696 /* Error set by GetFileAttributes() */
1702 /* Check to make sure sharing allows us to open the file for
1703 * writing. See bug 323389.
1705 * Do the checks that don't need an open file descriptor, for
1706 * simplicity's sake. If we really have to do the full checks
1707 * then we can implement that later.
1709 if (_wapi_stat (filename, &statbuf) < 0) {
1710 _wapi_set_last_path_error_from_errno (NULL, filename);
1715 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1716 &shareinfo) == FALSE) {
1717 SetLastError (ERROR_SHARING_VIOLATION);
1722 _wapi_handle_share_release (shareinfo);
1725 retval = _wapi_unlink (filename);
1728 _wapi_set_last_path_error_from_errno (NULL, filename);
1740 * @name: a pointer to a NULL-terminated unicode string, that names
1741 * the file to be moved.
1742 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1743 * new name for the file.
1745 * Renames file @name to @dest_name.
1746 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1747 * when it is the same file as the source. In that case it silently succeeds.
1749 * Return value: %TRUE on success, %FALSE otherwise.
1751 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1753 gchar *utf8_name, *utf8_dest_name;
1754 int result, errno_copy;
1755 struct stat stat_src, stat_dest;
1756 gboolean ret = FALSE;
1757 struct _WapiFileShare *shareinfo;
1760 DEBUG("%s: name is NULL", __func__);
1762 SetLastError (ERROR_INVALID_NAME);
1766 utf8_name = mono_unicode_to_external (name);
1767 if (utf8_name == NULL) {
1768 DEBUG ("%s: unicode conversion returned NULL", __func__);
1770 SetLastError (ERROR_INVALID_NAME);
1774 if(dest_name==NULL) {
1775 DEBUG("%s: name is NULL", __func__);
1778 SetLastError (ERROR_INVALID_NAME);
1782 utf8_dest_name = mono_unicode_to_external (dest_name);
1783 if (utf8_dest_name == NULL) {
1784 DEBUG ("%s: unicode conversion returned NULL", __func__);
1787 SetLastError (ERROR_INVALID_NAME);
1792 * In C# land we check for the existence of src, but not for dest.
1793 * We check it here and return the failure if dest exists and is not
1794 * the same file as src.
1796 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1797 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1798 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1800 g_free (utf8_dest_name);
1805 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1806 if (stat_dest.st_dev != stat_src.st_dev ||
1807 stat_dest.st_ino != stat_src.st_ino) {
1809 g_free (utf8_dest_name);
1810 SetLastError (ERROR_ALREADY_EXISTS);
1815 /* Check to make that we have delete sharing permission.
1816 * See https://bugzilla.xamarin.com/show_bug.cgi?id=17009
1818 * Do the checks that don't need an open file descriptor, for
1819 * simplicity's sake. If we really have to do the full checks
1820 * then we can implement that later.
1822 if (share_allows_delete (&stat_src, &shareinfo) == FALSE) {
1823 SetLastError (ERROR_SHARING_VIOLATION);
1827 _wapi_handle_share_release (shareinfo);
1829 result = _wapi_rename (utf8_name, utf8_dest_name);
1833 switch(errno_copy) {
1835 SetLastError (ERROR_ALREADY_EXISTS);
1839 /* Ignore here, it is dealt with below */
1843 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1848 g_free (utf8_dest_name);
1850 if (result != 0 && errno_copy == EXDEV) {
1851 if (S_ISDIR (stat_src.st_mode)) {
1852 SetLastError (ERROR_NOT_SAME_DEVICE);
1855 /* Try a copy to the new location, and delete the source */
1856 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1857 /* CopyFile will set the error */
1861 return(DeleteFile (name));
1872 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1876 int buf_size = st_src->st_blksize;
1878 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1879 buf = (char *) malloc (buf_size);
1882 remain = read (src_fd, buf, buf_size);
1884 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1888 _wapi_set_last_error_from_errno ();
1898 while (remain > 0) {
1899 if ((n = write (dest_fd, wbuf, remain)) < 0) {
1900 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1904 _wapi_set_last_error_from_errno ();
1905 DEBUG ("%s: write failed.", __func__);
1921 * @name: a pointer to a NULL-terminated unicode string, that names
1922 * the file to be copied.
1923 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1924 * new name for the file.
1925 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1927 * Copies file @name to @dest_name
1929 * Return value: %TRUE on success, %FALSE otherwise.
1931 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1932 gboolean fail_if_exists)
1934 gchar *utf8_src, *utf8_dest;
1935 int src_fd, dest_fd;
1936 struct stat st, dest_st;
1937 struct utimbuf dest_time;
1938 gboolean ret = TRUE;
1942 DEBUG("%s: name is NULL", __func__);
1944 SetLastError (ERROR_INVALID_NAME);
1948 utf8_src = mono_unicode_to_external (name);
1949 if (utf8_src == NULL) {
1950 DEBUG ("%s: unicode conversion of source returned NULL",
1953 SetLastError (ERROR_INVALID_PARAMETER);
1957 if(dest_name==NULL) {
1958 DEBUG("%s: dest is NULL", __func__);
1961 SetLastError (ERROR_INVALID_NAME);
1965 utf8_dest = mono_unicode_to_external (dest_name);
1966 if (utf8_dest == NULL) {
1967 DEBUG ("%s: unicode conversion of dest returned NULL",
1970 SetLastError (ERROR_INVALID_PARAMETER);
1977 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
1979 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
1987 if (fstat (src_fd, &st) < 0) {
1988 _wapi_set_last_error_from_errno ();
1997 /* Before trying to open/create the dest, we need to report a 'file busy'
1998 * error if src and dest are actually the same file. We do the check here to take
1999 * advantage of the IOMAP capability */
2000 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
2001 st.st_ino == dest_st.st_ino) {
2007 SetLastError (ERROR_SHARING_VIOLATION);
2011 if (fail_if_exists) {
2012 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2014 /* FIXME: it kinda sucks that this code path potentially scans
2015 * the directory twice due to the weird SetLastError()
2017 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2019 /* The file does not exist, try creating it */
2020 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2022 /* Apparently this error is set if we
2023 * overwrite the dest file
2025 SetLastError (ERROR_ALREADY_EXISTS);
2029 _wapi_set_last_error_from_errno ();
2038 if (!write_file (src_fd, dest_fd, &st, TRUE))
2044 dest_time.modtime = st.st_mtime;
2045 dest_time.actime = st.st_atime;
2046 ret_utime = utime (utf8_dest, &dest_time);
2047 if (ret_utime == -1)
2048 DEBUG ("%s: file [%s] utime failed: %s", __func__, utf8_dest, strerror(errno));
2057 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2062 DEBUG ("%s: %s is NULL", __func__, arg_name);
2063 SetLastError (ERROR_INVALID_NAME);
2067 utf8_ret = mono_unicode_to_external (arg);
2068 if (utf8_ret == NULL) {
2069 DEBUG ("%s: unicode conversion of %s returned NULL",
2070 __func__, arg_name);
2071 SetLastError (ERROR_INVALID_PARAMETER);
2079 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2080 const gunichar2 *backupFileName, guint32 replaceFlags,
2081 gpointer exclude, gpointer reserved)
2083 int result, backup_fd = -1,replaced_fd = -1;
2084 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2085 struct stat stBackup;
2086 gboolean ret = FALSE;
2088 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2090 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2091 goto replace_cleanup;
2092 if (backupFileName != NULL) {
2093 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2094 goto replace_cleanup;
2097 if (utf8_backupFileName) {
2098 // Open the backup file for read so we can restore the file if an error occurs.
2099 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2100 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2102 goto replace_cleanup;
2105 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2107 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2108 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2109 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2110 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2113 if (replaced_fd == -1)
2114 goto replace_cleanup;
2116 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2119 goto replace_cleanup;
2125 g_free (utf8_replacedFileName);
2126 g_free (utf8_replacementFileName);
2127 g_free (utf8_backupFileName);
2128 if (backup_fd != -1)
2130 if (replaced_fd != -1)
2131 close (replaced_fd);
2137 * @stdhandle: specifies the file descriptor
2139 * Returns a handle for stdin, stdout, or stderr. Always returns the
2140 * same handle for the same @stdhandle.
2142 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2145 static mono_mutex_t stdhandle_mutex;
2147 gpointer GetStdHandle(WapiStdHandle stdhandle)
2149 struct _WapiHandle_file *file_handle;
2156 case STD_INPUT_HANDLE:
2161 case STD_OUTPUT_HANDLE:
2166 case STD_ERROR_HANDLE:
2172 DEBUG("%s: unknown standard handle type", __func__);
2174 SetLastError (ERROR_INVALID_PARAMETER);
2175 return(INVALID_HANDLE_VALUE);
2178 handle = GINT_TO_POINTER (fd);
2180 thr_ret = mono_mutex_lock (&stdhandle_mutex);
2181 g_assert (thr_ret == 0);
2183 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2184 (gpointer *)&file_handle);
2186 /* Need to create this console handle */
2187 handle = _wapi_stdhandle_create (fd, name);
2189 if (handle == INVALID_HANDLE_VALUE) {
2190 SetLastError (ERROR_NO_MORE_FILES);
2194 /* Add a reference to this handle */
2195 _wapi_handle_ref (handle);
2199 thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2200 g_assert (thr_ret == 0);
2207 * @handle: The file handle to read from. The handle must have
2208 * %GENERIC_READ access.
2209 * @buffer: The buffer to store read data in
2210 * @numbytes: The maximum number of bytes to read
2211 * @bytesread: The actual number of bytes read is stored here. This
2212 * value can be zero if the handle is positioned at the end of the
2214 * @overlapped: points to a required %WapiOverlapped structure if
2215 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2218 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2219 * function reads up to @numbytes bytes from the file from the current
2220 * file position, and stores them in @buffer. If there are not enough
2221 * bytes left in the file, just the amount available will be read.
2222 * The actual number of bytes read is stored in @bytesread.
2224 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2225 * file position is ignored and the read position is taken from data
2226 * in the @overlapped structure.
2228 * Return value: %TRUE if the read succeeds (even if no bytes were
2229 * read due to an attempt to read past the end of the file), %FALSE on
2232 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2233 guint32 *bytesread, WapiOverlapped *overlapped)
2235 WapiHandleType type;
2237 type = _wapi_handle_type (handle);
2239 if(io_ops[type].readfile==NULL) {
2240 SetLastError (ERROR_INVALID_HANDLE);
2244 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2250 * @handle: The file handle to write to. The handle must have
2251 * %GENERIC_WRITE access.
2252 * @buffer: The buffer to read data from.
2253 * @numbytes: The maximum number of bytes to write.
2254 * @byteswritten: The actual number of bytes written is stored here.
2255 * If the handle is positioned at the file end, the length of the file
2256 * is extended. This parameter may be %NULL.
2257 * @overlapped: points to a required %WapiOverlapped structure if
2258 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2261 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2262 * function writes up to @numbytes bytes from @buffer to the file at
2263 * the current file position. If @handle is positioned at the end of
2264 * the file, the file is extended. The actual number of bytes written
2265 * is stored in @byteswritten.
2267 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2268 * file position is ignored and the write position is taken from data
2269 * in the @overlapped structure.
2271 * Return value: %TRUE if the write succeeds, %FALSE on error.
2273 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2274 guint32 *byteswritten, WapiOverlapped *overlapped)
2276 WapiHandleType type;
2278 type = _wapi_handle_type (handle);
2280 if(io_ops[type].writefile==NULL) {
2281 SetLastError (ERROR_INVALID_HANDLE);
2285 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2291 * @handle: Handle to open file. The handle must have
2292 * %GENERIC_WRITE access.
2294 * Flushes buffers of the file and causes all unwritten data to
2297 * Return value: %TRUE on success, %FALSE otherwise.
2299 gboolean FlushFileBuffers(gpointer handle)
2301 WapiHandleType type;
2303 type = _wapi_handle_type (handle);
2305 if(io_ops[type].flushfile==NULL) {
2306 SetLastError (ERROR_INVALID_HANDLE);
2310 return(io_ops[type].flushfile (handle));
2315 * @handle: The file handle to set. The handle must have
2316 * %GENERIC_WRITE access.
2318 * Moves the end-of-file position to the current position of the file
2319 * pointer. This function is used to truncate or extend a file.
2321 * Return value: %TRUE on success, %FALSE otherwise.
2323 gboolean SetEndOfFile(gpointer handle)
2325 WapiHandleType type;
2327 type = _wapi_handle_type (handle);
2329 if (io_ops[type].setendoffile == NULL) {
2330 SetLastError (ERROR_INVALID_HANDLE);
2334 return(io_ops[type].setendoffile (handle));
2339 * @handle: The file handle to set. The handle must have
2340 * %GENERIC_READ or %GENERIC_WRITE access.
2341 * @movedistance: Low 32 bits of a signed value that specifies the
2342 * number of bytes to move the file pointer.
2343 * @highmovedistance: Pointer to the high 32 bits of a signed value
2344 * that specifies the number of bytes to move the file pointer, or
2346 * @method: The starting point for the file pointer move.
2348 * Sets the file pointer of an open file.
2350 * The distance to move the file pointer is calculated from
2351 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2352 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2353 * is the low 32 bits and @highmovedistance a pointer to the high 32
2354 * bits of a 64 bit signed value. A positive distance moves the file
2355 * pointer forward from the position specified by @method; a negative
2356 * distance moves the file pointer backward.
2358 * If the library is compiled without large file support,
2359 * @highmovedistance is ignored and its value is set to zero on a
2360 * successful return.
2362 * Return value: On success, the low 32 bits of the new file pointer.
2363 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2364 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2366 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2367 gint32 *highmovedistance, WapiSeekMethod method)
2369 WapiHandleType type;
2371 type = _wapi_handle_type (handle);
2373 if (io_ops[type].seek == NULL) {
2374 SetLastError (ERROR_INVALID_HANDLE);
2375 return(INVALID_SET_FILE_POINTER);
2378 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2384 * @handle: The file handle to test.
2386 * Finds the type of file @handle.
2388 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2389 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2390 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2391 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2393 WapiFileType GetFileType(gpointer handle)
2395 WapiHandleType type;
2397 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2398 SetLastError (ERROR_INVALID_HANDLE);
2399 return(FILE_TYPE_UNKNOWN);
2402 type = _wapi_handle_type (handle);
2404 if (io_ops[type].getfiletype == NULL) {
2405 SetLastError (ERROR_INVALID_HANDLE);
2406 return(FILE_TYPE_UNKNOWN);
2409 return(io_ops[type].getfiletype ());
2414 * @handle: The file handle to query. The handle must have
2415 * %GENERIC_READ or %GENERIC_WRITE access.
2416 * @highsize: If non-%NULL, the high 32 bits of the file size are
2419 * Retrieves the size of the file @handle.
2421 * If the library is compiled without large file support, @highsize
2422 * has its value set to zero on a successful return.
2424 * Return value: On success, the low 32 bits of the file size. If
2425 * @highsize is non-%NULL then the high 32 bits of the file size are
2426 * stored here. On failure %INVALID_FILE_SIZE is returned.
2428 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2430 WapiHandleType type;
2432 type = _wapi_handle_type (handle);
2434 if (io_ops[type].getfilesize == NULL) {
2435 SetLastError (ERROR_INVALID_HANDLE);
2436 return(INVALID_FILE_SIZE);
2439 return(io_ops[type].getfilesize (handle, highsize));
2444 * @handle: The file handle to query. The handle must have
2445 * %GENERIC_READ access.
2446 * @create_time: Points to a %WapiFileTime structure to receive the
2447 * number of ticks since the epoch that file was created. May be
2449 * @last_access: Points to a %WapiFileTime structure to receive the
2450 * number of ticks since the epoch when file was last accessed. May be
2452 * @last_write: Points to a %WapiFileTime structure to receive the
2453 * number of ticks since the epoch when file was last written to. May
2456 * Finds the number of ticks since the epoch that the file referenced
2457 * by @handle was created, last accessed and last modified. A tick is
2458 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2461 * Create time isn't recorded on POSIX file systems or reported by
2462 * stat(2), so that time is guessed by returning the oldest of the
2465 * Return value: %TRUE on success, %FALSE otherwise.
2467 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2468 WapiFileTime *last_access, WapiFileTime *last_write)
2470 WapiHandleType type;
2472 type = _wapi_handle_type (handle);
2474 if (io_ops[type].getfiletime == NULL) {
2475 SetLastError (ERROR_INVALID_HANDLE);
2479 return(io_ops[type].getfiletime (handle, create_time, last_access,
2485 * @handle: The file handle to set. The handle must have
2486 * %GENERIC_WRITE access.
2487 * @create_time: Points to a %WapiFileTime structure that contains the
2488 * number of ticks since the epoch that the file was created. May be
2490 * @last_access: Points to a %WapiFileTime structure that contains the
2491 * number of ticks since the epoch when the file was last accessed.
2493 * @last_write: Points to a %WapiFileTime structure that contains the
2494 * number of ticks since the epoch when the file was last written to.
2497 * Sets the number of ticks since the epoch that the file referenced
2498 * by @handle was created, last accessed or last modified. A tick is
2499 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2502 * Create time isn't recorded on POSIX file systems, and is ignored.
2504 * Return value: %TRUE on success, %FALSE otherwise.
2506 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2507 const WapiFileTime *last_access,
2508 const WapiFileTime *last_write)
2510 WapiHandleType type;
2512 type = _wapi_handle_type (handle);
2514 if (io_ops[type].setfiletime == NULL) {
2515 SetLastError (ERROR_INVALID_HANDLE);
2519 return(io_ops[type].setfiletime (handle, create_time, last_access,
2523 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2524 * January 1 1601 GMT
2527 #define TICKS_PER_MILLISECOND 10000L
2528 #define TICKS_PER_SECOND 10000000L
2529 #define TICKS_PER_MINUTE 600000000L
2530 #define TICKS_PER_HOUR 36000000000LL
2531 #define TICKS_PER_DAY 864000000000LL
2533 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2535 static const guint16 mon_yday[2][13]={
2536 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2537 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2541 * FileTimeToSystemTime:
2542 * @file_time: Points to a %WapiFileTime structure that contains the
2543 * number of ticks to convert.
2544 * @system_time: Points to a %WapiSystemTime structure to receive the
2547 * Converts a tick count into broken-out time values.
2549 * Return value: %TRUE on success, %FALSE otherwise.
2551 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2552 WapiSystemTime *system_time)
2554 gint64 file_ticks, totaldays, rem, y;
2557 if(system_time==NULL) {
2558 DEBUG("%s: system_time NULL", __func__);
2560 SetLastError (ERROR_INVALID_PARAMETER);
2564 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2565 file_time->dwLowDateTime;
2567 /* Really compares if file_ticks>=0x8000000000000000
2568 * (LLONG_MAX+1) but we're working with a signed value for the
2569 * year and day calculation to work later
2572 DEBUG("%s: file_time too big", __func__);
2574 SetLastError (ERROR_INVALID_PARAMETER);
2578 totaldays=(file_ticks / TICKS_PER_DAY);
2579 rem = file_ticks % TICKS_PER_DAY;
2580 DEBUG("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2582 system_time->wHour=rem/TICKS_PER_HOUR;
2583 rem %= TICKS_PER_HOUR;
2584 DEBUG("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2586 system_time->wMinute = rem / TICKS_PER_MINUTE;
2587 rem %= TICKS_PER_MINUTE;
2588 DEBUG("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2591 system_time->wSecond = rem / TICKS_PER_SECOND;
2592 rem %= TICKS_PER_SECOND;
2593 DEBUG("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2596 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2597 DEBUG("%s: Milliseconds: %d", __func__,
2598 system_time->wMilliseconds);
2600 /* January 1, 1601 was a Monday, according to Emacs calendar */
2601 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2602 DEBUG("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2604 /* This algorithm to find year and month given days from epoch
2609 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2610 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2612 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2613 /* Guess a corrected year, assuming 365 days per year */
2614 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2615 DEBUG("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2618 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2619 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2621 /* Adjust days and y to match the guessed year. */
2622 totaldays -= ((yg - y) * 365
2623 + LEAPS_THRU_END_OF (yg - 1)
2624 - LEAPS_THRU_END_OF (y - 1));
2625 DEBUG("%s: totaldays: %lld", __func__, totaldays);
2627 DEBUG("%s: y: %lld", __func__, y);
2630 system_time->wYear = y;
2631 DEBUG("%s: Year: %d", __func__, system_time->wYear);
2633 ip = mon_yday[isleap(y)];
2635 for(y=11; totaldays < ip[y]; --y) {
2639 DEBUG("%s: totaldays: %lld", __func__, totaldays);
2641 system_time->wMonth = y + 1;
2642 DEBUG("%s: Month: %d", __func__, system_time->wMonth);
2644 system_time->wDay = totaldays + 1;
2645 DEBUG("%s: Day: %d", __func__, system_time->wDay);
2650 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2652 struct _WapiHandle_find find_handle = {0};
2654 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2657 if (pattern == NULL) {
2658 DEBUG ("%s: pattern is NULL", __func__);
2660 SetLastError (ERROR_PATH_NOT_FOUND);
2661 return(INVALID_HANDLE_VALUE);
2664 utf8_pattern = mono_unicode_to_external (pattern);
2665 if (utf8_pattern == NULL) {
2666 DEBUG ("%s: unicode conversion returned NULL", __func__);
2668 SetLastError (ERROR_INVALID_NAME);
2669 return(INVALID_HANDLE_VALUE);
2672 DEBUG ("%s: looking for [%s]", __func__, utf8_pattern);
2674 /* Figure out which bit of the pattern is the directory */
2675 dir_part = _wapi_dirname (utf8_pattern);
2676 entry_part = _wapi_basename (utf8_pattern);
2679 /* Don't do this check for now, it breaks if directories
2680 * really do have metachars in their names (see bug 58116).
2681 * FIXME: Figure out a better solution to keep some checks...
2683 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2684 SetLastError (ERROR_INVALID_NAME);
2686 g_free (entry_part);
2687 g_free (utf8_pattern);
2688 return(INVALID_HANDLE_VALUE);
2692 /* The pattern can specify a directory or a set of files.
2694 * The pattern can have wildcard characters ? and *, but only
2695 * in the section after the last directory delimiter. (Return
2696 * ERROR_INVALID_NAME if there are wildcards in earlier path
2697 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2698 * means "match one character", "??" seems to mean "match one
2699 * or two characters", "???" seems to mean "match one, two or
2700 * three characters", etc. Windows will also try and match
2701 * the mangled "short name" of files, so 8 character patterns
2702 * with wildcards will show some surprising results.
2704 * All the written documentation I can find says that '?'
2705 * should only match one character, and doesn't mention '??',
2706 * '???' etc. I'm going to assume that the strict behaviour
2707 * (ie '???' means three and only three characters) is the
2708 * correct one, because that lets me use fnmatch(3) rather
2709 * than mess around with regexes.
2712 find_handle.namelist = NULL;
2713 result = _wapi_io_scandir (dir_part, entry_part,
2714 &find_handle.namelist);
2717 /* No files, which windows seems to call
2720 SetLastError (ERROR_FILE_NOT_FOUND);
2721 g_free (utf8_pattern);
2722 g_free (entry_part);
2724 return (INVALID_HANDLE_VALUE);
2728 #ifdef DEBUG_ENABLED
2729 gint errnum = errno;
2731 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2732 DEBUG ("%s: scandir error: %s", __func__,
2733 g_strerror (errnum));
2734 g_free (utf8_pattern);
2735 g_free (entry_part);
2737 return (INVALID_HANDLE_VALUE);
2740 g_free (utf8_pattern);
2741 g_free (entry_part);
2743 DEBUG ("%s: Got %d matches", __func__, result);
2745 find_handle.dir_part = dir_part;
2746 find_handle.num = result;
2747 find_handle.count = 0;
2749 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2750 if (handle == _WAPI_HANDLE_INVALID) {
2751 g_warning ("%s: error creating find handle", __func__);
2753 g_free (entry_part);
2754 g_free (utf8_pattern);
2755 SetLastError (ERROR_GEN_FAILURE);
2757 return(INVALID_HANDLE_VALUE);
2760 if (handle != INVALID_HANDLE_VALUE &&
2761 !FindNextFile (handle, find_data)) {
2763 SetLastError (ERROR_NO_MORE_FILES);
2764 handle = INVALID_HANDLE_VALUE;
2770 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2772 struct _WapiHandle_find *find_handle;
2774 struct stat buf, linkbuf;
2777 gchar *utf8_filename, *utf8_basename;
2778 gunichar2 *utf16_basename;
2782 gboolean ret = FALSE;
2784 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2785 (gpointer *)&find_handle);
2787 g_warning ("%s: error looking up find handle %p", __func__,
2789 SetLastError (ERROR_INVALID_HANDLE);
2793 thr_ret = _wapi_handle_lock_handle (handle);
2794 g_assert (thr_ret == 0);
2797 if (find_handle->count >= find_handle->num) {
2798 SetLastError (ERROR_NO_MORE_FILES);
2802 /* stat next match */
2804 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2806 result = _wapi_stat (filename, &buf);
2807 if (result == -1 && errno == ENOENT) {
2808 /* Might be a dangling symlink */
2809 result = _wapi_lstat (filename, &buf);
2813 DEBUG ("%s: stat failed: %s", __func__, filename);
2819 #ifndef __native_client__
2820 result = _wapi_lstat (filename, &linkbuf);
2822 DEBUG ("%s: lstat failed: %s", __func__, filename);
2829 utf8_filename = mono_utf8_from_external (filename);
2830 if (utf8_filename == NULL) {
2831 /* We couldn't turn this filename into utf8 (eg the
2832 * encoding of the name wasn't convertible), so just
2835 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2842 DEBUG ("%s: Found [%s]", __func__, utf8_filename);
2844 /* fill data block */
2846 if (buf.st_mtime < buf.st_ctime)
2847 create_time = buf.st_mtime;
2849 create_time = buf.st_ctime;
2851 #ifdef __native_client__
2852 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, NULL);
2854 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2857 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2858 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2859 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2861 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2862 find_data->nFileSizeHigh = 0;
2863 find_data->nFileSizeLow = 0;
2865 find_data->nFileSizeHigh = buf.st_size >> 32;
2866 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2869 find_data->dwReserved0 = 0;
2870 find_data->dwReserved1 = 0;
2872 utf8_basename = _wapi_basename (utf8_filename);
2873 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2875 if(utf16_basename==NULL) {
2876 g_free (utf8_basename);
2877 g_free (utf8_filename);
2882 /* utf16 is 2 * utf8 */
2885 memset (find_data->cFileName, '\0', (MAX_PATH*2));
2887 /* Truncating a utf16 string like this might leave the last
2890 memcpy (find_data->cFileName, utf16_basename,
2891 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
2893 find_data->cAlternateFileName [0] = 0; /* not used */
2895 g_free (utf8_basename);
2896 g_free (utf8_filename);
2897 g_free (utf16_basename);
2900 thr_ret = _wapi_handle_unlock_handle (handle);
2901 g_assert (thr_ret == 0);
2908 * @wapi_handle: the find handle to close.
2910 * Closes find handle @wapi_handle
2912 * Return value: %TRUE on success, %FALSE otherwise.
2914 gboolean FindClose (gpointer handle)
2916 struct _WapiHandle_find *find_handle;
2920 if (handle == NULL) {
2921 SetLastError (ERROR_INVALID_HANDLE);
2925 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2926 (gpointer *)&find_handle);
2928 g_warning ("%s: error looking up find handle %p", __func__,
2930 SetLastError (ERROR_INVALID_HANDLE);
2934 thr_ret = _wapi_handle_lock_handle (handle);
2935 g_assert (thr_ret == 0);
2937 g_strfreev (find_handle->namelist);
2938 g_free (find_handle->dir_part);
2940 thr_ret = _wapi_handle_unlock_handle (handle);
2941 g_assert (thr_ret == 0);
2943 _wapi_handle_unref (handle);
2950 * @name: a pointer to a NULL-terminated unicode string, that names
2951 * the directory to be created.
2952 * @security: ignored for now
2954 * Creates directory @name
2956 * Return value: %TRUE on success, %FALSE otherwise.
2958 gboolean CreateDirectory (const gunichar2 *name,
2959 WapiSecurityAttributes *security)
2965 DEBUG("%s: name is NULL", __func__);
2967 SetLastError (ERROR_INVALID_NAME);
2971 utf8_name = mono_unicode_to_external (name);
2972 if (utf8_name == NULL) {
2973 DEBUG ("%s: unicode conversion returned NULL", __func__);
2975 SetLastError (ERROR_INVALID_NAME);
2979 result = _wapi_mkdir (utf8_name, 0777);
2986 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2993 * @name: a pointer to a NULL-terminated unicode string, that names
2994 * the directory to be removed.
2996 * Removes directory @name
2998 * Return value: %TRUE on success, %FALSE otherwise.
3000 gboolean RemoveDirectory (const gunichar2 *name)
3006 DEBUG("%s: name is NULL", __func__);
3008 SetLastError (ERROR_INVALID_NAME);
3012 utf8_name = mono_unicode_to_external (name);
3013 if (utf8_name == NULL) {
3014 DEBUG ("%s: unicode conversion returned NULL", __func__);
3016 SetLastError (ERROR_INVALID_NAME);
3020 result = _wapi_rmdir (utf8_name);
3022 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3033 * GetFileAttributes:
3034 * @name: a pointer to a NULL-terminated unicode filename.
3036 * Gets the attributes for @name;
3038 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3040 guint32 GetFileAttributes (const gunichar2 *name)
3043 struct stat buf, linkbuf;
3048 DEBUG("%s: name is NULL", __func__);
3050 SetLastError (ERROR_INVALID_NAME);
3054 utf8_name = mono_unicode_to_external (name);
3055 if (utf8_name == NULL) {
3056 DEBUG ("%s: unicode conversion returned NULL", __func__);
3058 SetLastError (ERROR_INVALID_PARAMETER);
3059 return (INVALID_FILE_ATTRIBUTES);
3062 result = _wapi_stat (utf8_name, &buf);
3063 if (result == -1 && errno == ENOENT) {
3064 /* Might be a dangling symlink... */
3065 result = _wapi_lstat (utf8_name, &buf);
3069 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3071 return (INVALID_FILE_ATTRIBUTES);
3074 #ifndef __native_client__
3075 result = _wapi_lstat (utf8_name, &linkbuf);
3077 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3079 return (INVALID_FILE_ATTRIBUTES);
3083 #ifdef __native_client__
3084 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, NULL);
3086 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3095 * GetFileAttributesEx:
3096 * @name: a pointer to a NULL-terminated unicode filename.
3097 * @level: must be GetFileExInfoStandard
3098 * @info: pointer to a WapiFileAttributesData structure
3100 * Gets attributes, size and filetimes for @name;
3102 * Return value: %TRUE on success, %FALSE on failure
3104 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3107 WapiFileAttributesData *data;
3109 struct stat buf, linkbuf;
3113 if (level != GetFileExInfoStandard) {
3114 DEBUG ("%s: info level %d not supported.", __func__,
3117 SetLastError (ERROR_INVALID_PARAMETER);
3122 DEBUG("%s: name is NULL", __func__);
3124 SetLastError (ERROR_INVALID_NAME);
3128 utf8_name = mono_unicode_to_external (name);
3129 if (utf8_name == NULL) {
3130 DEBUG ("%s: unicode conversion returned NULL", __func__);
3132 SetLastError (ERROR_INVALID_PARAMETER);
3136 result = _wapi_stat (utf8_name, &buf);
3137 if (result == -1 && errno == ENOENT) {
3138 /* Might be a dangling symlink... */
3139 result = _wapi_lstat (utf8_name, &buf);
3143 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3148 result = _wapi_lstat (utf8_name, &linkbuf);
3150 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3155 /* fill data block */
3157 data = (WapiFileAttributesData *)info;
3159 if (buf.st_mtime < buf.st_ctime)
3160 create_time = buf.st_mtime;
3162 create_time = buf.st_ctime;
3164 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3170 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3171 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3172 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3174 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3175 data->nFileSizeHigh = 0;
3176 data->nFileSizeLow = 0;
3179 data->nFileSizeHigh = buf.st_size >> 32;
3180 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3188 * @name: name of file
3189 * @attrs: attributes to set
3191 * Changes the attributes on a named file.
3193 * Return value: %TRUE on success, %FALSE on failure.
3195 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3197 /* FIXME: think of something clever to do on unix */
3203 * Currently we only handle one *internal* case, with a value that is
3204 * not standard: 0x80000000, which means `set executable bit'
3208 DEBUG("%s: name is NULL", __func__);
3210 SetLastError (ERROR_INVALID_NAME);
3214 utf8_name = mono_unicode_to_external (name);
3215 if (utf8_name == NULL) {
3216 DEBUG ("%s: unicode conversion returned NULL", __func__);
3218 SetLastError (ERROR_INVALID_NAME);
3222 result = _wapi_stat (utf8_name, &buf);
3223 if (result == -1 && errno == ENOENT) {
3224 /* Might be a dangling symlink... */
3225 result = _wapi_lstat (utf8_name, &buf);
3229 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3234 /* Contrary to the documentation, ms allows NORMAL to be
3235 * specified along with other attributes, so dont bother to
3236 * catch that case here.
3238 if (attrs & FILE_ATTRIBUTE_READONLY) {
3239 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWUSR | S_IWOTH | S_IWGRP));
3241 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWUSR);
3244 /* Ignore the other attributes for now */
3246 if (attrs & 0x80000000){
3247 mode_t exec_mask = 0;
3249 if ((buf.st_mode & S_IRUSR) != 0)
3250 exec_mask |= S_IXUSR;
3252 if ((buf.st_mode & S_IRGRP) != 0)
3253 exec_mask |= S_IXGRP;
3255 if ((buf.st_mode & S_IROTH) != 0)
3256 exec_mask |= S_IXOTH;
3258 result = chmod (utf8_name, buf.st_mode | exec_mask);
3260 /* Don't bother to reset executable (might need to change this
3270 * GetCurrentDirectory
3271 * @length: size of the buffer
3272 * @buffer: pointer to buffer that recieves path
3274 * Retrieves the current directory for the current process.
3276 * Return value: number of characters in buffer on success, zero on failure
3278 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3280 gunichar2 *utf16_path;
3284 #ifdef __native_client__
3285 gchar *path = g_get_current_dir ();
3286 if (length < strlen(path) + 1 || path == NULL)
3288 memcpy (buffer, path, strlen(path) + 1);
3290 if (getcwd ((char*)buffer, length) == NULL) {
3291 if (errno == ERANGE) { /*buffer length is not big enough */
3292 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*/
3295 utf16_path = mono_unicode_from_external (path, &bytes);
3296 g_free (utf16_path);
3300 _wapi_set_last_error_from_errno ();
3305 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3306 count = (bytes/2)+1;
3307 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3309 /* Add the terminator */
3310 memset (buffer, '\0', bytes+2);
3311 memcpy (buffer, utf16_path, bytes);
3313 g_free (utf16_path);
3319 * SetCurrentDirectory
3320 * @path: path to new directory
3322 * Changes the directory path for the current process.
3324 * Return value: %TRUE on success, %FALSE on failure.
3326 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3332 SetLastError (ERROR_INVALID_PARAMETER);
3336 utf8_path = mono_unicode_to_external (path);
3337 if (_wapi_chdir (utf8_path) != 0) {
3338 _wapi_set_last_error_from_errno ();
3348 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3349 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3351 struct _WapiHandle_file pipe_read_handle = {0};
3352 struct _WapiHandle_file pipe_write_handle = {0};
3353 gpointer read_handle;
3354 gpointer write_handle;
3358 mono_once (&io_ops_once, io_ops_init);
3360 DEBUG ("%s: Creating pipe", __func__);
3364 DEBUG ("%s: Error creating pipe: %s", __func__,
3367 _wapi_set_last_error_from_errno ();
3371 if (filedes[0] >= _wapi_fd_reserve ||
3372 filedes[1] >= _wapi_fd_reserve) {
3373 DEBUG ("%s: File descriptor is too big", __func__);
3375 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3383 /* filedes[0] is open for reading, filedes[1] for writing */
3385 pipe_read_handle.fd = filedes [0];
3386 pipe_read_handle.fileaccess = GENERIC_READ;
3387 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3389 if (read_handle == _WAPI_HANDLE_INVALID) {
3390 g_warning ("%s: error creating pipe read handle", __func__);
3393 SetLastError (ERROR_GEN_FAILURE);
3398 pipe_write_handle.fd = filedes [1];
3399 pipe_write_handle.fileaccess = GENERIC_WRITE;
3400 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3401 &pipe_write_handle);
3402 if (write_handle == _WAPI_HANDLE_INVALID) {
3403 g_warning ("%s: error creating pipe write handle", __func__);
3404 _wapi_handle_unref (read_handle);
3408 SetLastError (ERROR_GEN_FAILURE);
3413 *readpipe = read_handle;
3414 *writepipe = write_handle;
3416 DEBUG ("%s: Returning pipe: read handle %p, write handle %p",
3417 __func__, read_handle, write_handle);
3422 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3424 gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3425 gunichar2 *tmpdir16=NULL;
3430 if(tmpdir[strlen (tmpdir)]!='/') {
3432 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3435 tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3436 if(tmpdir16==NULL) {
3443 DEBUG ("%s: Size %d smaller than needed (%ld)",
3444 __func__, len, dirlen+1);
3448 /* Add the terminator */
3449 memset (buf, '\0', bytes+2);
3450 memcpy (buf, tmpdir16, bytes);
3456 if(tmpdir16!=NULL) {
3464 #ifdef HAVE_GETFSSTAT
3465 /* Darwin has getfsstat */
3466 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3468 struct statfs *stats;
3471 glong length, total = 0;
3473 n = getfsstat (NULL, 0, MNT_NOWAIT);
3476 size = n * sizeof (struct statfs);
3477 stats = (struct statfs *) g_malloc (size);
3480 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3484 for (i = 0; i < n; i++){
3485 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3486 if (total + length < len){
3487 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3488 buf [total+length] = 0;
3491 total += length + 1;
3500 /* In-place octal sequence replacement */
3502 unescape_octal (gchar *str)
3511 while (*rptr != '\0') {
3512 if (*rptr == '\\') {
3515 c = (*(rptr++) - '0') << 6;
3516 c += (*(rptr++) - '0') << 3;
3517 c += *(rptr++) - '0';
3519 } else if (wptr != rptr) {
3527 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3530 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3531 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3532 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3537 guint32 buffer_index;
3538 guint32 mountpoint_index;
3539 guint32 field_number;
3540 guint32 allocated_size;
3541 guint32 fsname_index;
3542 guint32 fstype_index;
3543 gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3544 gchar *mountpoint_allocated;
3545 gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3546 gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3547 gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3550 gboolean check_mount_source;
3551 } LinuxMountInfoParseState;
3553 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3554 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3555 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3556 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3558 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3562 LinuxMountInfoParseState state;
3563 gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3565 memset (buf, 0, len * sizeof (gunichar2));
3566 fd = open ("/proc/self/mountinfo", O_RDONLY);
3568 parser = GetLogicalDriveStrings_MountInfo;
3570 fd = open ("/proc/mounts", O_RDONLY);
3572 parser = GetLogicalDriveStrings_Mounts;
3576 ret = GetLogicalDriveStrings_Mtab (len, buf);
3580 memset (&state, 0, sizeof (LinuxMountInfoParseState));
3581 state.field_number = 1;
3582 state.delimiter = ' ';
3584 while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3585 state.buffer_index = 0;
3587 while ((*parser)(len, buf, &state)) {
3588 if (state.buffer [state.buffer_index] == '\n') {
3589 gboolean quit = add_drive_string (len, buf, &state);
3590 state.field_number = 1;
3591 state.buffer_index++;
3592 if (state.mountpoint_allocated) {
3593 g_free (state.mountpoint_allocated);
3594 state.mountpoint_allocated = NULL;
3611 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3615 if (state->field_number == 1)
3616 state->check_mount_source = TRUE;
3618 while (state->buffer_index < (guint32)state->nbytes) {
3619 if (state->buffer [state->buffer_index] == state->delimiter) {
3620 state->field_number++;
3621 switch (state->field_number) {
3623 state->mountpoint_index = 0;
3627 if (state->mountpoint_allocated)
3628 state->mountpoint_allocated [state->mountpoint_index] = 0;
3630 state->mountpoint [state->mountpoint_index] = 0;
3634 ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3636 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3638 state->buffer_index = state->nbytes;
3641 state->buffer_index++;
3643 } else if (state->buffer [state->buffer_index] == '\n')
3646 switch (state->field_number) {
3648 if (state->check_mount_source) {
3649 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3650 /* We can ignore the rest, it's a device
3652 state->check_mount_source = FALSE;
3653 state->fsname [state->fsname_index++] = '/';
3656 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3657 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3662 append_to_mountpoint (state);
3666 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3667 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3671 state->buffer_index++;
3677 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3679 while (state->buffer_index < (guint32)state->nbytes) {
3680 if (state->buffer [state->buffer_index] == state->delimiter) {
3681 state->field_number++;
3682 switch (state->field_number) {
3684 state->mountpoint_index = 0;
3688 if (state->mountpoint_allocated)
3689 state->mountpoint_allocated [state->mountpoint_index] = 0;
3691 state->mountpoint [state->mountpoint_index] = 0;
3695 state->delimiter = '-';
3699 state->delimiter = ' ';
3703 state->check_mount_source = TRUE;
3706 state->buffer_index++;
3708 } else if (state->buffer [state->buffer_index] == '\n')
3711 switch (state->field_number) {
3713 append_to_mountpoint (state);
3717 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3718 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3722 if (state->check_mount_source) {
3723 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3724 /* We can ignore the rest, it's a device
3726 state->check_mount_source = FALSE;
3727 state->fsname [state->fsname_index++] = '/';
3730 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3731 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3736 state->buffer_index++;
3743 append_to_mountpoint (LinuxMountInfoParseState *state)
3745 gchar ch = state->buffer [state->buffer_index];
3746 if (state->mountpoint_allocated) {
3747 if (state->mountpoint_index >= state->allocated_size) {
3748 guint32 newsize = (state->allocated_size << 1) + 1;
3749 gchar *newbuf = g_malloc0 (newsize * sizeof (gchar));
3751 memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3752 g_free (state->mountpoint_allocated);
3753 state->mountpoint_allocated = newbuf;
3754 state->allocated_size = newsize;
3756 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3758 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3759 state->allocated_size = (state->mountpoint_index << 1) + 1;
3760 state->mountpoint_allocated = g_malloc0 (state->allocated_size * sizeof (gchar));
3761 memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3762 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3764 state->mountpoint [state->mountpoint_index++] = ch;
3769 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3771 gboolean quit = FALSE;
3772 gboolean ignore_entry;
3774 if (state->fsname_index == 1 && state->fsname [0] == '/')
3775 ignore_entry = FALSE;
3776 else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0)
3777 ignore_entry = TRUE;
3778 else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3779 /* Ignore GNOME's gvfs */
3780 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3781 ignore_entry = TRUE;
3783 ignore_entry = FALSE;
3784 } else if (state->fstype_index == 3 && memcmp ("nfs", state->fstype, state->fstype_index) == 0)
3785 ignore_entry = FALSE;
3787 ignore_entry = TRUE;
3789 if (!ignore_entry) {
3792 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3794 unescape_octal (mountpoint);
3795 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3796 if (state->total + length + 1 > len) {
3798 state->total = len * 2;
3801 memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3802 state->total += length;
3806 state->fsname_index = 0;
3807 state->fstype_index = 0;
3813 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3815 return GetLogicalDriveStrings_Mtab (len, buf);
3819 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3822 gunichar2 *ptr, *dir;
3823 glong length, total = 0;
3827 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3832 /* Sigh, mntent and friends don't work well.
3833 * It stops on the first line that doesn't begin with a '/'.
3834 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3835 fp = fopen ("/etc/mtab", "rt");
3837 fp = fopen ("/etc/mnttab", "rt");
3843 while (fgets (buffer, 512, fp) != NULL) {
3847 splitted = g_strsplit (buffer, " ", 0);
3848 if (!*splitted || !*(splitted + 1)) {
3849 g_strfreev (splitted);
3853 unescape_octal (*(splitted + 1));
3854 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3855 g_strfreev (splitted);
3856 if (total + length + 1 > len) {
3859 return len * 2; /* guess */
3862 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3864 total += length + 1;
3869 /* Commented out, does not work with my mtab!!! - Gonz */
3870 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3874 gunichar2 *ptr, *dir;
3875 glong len, total = 0;
3878 fp = setmntent ("/etc/mtab", "rt");
3880 fp = setmntent ("/etc/mnttab", "rt");
3886 while ((mnt = getmntent (fp)) != NULL) {
3887 g_print ("GOT %s\n", mnt->mnt_dir);
3888 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3889 if (total + len + 1 > len) {
3890 return len * 2; /* guess */
3893 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3905 #if defined(HAVE_STATVFS) || defined(HAVE_STATFS)
3906 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3907 WapiULargeInteger *total_number_of_bytes,
3908 WapiULargeInteger *total_number_of_free_bytes)
3911 struct statvfs fsstat;
3912 #elif defined(HAVE_STATFS)
3913 struct statfs fsstat;
3915 gboolean isreadonly;
3916 gchar *utf8_path_name;
3918 unsigned long block_size;
3920 if (path_name == NULL) {
3921 utf8_path_name = g_strdup (g_get_current_dir());
3922 if (utf8_path_name == NULL) {
3923 SetLastError (ERROR_DIRECTORY);
3928 utf8_path_name = mono_unicode_to_external (path_name);
3929 if (utf8_path_name == NULL) {
3930 DEBUG("%s: unicode conversion returned NULL", __func__);
3932 SetLastError (ERROR_INVALID_NAME);
3939 ret = statvfs (utf8_path_name, &fsstat);
3940 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
3941 block_size = fsstat.f_frsize;
3942 #elif defined(HAVE_STATFS)
3943 ret = statfs (utf8_path_name, &fsstat);
3944 #if defined (MNT_RDONLY)
3945 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
3946 #elif defined (MS_RDONLY)
3947 isreadonly = ((fsstat.f_flags & MS_RDONLY) == MS_RDONLY);
3949 block_size = fsstat.f_bsize;
3951 } while(ret == -1 && errno == EINTR);
3953 g_free(utf8_path_name);
3956 _wapi_set_last_error_from_errno ();
3957 DEBUG ("%s: statvfs failed: %s", __func__, strerror (errno));
3961 /* total number of free bytes for non-root */
3962 if (free_bytes_avail != NULL) {
3964 free_bytes_avail->QuadPart = 0;
3967 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
3971 /* total number of bytes available for non-root */
3972 if (total_number_of_bytes != NULL) {
3973 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
3976 /* total number of bytes available for root */
3977 if (total_number_of_free_bytes != NULL) {
3979 total_number_of_free_bytes->QuadPart = 0;
3982 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
3989 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3990 WapiULargeInteger *total_number_of_bytes,
3991 WapiULargeInteger *total_number_of_free_bytes)
3993 if (free_bytes_avail != NULL) {
3994 free_bytes_avail->QuadPart = (guint64) -1;
3997 if (total_number_of_bytes != NULL) {
3998 total_number_of_bytes->QuadPart = (guint64) -1;
4001 if (total_number_of_free_bytes != NULL) {
4002 total_number_of_free_bytes->QuadPart = (guint64) -1;
4010 * General Unix support
4015 const long fstypeid;
4017 const gchar* fstype;
4020 static _wapi_drive_type _wapi_drive_types[] = {
4022 { DRIVE_REMOTE, "afp" },
4023 { DRIVE_REMOTE, "autofs" },
4024 { DRIVE_CDROM, "cddafs" },
4025 { DRIVE_CDROM, "cd9660" },
4026 { DRIVE_RAMDISK, "devfs" },
4027 { DRIVE_FIXED, "exfat" },
4028 { DRIVE_RAMDISK, "fdesc" },
4029 { DRIVE_REMOTE, "ftp" },
4030 { DRIVE_FIXED, "hfs" },
4031 { DRIVE_FIXED, "msdos" },
4032 { DRIVE_REMOTE, "nfs" },
4033 { DRIVE_FIXED, "ntfs" },
4034 { DRIVE_REMOTE, "smbfs" },
4035 { DRIVE_FIXED, "udf" },
4036 { DRIVE_REMOTE, "webdav" },
4037 { DRIVE_UNKNOWN, NULL }
4039 { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
4040 { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
4041 { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
4042 { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
4043 { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
4044 { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
4045 { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
4046 { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
4047 { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
4048 { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
4049 { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
4050 { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
4051 { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
4052 { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
4053 { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
4054 { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
4055 { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
4056 { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4057 { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4058 { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4059 { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4060 { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4061 { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4062 { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4063 { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4064 { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4065 { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4066 { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4067 { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4068 { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4069 { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4070 { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4071 { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4072 { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4073 { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4074 { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4075 { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4076 { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4077 { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4078 { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4079 { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4080 { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4081 { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4082 { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4083 { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4084 { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4085 { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4086 { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4087 { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4088 { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4089 { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4090 { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4091 { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4092 { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4093 { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4094 { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4095 { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4096 { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4097 { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4098 { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4099 { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4100 { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4101 { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4102 { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4103 { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4104 { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4105 { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4106 { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4107 { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4108 { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4109 { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4110 { DRIVE_UNKNOWN, 0, NULL}
4112 { DRIVE_RAMDISK, "ramfs" },
4113 { DRIVE_RAMDISK, "tmpfs" },
4114 { DRIVE_RAMDISK, "proc" },
4115 { DRIVE_RAMDISK, "sysfs" },
4116 { DRIVE_RAMDISK, "debugfs" },
4117 { DRIVE_RAMDISK, "devpts" },
4118 { DRIVE_RAMDISK, "securityfs" },
4119 { DRIVE_CDROM, "iso9660" },
4120 { DRIVE_FIXED, "ext2" },
4121 { DRIVE_FIXED, "ext3" },
4122 { DRIVE_FIXED, "ext4" },
4123 { DRIVE_FIXED, "sysv" },
4124 { DRIVE_FIXED, "reiserfs" },
4125 { DRIVE_FIXED, "ufs" },
4126 { DRIVE_FIXED, "vfat" },
4127 { DRIVE_FIXED, "msdos" },
4128 { DRIVE_FIXED, "udf" },
4129 { DRIVE_FIXED, "hfs" },
4130 { DRIVE_FIXED, "hpfs" },
4131 { DRIVE_FIXED, "qnx4" },
4132 { DRIVE_FIXED, "ntfs" },
4133 { DRIVE_FIXED, "ntfs-3g" },
4134 { DRIVE_REMOTE, "smbfs" },
4135 { DRIVE_REMOTE, "fuse" },
4136 { DRIVE_REMOTE, "nfs" },
4137 { DRIVE_REMOTE, "nfs4" },
4138 { DRIVE_REMOTE, "cifs" },
4139 { DRIVE_REMOTE, "ncpfs" },
4140 { DRIVE_REMOTE, "coda" },
4141 { DRIVE_REMOTE, "afs" },
4142 { DRIVE_UNKNOWN, NULL }
4147 static guint32 _wapi_get_drive_type(long f_type)
4149 _wapi_drive_type *current;
4151 current = &_wapi_drive_types[0];
4152 while (current->drive_type != DRIVE_UNKNOWN) {
4153 if (current->fstypeid == f_type)
4154 return current->drive_type;
4158 return DRIVE_UNKNOWN;
4161 static guint32 _wapi_get_drive_type(const gchar* fstype)
4163 _wapi_drive_type *current;
4165 current = &_wapi_drive_types[0];
4166 while (current->drive_type != DRIVE_UNKNOWN) {
4167 if (strcmp (current->fstype, fstype) == 0)
4173 return current->drive_type;
4177 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4179 GetDriveTypeFromPath (const char *utf8_root_path_name)
4183 if (statfs (utf8_root_path_name, &buf) == -1)
4184 return DRIVE_UNKNOWN;
4186 return _wapi_get_drive_type (buf.f_fstypename);
4188 return _wapi_get_drive_type (buf.f_type);
4193 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4200 fp = fopen ("/etc/mtab", "rt");
4202 fp = fopen ("/etc/mnttab", "rt");
4204 return(DRIVE_UNKNOWN);
4207 drive_type = DRIVE_NO_ROOT_DIR;
4208 while (fgets (buffer, 512, fp) != NULL) {
4209 splitted = g_strsplit (buffer, " ", 0);
4210 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4211 g_strfreev (splitted);
4215 /* compare given root_path_name with the one from mtab,
4216 if length of utf8_root_path_name is zero it must be the root dir */
4217 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4218 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4219 drive_type = _wapi_get_drive_type (*(splitted + 2));
4220 /* it is possible this path might be mounted again with
4221 a known type...keep looking */
4222 if (drive_type != DRIVE_UNKNOWN) {
4223 g_strfreev (splitted);
4228 g_strfreev (splitted);
4236 guint32 GetDriveType(const gunichar2 *root_path_name)
4238 gchar *utf8_root_path_name;
4241 if (root_path_name == NULL) {
4242 utf8_root_path_name = g_strdup (g_get_current_dir());
4243 if (utf8_root_path_name == NULL) {
4244 return(DRIVE_NO_ROOT_DIR);
4248 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4249 if (utf8_root_path_name == NULL) {
4250 DEBUG("%s: unicode conversion returned NULL", __func__);
4251 return(DRIVE_NO_ROOT_DIR);
4254 /* strip trailing slash for compare below */
4255 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4256 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4259 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4260 g_free (utf8_root_path_name);
4262 return (drive_type);
4265 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__) || defined(__FreeBSD_kernel__)
4267 get_fstypename (gchar *utfpath)
4269 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4272 _wapi_drive_type *current;
4274 if (statfs (utfpath, &stat) == -1)
4277 return g_strdup (stat.f_fstypename);
4279 current = &_wapi_drive_types[0];
4280 while (current->drive_type != DRIVE_UNKNOWN) {
4281 if (stat.f_type == current->fstypeid)
4282 return g_strdup (current->fstype);
4292 /* Linux has struct statfs which has a different layout */
4294 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4298 gboolean status = FALSE;
4301 // We only support getting the file system type
4302 if (fsbuffer == NULL)
4305 utfpath = mono_unicode_to_external (path);
4306 if ((fstypename = get_fstypename (utfpath)) != NULL){
4307 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4308 if (ret != NULL && len < fsbuffersize){
4309 memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4315 g_free (fstypename);
4324 _wapi_io_init (void)
4326 mono_mutex_init (&stdhandle_mutex);