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>
35 #include <sys/ioctl.h>
37 #include <mono/utils/linux_magic.h>
40 #include <mono/io-layer/wapi.h>
41 #include <mono/io-layer/wapi-private.h>
42 #include <mono/io-layer/handles-private.h>
43 #include <mono/io-layer/io-private.h>
44 #include <mono/io-layer/timefuncs-private.h>
45 #include <mono/io-layer/thread-private.h>
46 #include <mono/io-layer/io-portability.h>
47 #include <mono/utils/strenc.h>
50 #define DEBUG(...) g_message(__VA_ARGS__)
51 #define DEBUG_ENABLED 1
56 static void file_close (gpointer handle, gpointer data);
57 static WapiFileType file_getfiletype(void);
58 static gboolean file_read(gpointer handle, gpointer buffer,
59 guint32 numbytes, guint32 *bytesread,
60 WapiOverlapped *overlapped);
61 static gboolean file_write(gpointer handle, gconstpointer buffer,
62 guint32 numbytes, guint32 *byteswritten,
63 WapiOverlapped *overlapped);
64 static gboolean file_flush(gpointer handle);
65 static guint32 file_seek(gpointer handle, gint32 movedistance,
66 gint32 *highmovedistance, WapiSeekMethod method);
67 static gboolean file_setendoffile(gpointer handle);
68 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
69 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
70 WapiFileTime *last_access,
71 WapiFileTime *last_write);
72 static gboolean file_setfiletime(gpointer handle,
73 const WapiFileTime *create_time,
74 const WapiFileTime *last_access,
75 const WapiFileTime *last_write);
76 static guint32 GetDriveTypeFromPath (const gchar *utf8_root_path_name);
78 /* File handle is only signalled for overlapped IO */
79 struct _WapiHandleOps _wapi_file_ops = {
80 file_close, /* close */
84 NULL, /* special_wait */
88 void _wapi_file_details (gpointer handle_info)
90 struct _WapiHandle_file *file = (struct _WapiHandle_file *)handle_info;
92 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
94 file->fileaccess&GENERIC_READ?'R':'.',
95 file->fileaccess&GENERIC_WRITE?'W':'.',
96 file->fileaccess&GENERIC_EXECUTE?'X':'.',
97 file->sharemode&FILE_SHARE_READ?'R':'.',
98 file->sharemode&FILE_SHARE_WRITE?'W':'.',
99 file->sharemode&FILE_SHARE_DELETE?'D':'.',
103 static void console_close (gpointer handle, gpointer data);
104 static WapiFileType console_getfiletype(void);
105 static gboolean console_read(gpointer handle, gpointer buffer,
106 guint32 numbytes, guint32 *bytesread,
107 WapiOverlapped *overlapped);
108 static gboolean console_write(gpointer handle, gconstpointer buffer,
109 guint32 numbytes, guint32 *byteswritten,
110 WapiOverlapped *overlapped);
112 /* Console is mostly the same as file, except it can block waiting for
115 struct _WapiHandleOps _wapi_console_ops = {
116 console_close, /* close */
120 NULL, /* special_wait */
124 void _wapi_console_details (gpointer handle_info)
126 _wapi_file_details (handle_info);
129 /* Find handle has no ops.
131 struct _WapiHandleOps _wapi_find_ops = {
136 NULL, /* special_wait */
140 static void pipe_close (gpointer handle, gpointer data);
141 static WapiFileType pipe_getfiletype (void);
142 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
143 guint32 *bytesread, WapiOverlapped *overlapped);
144 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
145 guint32 numbytes, guint32 *byteswritten,
146 WapiOverlapped *overlapped);
150 struct _WapiHandleOps _wapi_pipe_ops = {
151 pipe_close, /* close */
155 NULL, /* special_wait */
159 void _wapi_pipe_details (gpointer handle_info)
161 _wapi_file_details (handle_info);
164 static const struct {
165 /* File, console and pipe handles */
166 WapiFileType (*getfiletype)(void);
168 /* File, console and pipe handles */
169 gboolean (*readfile)(gpointer handle, gpointer buffer,
170 guint32 numbytes, guint32 *bytesread,
171 WapiOverlapped *overlapped);
172 gboolean (*writefile)(gpointer handle, gconstpointer buffer,
173 guint32 numbytes, guint32 *byteswritten,
174 WapiOverlapped *overlapped);
175 gboolean (*flushfile)(gpointer handle);
178 guint32 (*seek)(gpointer handle, gint32 movedistance,
179 gint32 *highmovedistance, WapiSeekMethod method);
180 gboolean (*setendoffile)(gpointer handle);
181 guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
182 gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
183 WapiFileTime *last_access,
184 WapiFileTime *last_write);
185 gboolean (*setfiletime)(gpointer handle,
186 const WapiFileTime *create_time,
187 const WapiFileTime *last_access,
188 const WapiFileTime *last_write);
189 } io_ops[WAPI_HANDLE_COUNT]={
190 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
193 file_read, file_write,
194 file_flush, file_seek,
200 {console_getfiletype,
203 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},
211 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
212 /* socket (will need at least read and write) */
213 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
215 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
217 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
222 NULL, NULL, NULL, NULL, NULL, NULL},
225 static mono_once_t io_ops_once=MONO_ONCE_INIT;
226 static gboolean lock_while_writing = FALSE;
228 static void io_ops_init (void)
230 /* _wapi_handle_register_capabilities (WAPI_HANDLE_FILE, */
231 /* WAPI_HANDLE_CAP_WAIT); */
232 /* _wapi_handle_register_capabilities (WAPI_HANDLE_CONSOLE, */
233 /* WAPI_HANDLE_CAP_WAIT); */
235 if (g_getenv ("MONO_STRICT_IO_EMULATION") != NULL) {
236 lock_while_writing = TRUE;
240 /* Some utility functions.
244 * Check if a file is writable by the current user.
246 * This is is a best effort kind of thing. It assumes a reasonable sane set
247 * of permissions by the underlying OS.
249 * We assume that basic unix permission bits are authoritative. Which might not
250 * be the case under systems with extended permissions systems (posix ACLs, SELinux, OSX/iOS sandboxing, etc)
252 * The choice of access as the fallback is due to the expected lower overhead compared to trying to open the file.
254 * The only expected problem with using access are for root, setuid or setgid programs as access is not consistent
255 * under those situations. It's to be expected that this should not happen in practice as those bits are very dangerous
256 * and should not be used with a dynamic runtime.
259 is_file_writable (struct stat *st, const char *path)
261 /* Is it globally writable? */
262 if (st->st_mode & S_IWOTH)
265 /* Am I the owner? */
266 if ((st->st_uid == geteuid ()) && (st->st_mode & S_IWUSR))
269 /* Am I in the same group? */
270 if ((st->st_gid == getegid ()) && (st->st_mode & S_IWGRP))
273 /* Fallback to using access(2). It's not ideal as it might not take into consideration euid/egid
274 * but it's the only sane option we have on unix.
276 return access (path, W_OK) == 0;
280 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
287 /* FIXME: this could definitely be better, but there seems to
288 * be no pattern to the attributes that are set
291 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
292 if (S_ISSOCK (buf->st_mode))
293 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
295 filename = _wapi_basename (pathname);
297 if (S_ISDIR (buf->st_mode)) {
298 attrs = FILE_ATTRIBUTE_DIRECTORY;
299 if (!is_file_writable (buf, pathname)) {
300 attrs |= FILE_ATTRIBUTE_READONLY;
302 if (filename[0] == '.') {
303 attrs |= FILE_ATTRIBUTE_HIDDEN;
306 if (!is_file_writable (buf, pathname)) {
307 attrs = FILE_ATTRIBUTE_READONLY;
309 if (filename[0] == '.') {
310 attrs |= FILE_ATTRIBUTE_HIDDEN;
312 } else if (filename[0] == '.') {
313 attrs = FILE_ATTRIBUTE_HIDDEN;
315 attrs = FILE_ATTRIBUTE_NORMAL;
320 if (S_ISLNK (lbuf->st_mode)) {
321 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
331 _wapi_set_last_error_from_errno (void)
333 SetLastError (_wapi_get_win32_file_error (errno));
336 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
339 if (errno == ENOENT) {
340 /* Check the path - if it's a missing directory then
341 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
347 dirname = _wapi_dirname (path);
349 dirname = g_strdup (dir);
352 if (_wapi_access (dirname, F_OK) == 0) {
353 SetLastError (ERROR_FILE_NOT_FOUND);
355 SetLastError (ERROR_PATH_NOT_FOUND);
360 _wapi_set_last_error_from_errno ();
366 static void file_close (gpointer handle, gpointer data)
368 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
369 int fd = file_handle->fd;
371 DEBUG("%s: closing file handle %p [%s]", __func__, handle,
372 file_handle->filename);
374 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
375 _wapi_unlink (file_handle->filename);
377 g_free (file_handle->filename);
379 if (file_handle->share_info)
380 _wapi_handle_share_release (file_handle->share_info);
385 static WapiFileType file_getfiletype(void)
387 return(FILE_TYPE_DISK);
390 static gboolean file_read(gpointer handle, gpointer buffer,
391 guint32 numbytes, guint32 *bytesread,
392 WapiOverlapped *overlapped)
394 struct _WapiHandle_file *file_handle;
398 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
399 (gpointer *)&file_handle);
401 g_warning ("%s: error looking up file handle %p", __func__,
403 SetLastError (ERROR_INVALID_HANDLE);
407 fd = file_handle->fd;
408 if(bytesread!=NULL) {
412 if(!(file_handle->fileaccess & GENERIC_READ) &&
413 !(file_handle->fileaccess & GENERIC_ALL)) {
414 DEBUG("%s: handle %p doesn't have GENERIC_READ access: %u",
415 __func__, handle, file_handle->fileaccess);
417 SetLastError (ERROR_ACCESS_DENIED);
422 ret = read (fd, buffer, numbytes);
423 } while (ret == -1 && errno == EINTR &&
424 !_wapi_thread_cur_apc_pending());
429 DEBUG("%s: read of handle %p error: %s", __func__,
430 handle, strerror(err));
431 SetLastError (_wapi_get_win32_file_error (err));
435 if (bytesread != NULL) {
442 static gboolean file_write(gpointer handle, gconstpointer buffer,
443 guint32 numbytes, guint32 *byteswritten,
444 WapiOverlapped *overlapped G_GNUC_UNUSED)
446 struct _WapiHandle_file *file_handle;
449 off_t current_pos = 0;
451 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
452 (gpointer *)&file_handle);
454 g_warning ("%s: error looking up file handle %p", __func__,
456 SetLastError (ERROR_INVALID_HANDLE);
460 fd = file_handle->fd;
462 if(byteswritten!=NULL) {
466 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
467 !(file_handle->fileaccess & GENERIC_ALL)) {
468 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
470 SetLastError (ERROR_ACCESS_DENIED);
474 if (lock_while_writing) {
475 /* Need to lock the region we're about to write to,
476 * because we only do advisory locking on POSIX
479 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
480 if (current_pos == -1) {
481 DEBUG ("%s: handle %p lseek failed: %s", __func__,
482 handle, strerror (errno));
483 _wapi_set_last_error_from_errno ();
487 if (_wapi_lock_file_region (fd, current_pos,
488 numbytes) == FALSE) {
489 /* The error has already been set */
495 ret = write (fd, buffer, numbytes);
496 } while (ret == -1 && errno == EINTR &&
497 !_wapi_thread_cur_apc_pending());
499 if (lock_while_writing) {
500 _wapi_unlock_file_region (fd, current_pos, numbytes);
504 if (errno == EINTR) {
507 _wapi_set_last_error_from_errno ();
509 DEBUG("%s: write of handle %p error: %s",
510 __func__, handle, strerror(errno));
515 if (byteswritten != NULL) {
521 static gboolean file_flush(gpointer handle)
523 struct _WapiHandle_file *file_handle;
527 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
528 (gpointer *)&file_handle);
530 g_warning ("%s: error looking up file handle %p", __func__,
532 SetLastError (ERROR_INVALID_HANDLE);
536 fd = file_handle->fd;
538 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
539 !(file_handle->fileaccess & GENERIC_ALL)) {
540 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
542 SetLastError (ERROR_ACCESS_DENIED);
548 DEBUG("%s: fsync of handle %p error: %s", __func__, handle,
551 _wapi_set_last_error_from_errno ();
558 static guint32 file_seek(gpointer handle, gint32 movedistance,
559 gint32 *highmovedistance, WapiSeekMethod method)
561 struct _WapiHandle_file *file_handle;
563 gint64 offset, newpos;
567 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
568 (gpointer *)&file_handle);
570 g_warning ("%s: error looking up file handle %p", __func__,
572 SetLastError (ERROR_INVALID_HANDLE);
573 return(INVALID_SET_FILE_POINTER);
576 fd = file_handle->fd;
578 if(!(file_handle->fileaccess & GENERIC_READ) &&
579 !(file_handle->fileaccess & GENERIC_WRITE) &&
580 !(file_handle->fileaccess & GENERIC_ALL)) {
581 DEBUG ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
583 SetLastError (ERROR_ACCESS_DENIED);
584 return(INVALID_SET_FILE_POINTER);
598 DEBUG("%s: invalid seek type %d", __func__, method);
600 SetLastError (ERROR_INVALID_PARAMETER);
601 return(INVALID_SET_FILE_POINTER);
604 #ifdef HAVE_LARGE_FILE_SUPPORT
605 if(highmovedistance==NULL) {
607 DEBUG("%s: setting offset to %lld (low %d)", __func__,
608 offset, movedistance);
610 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
612 DEBUG("%s: setting offset to %lld 0x%llx (high %d 0x%x, low %d 0x%x)", __func__, offset, offset, *highmovedistance, *highmovedistance, movedistance, movedistance);
618 DEBUG ("%s: moving handle %p by %lld bytes from %d", __func__,
619 handle, (long long)offset, whence);
621 #ifdef PLATFORM_ANDROID
622 /* bionic doesn't support -D_FILE_OFFSET_BITS=64 */
623 newpos=lseek64(fd, offset, whence);
625 newpos=lseek(fd, offset, whence);
628 DEBUG("%s: lseek on handle %p returned error %s",
629 __func__, handle, strerror(errno));
631 _wapi_set_last_error_from_errno ();
632 return(INVALID_SET_FILE_POINTER);
635 DEBUG ("%s: lseek returns %lld", __func__, newpos);
637 #ifdef HAVE_LARGE_FILE_SUPPORT
638 ret=newpos & 0xFFFFFFFF;
639 if(highmovedistance!=NULL) {
640 *highmovedistance=newpos>>32;
644 if(highmovedistance!=NULL) {
645 /* Accurate, but potentially dodgy :-) */
650 DEBUG ("%s: move of handle %p returning %d/%d", __func__,
651 handle, ret, highmovedistance==NULL?0:*highmovedistance);
656 static gboolean file_setendoffile(gpointer handle)
658 struct _WapiHandle_file *file_handle;
664 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
665 (gpointer *)&file_handle);
667 g_warning ("%s: error looking up file handle %p", __func__,
669 SetLastError (ERROR_INVALID_HANDLE);
672 fd = file_handle->fd;
674 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
675 !(file_handle->fileaccess & GENERIC_ALL)) {
676 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
678 SetLastError (ERROR_ACCESS_DENIED);
682 /* Find the current file position, and the file length. If
683 * the file position is greater than the length, write to
684 * extend the file with a hole. If the file position is less
685 * than the length, truncate the file.
688 ret=fstat(fd, &statbuf);
690 DEBUG ("%s: handle %p fstat failed: %s", __func__,
691 handle, strerror(errno));
693 _wapi_set_last_error_from_errno ();
696 size=statbuf.st_size;
698 pos=lseek(fd, (off_t)0, SEEK_CUR);
700 DEBUG("%s: handle %p lseek failed: %s", __func__,
701 handle, strerror(errno));
703 _wapi_set_last_error_from_errno ();
707 #ifdef FTRUNCATE_DOESNT_EXTEND
708 /* I haven't bothered to write the configure.in stuff for this
709 * because I don't know if any platform needs it. I'm leaving
710 * this code just in case though
713 /* Extend the file. Use write() here, because some
714 * manuals say that ftruncate() behaviour is undefined
715 * when the file needs extending. The POSIX spec says
716 * that on XSI-conformant systems it extends, so if
717 * every system we care about conforms, then we can
721 ret = write (fd, "", 1);
722 } while (ret == -1 && errno == EINTR &&
723 !_wapi_thread_cur_apc_pending());
726 DEBUG("%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
728 _wapi_set_last_error_from_errno ();
732 /* And put the file position back after the write */
733 ret = lseek (fd, pos, SEEK_SET);
735 DEBUG ("%s: handle %p second lseek failed: %s",
736 __func__, handle, strerror(errno));
738 _wapi_set_last_error_from_errno ();
744 /* Native Client has no ftruncate function, even in standalone sel_ldr. */
745 #ifndef __native_client__
746 /* always truncate, because the extend write() adds an extra
747 * byte to the end of the file
750 ret=ftruncate(fd, pos);
752 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
754 DEBUG("%s: handle %p ftruncate failed: %s", __func__,
755 handle, strerror(errno));
757 _wapi_set_last_error_from_errno ();
765 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
767 struct _WapiHandle_file *file_handle;
774 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
775 (gpointer *)&file_handle);
777 g_warning ("%s: error looking up file handle %p", __func__,
779 SetLastError (ERROR_INVALID_HANDLE);
780 return(INVALID_FILE_SIZE);
782 fd = file_handle->fd;
784 if(!(file_handle->fileaccess & GENERIC_READ) &&
785 !(file_handle->fileaccess & GENERIC_WRITE) &&
786 !(file_handle->fileaccess & GENERIC_ALL)) {
787 DEBUG("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
789 SetLastError (ERROR_ACCESS_DENIED);
790 return(INVALID_FILE_SIZE);
793 /* If the file has a size with the low bits 0xFFFFFFFF the
794 * caller can't tell if this is an error, so clear the error
797 SetLastError (ERROR_SUCCESS);
799 ret = fstat(fd, &statbuf);
801 DEBUG ("%s: handle %p fstat failed: %s", __func__,
802 handle, strerror(errno));
804 _wapi_set_last_error_from_errno ();
805 return(INVALID_FILE_SIZE);
808 /* fstat indicates block devices as zero-length, so go a different path */
810 if (S_ISBLK(statbuf.st_mode)) {
812 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
813 DEBUG ("%s: handle %p ioctl BLKGETSIZE64 failed: %s",
814 __func__, handle, strerror(errno));
816 _wapi_set_last_error_from_errno ();
817 return(INVALID_FILE_SIZE);
820 size = bigsize & 0xFFFFFFFF;
821 if (highsize != NULL) {
822 *highsize = bigsize>>32;
825 DEBUG ("%s: Returning block device size %d/%d",
826 __func__, size, *highsize);
832 #ifdef HAVE_LARGE_FILE_SUPPORT
833 size = statbuf.st_size & 0xFFFFFFFF;
834 if (highsize != NULL) {
835 *highsize = statbuf.st_size>>32;
838 if (highsize != NULL) {
839 /* Accurate, but potentially dodgy :-) */
842 size = statbuf.st_size;
845 DEBUG ("%s: Returning size %d/%d", __func__, size, *highsize);
850 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
851 WapiFileTime *last_access,
852 WapiFileTime *last_write)
854 struct _WapiHandle_file *file_handle;
857 guint64 create_ticks, access_ticks, write_ticks;
860 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
861 (gpointer *)&file_handle);
863 g_warning ("%s: error looking up file handle %p", __func__,
865 SetLastError (ERROR_INVALID_HANDLE);
868 fd = file_handle->fd;
870 if(!(file_handle->fileaccess & GENERIC_READ) &&
871 !(file_handle->fileaccess & GENERIC_ALL)) {
872 DEBUG("%s: handle %p doesn't have GENERIC_READ access: %u",
873 __func__, handle, file_handle->fileaccess);
875 SetLastError (ERROR_ACCESS_DENIED);
879 ret=fstat(fd, &statbuf);
881 DEBUG("%s: handle %p fstat failed: %s", __func__, handle,
884 _wapi_set_last_error_from_errno ();
888 DEBUG("%s: atime: %ld ctime: %ld mtime: %ld", __func__,
889 statbuf.st_atime, statbuf.st_ctime,
892 /* Try and guess a meaningful create time by using the older
895 /* The magic constant comes from msdn documentation
896 * "Converting a time_t Value to a File Time"
898 if(statbuf.st_atime < statbuf.st_ctime) {
899 create_ticks=((guint64)statbuf.st_atime*10000000)
900 + 116444736000000000ULL;
902 create_ticks=((guint64)statbuf.st_ctime*10000000)
903 + 116444736000000000ULL;
906 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
907 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
909 DEBUG("%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
910 access_ticks, create_ticks, write_ticks);
912 if(create_time!=NULL) {
913 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
914 create_time->dwHighDateTime = create_ticks >> 32;
917 if(last_access!=NULL) {
918 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
919 last_access->dwHighDateTime = access_ticks >> 32;
922 if(last_write!=NULL) {
923 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
924 last_write->dwHighDateTime = write_ticks >> 32;
930 static gboolean file_setfiletime(gpointer handle,
931 const WapiFileTime *create_time G_GNUC_UNUSED,
932 const WapiFileTime *last_access,
933 const WapiFileTime *last_write)
935 struct _WapiHandle_file *file_handle;
937 struct utimbuf utbuf;
939 guint64 access_ticks, write_ticks;
942 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
943 (gpointer *)&file_handle);
945 g_warning ("%s: error looking up file handle %p", __func__,
947 SetLastError (ERROR_INVALID_HANDLE);
950 fd = file_handle->fd;
952 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
953 !(file_handle->fileaccess & GENERIC_ALL)) {
954 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
956 SetLastError (ERROR_ACCESS_DENIED);
960 if(file_handle->filename == NULL) {
961 DEBUG("%s: handle %p unknown filename", __func__, handle);
963 SetLastError (ERROR_INVALID_HANDLE);
967 /* Get the current times, so we can put the same times back in
968 * the event that one of the FileTime structs is NULL
970 ret=fstat (fd, &statbuf);
972 DEBUG("%s: handle %p fstat failed: %s", __func__, handle,
975 SetLastError (ERROR_INVALID_PARAMETER);
979 if(last_access!=NULL) {
980 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
981 last_access->dwLowDateTime;
982 /* This is (time_t)0. We can actually go to INT_MIN,
983 * but this will do for now.
985 if (access_ticks < 116444736000000000ULL) {
986 DEBUG ("%s: attempt to set access time too early",
988 SetLastError (ERROR_INVALID_PARAMETER);
992 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
994 utbuf.actime=statbuf.st_atime;
997 if(last_write!=NULL) {
998 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
999 last_write->dwLowDateTime;
1000 /* This is (time_t)0. We can actually go to INT_MIN,
1001 * but this will do for now.
1003 if (write_ticks < 116444736000000000ULL) {
1004 DEBUG ("%s: attempt to set write time too early",
1006 SetLastError (ERROR_INVALID_PARAMETER);
1010 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1012 utbuf.modtime=statbuf.st_mtime;
1015 DEBUG ("%s: setting handle %p access %ld write %ld", __func__,
1016 handle, utbuf.actime, utbuf.modtime);
1018 ret = _wapi_utime (file_handle->filename, &utbuf);
1020 DEBUG ("%s: handle %p [%s] utime failed: %s", __func__,
1021 handle, file_handle->filename, strerror(errno));
1023 SetLastError (ERROR_INVALID_PARAMETER);
1030 static void console_close (gpointer handle, gpointer data)
1032 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1033 int fd = console_handle->fd;
1035 DEBUG("%s: closing console handle %p", __func__, handle);
1037 g_free (console_handle->filename);
1042 static WapiFileType console_getfiletype(void)
1044 return(FILE_TYPE_CHAR);
1047 static gboolean console_read(gpointer handle, gpointer buffer,
1048 guint32 numbytes, guint32 *bytesread,
1049 WapiOverlapped *overlapped G_GNUC_UNUSED)
1051 struct _WapiHandle_file *console_handle;
1055 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1056 (gpointer *)&console_handle);
1058 g_warning ("%s: error looking up console handle %p", __func__,
1060 SetLastError (ERROR_INVALID_HANDLE);
1063 fd = console_handle->fd;
1065 if(bytesread!=NULL) {
1069 if(!(console_handle->fileaccess & GENERIC_READ) &&
1070 !(console_handle->fileaccess & GENERIC_ALL)) {
1071 DEBUG ("%s: handle %p doesn't have GENERIC_READ access: %u",
1072 __func__, handle, console_handle->fileaccess);
1074 SetLastError (ERROR_ACCESS_DENIED);
1079 ret=read(fd, buffer, numbytes);
1080 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1083 DEBUG("%s: read of handle %p error: %s", __func__, handle,
1086 _wapi_set_last_error_from_errno ();
1090 if(bytesread!=NULL) {
1097 static gboolean console_write(gpointer handle, gconstpointer buffer,
1098 guint32 numbytes, guint32 *byteswritten,
1099 WapiOverlapped *overlapped G_GNUC_UNUSED)
1101 struct _WapiHandle_file *console_handle;
1105 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1106 (gpointer *)&console_handle);
1108 g_warning ("%s: error looking up console handle %p", __func__,
1110 SetLastError (ERROR_INVALID_HANDLE);
1113 fd = console_handle->fd;
1115 if(byteswritten!=NULL) {
1119 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1120 !(console_handle->fileaccess & GENERIC_ALL)) {
1121 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, console_handle->fileaccess);
1123 SetLastError (ERROR_ACCESS_DENIED);
1128 ret = write(fd, buffer, numbytes);
1129 } while (ret == -1 && errno == EINTR &&
1130 !_wapi_thread_cur_apc_pending());
1133 if (errno == EINTR) {
1136 _wapi_set_last_error_from_errno ();
1138 DEBUG ("%s: write of handle %p error: %s",
1139 __func__, handle, strerror(errno));
1144 if(byteswritten!=NULL) {
1151 static void pipe_close (gpointer handle, gpointer data)
1153 struct _WapiHandle_file *pipe_handle = (struct _WapiHandle_file*)data;
1154 int fd = pipe_handle->fd;
1156 DEBUG("%s: closing pipe handle %p", __func__, handle);
1158 /* No filename with pipe handles */
1163 static WapiFileType pipe_getfiletype(void)
1165 return(FILE_TYPE_PIPE);
1168 static gboolean pipe_read (gpointer handle, gpointer buffer,
1169 guint32 numbytes, guint32 *bytesread,
1170 WapiOverlapped *overlapped G_GNUC_UNUSED)
1172 struct _WapiHandle_file *pipe_handle;
1176 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1177 (gpointer *)&pipe_handle);
1179 g_warning ("%s: error looking up pipe handle %p", __func__,
1181 SetLastError (ERROR_INVALID_HANDLE);
1184 fd = pipe_handle->fd;
1186 if(bytesread!=NULL) {
1190 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1191 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1192 DEBUG("%s: handle %p doesn't have GENERIC_READ access: %u",
1193 __func__, handle, pipe_handle->fileaccess);
1195 SetLastError (ERROR_ACCESS_DENIED);
1199 DEBUG ("%s: reading up to %d bytes from pipe %p", __func__,
1203 ret=read(fd, buffer, numbytes);
1204 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1207 if (errno == EINTR) {
1210 _wapi_set_last_error_from_errno ();
1212 DEBUG("%s: read of handle %p error: %s", __func__,
1213 handle, strerror(errno));
1219 DEBUG ("%s: read %d bytes from pipe", __func__, ret);
1221 if(bytesread!=NULL) {
1228 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1229 guint32 numbytes, guint32 *byteswritten,
1230 WapiOverlapped *overlapped G_GNUC_UNUSED)
1232 struct _WapiHandle_file *pipe_handle;
1236 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1237 (gpointer *)&pipe_handle);
1239 g_warning ("%s: error looking up pipe handle %p", __func__,
1241 SetLastError (ERROR_INVALID_HANDLE);
1244 fd = pipe_handle->fd;
1246 if(byteswritten!=NULL) {
1250 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1251 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1252 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, pipe_handle->fileaccess);
1254 SetLastError (ERROR_ACCESS_DENIED);
1258 DEBUG ("%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1262 ret = write (fd, buffer, numbytes);
1263 } while (ret == -1 && errno == EINTR &&
1264 !_wapi_thread_cur_apc_pending());
1267 if (errno == EINTR) {
1270 _wapi_set_last_error_from_errno ();
1272 DEBUG("%s: write of handle %p error: %s", __func__,
1273 handle, strerror(errno));
1278 if(byteswritten!=NULL) {
1285 static int convert_flags(guint32 fileaccess, guint32 createmode)
1289 switch(fileaccess) {
1296 case GENERIC_READ|GENERIC_WRITE:
1300 DEBUG("%s: Unknown access type 0x%x", __func__,
1305 switch(createmode) {
1307 flags|=O_CREAT|O_EXCL;
1310 flags|=O_CREAT|O_TRUNC;
1317 case TRUNCATE_EXISTING:
1321 DEBUG("%s: Unknown create mode 0x%x", __func__,
1330 static mode_t convert_perms(guint32 sharemode)
1334 if(sharemode&FILE_SHARE_READ) {
1337 if(sharemode&FILE_SHARE_WRITE) {
1345 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1347 struct _WapiFileShare **share_info)
1349 gboolean file_already_shared;
1350 guint32 file_existing_share, file_existing_access;
1352 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);
1354 if (file_already_shared) {
1355 /* The reference to this share info was incremented
1356 * when we looked it up, so be careful to put it back
1357 * if we conclude we can't use this file.
1359 if (file_existing_share == 0) {
1360 /* Quick and easy, no possibility to share */
1361 DEBUG ("%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
1363 _wapi_handle_share_release (*share_info);
1368 if (((file_existing_share == FILE_SHARE_READ) &&
1369 (fileaccess != GENERIC_READ)) ||
1370 ((file_existing_share == FILE_SHARE_WRITE) &&
1371 (fileaccess != GENERIC_WRITE))) {
1372 /* New access mode doesn't match up */
1373 DEBUG ("%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
1375 _wapi_handle_share_release (*share_info);
1380 if (((file_existing_access & GENERIC_READ) &&
1381 !(sharemode & FILE_SHARE_READ)) ||
1382 ((file_existing_access & GENERIC_WRITE) &&
1383 !(sharemode & FILE_SHARE_WRITE))) {
1384 /* New share mode doesn't match up */
1385 DEBUG ("%s: Access mode prevents open: requested share: 0x%x, file has access: 0x%x", __func__, sharemode, file_existing_access);
1387 _wapi_handle_share_release (*share_info);
1392 DEBUG ("%s: New file!", __func__);
1400 share_allows_delete (struct stat *statbuf, struct _WapiFileShare **share_info)
1402 gboolean file_already_shared;
1403 guint32 file_existing_share, file_existing_access;
1405 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);
1407 if (file_already_shared) {
1408 /* The reference to this share info was incremented
1409 * when we looked it up, so be careful to put it back
1410 * if we conclude we can't use this file.
1412 if (file_existing_share == 0) {
1413 /* Quick and easy, no possibility to share */
1414 DEBUG ("%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
1416 _wapi_handle_share_release (*share_info);
1421 if (!(file_existing_share & FILE_SHARE_DELETE)) {
1422 /* New access mode doesn't match up */
1423 DEBUG ("%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
1425 _wapi_handle_share_release (*share_info);
1430 DEBUG ("%s: New file!", __func__);
1435 static gboolean share_check (struct stat *statbuf, guint32 sharemode,
1437 struct _WapiFileShare **share_info, int fd)
1439 if (share_allows_open (statbuf, sharemode, fileaccess,
1440 share_info) == TRUE) {
1444 /* Got a share violation. Double check that the file is still
1445 * open by someone, in case a process crashed while still
1446 * holding a file handle. This will also cope with someone
1447 * using Mono.Posix to close the file. This is cheaper and
1448 * less intrusive to other processes than initiating a handle
1452 _wapi_handle_check_share (*share_info, fd);
1453 if (share_allows_open (statbuf, sharemode, fileaccess,
1454 share_info) == TRUE) {
1458 /* Still violating. It's possible that a process crashed
1459 * while still holding a file handle, and that a non-mono
1460 * process has the file open. (For example, C-c mcs while
1461 * editing a source file.) As a last resort, run a handle
1462 * collection, which will remove stale share entries.
1464 _wapi_handle_collect ();
1466 return(share_allows_open (statbuf, sharemode, fileaccess, share_info));
1471 * @name: a pointer to a NULL-terminated unicode string, that names
1472 * the file or other object to create.
1473 * @fileaccess: specifies the file access mode
1474 * @sharemode: whether the file should be shared. This parameter is
1475 * currently ignored.
1476 * @security: Ignored for now.
1477 * @createmode: specifies whether to create a new file, whether to
1478 * overwrite an existing file, whether to truncate the file, etc.
1479 * @attrs: specifies file attributes and flags. On win32 attributes
1480 * are characteristics of the file, not the handle, and are ignored
1481 * when an existing file is opened. Flags give the library hints on
1482 * how to process a file to optimise performance.
1483 * @template: the handle of an open %GENERIC_READ file that specifies
1484 * attributes to apply to a newly created file, ignoring @attrs.
1485 * Normally this parameter is NULL. This parameter is ignored when an
1486 * existing file is opened.
1488 * Creates a new file handle. This only applies to normal files:
1489 * pipes are handled by CreatePipe(), and console handles are created
1490 * with GetStdHandle().
1492 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1494 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1495 guint32 sharemode, WapiSecurityAttributes *security,
1496 guint32 createmode, guint32 attrs,
1497 gpointer template G_GNUC_UNUSED)
1499 struct _WapiHandle_file file_handle = {0};
1501 int flags=convert_flags(fileaccess, createmode);
1502 /*mode_t perms=convert_perms(sharemode);*/
1503 /* we don't use sharemode, because that relates to sharing of
1504 * the file when the file is open and is already handled by
1505 * other code, perms instead are the on-disk permissions and
1506 * this is a sane default.
1512 struct stat statbuf;
1514 mono_once (&io_ops_once, io_ops_init);
1516 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1519 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1520 SetLastError (ERROR_ENCRYPTION_FAILED);
1521 return INVALID_HANDLE_VALUE;
1525 DEBUG ("%s: name is NULL", __func__);
1527 SetLastError (ERROR_INVALID_NAME);
1528 return(INVALID_HANDLE_VALUE);
1531 filename = mono_unicode_to_external (name);
1532 if (filename == NULL) {
1533 DEBUG("%s: unicode conversion returned NULL", __func__);
1535 SetLastError (ERROR_INVALID_NAME);
1536 return(INVALID_HANDLE_VALUE);
1539 DEBUG ("%s: Opening %s with share 0x%x and access 0x%x", __func__,
1540 filename, sharemode, fileaccess);
1542 fd = _wapi_open (filename, flags, perms);
1544 /* If we were trying to open a directory with write permissions
1545 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1546 * EISDIR. However, this is a bit bogus because calls to
1547 * manipulate the directory (e.g. SetFileTime) will still work on
1548 * the directory because they use other API calls
1549 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1550 * to open the directory again without write permission.
1552 if (fd == -1 && errno == EISDIR)
1554 /* Try again but don't try to make it writable */
1555 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1559 DEBUG("%s: Error opening file %s: %s", __func__, filename,
1561 _wapi_set_last_path_error_from_errno (NULL, filename);
1564 return(INVALID_HANDLE_VALUE);
1567 if (fd >= _wapi_fd_reserve) {
1568 DEBUG ("%s: File descriptor is too big", __func__);
1570 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1575 return(INVALID_HANDLE_VALUE);
1578 ret = fstat (fd, &statbuf);
1580 DEBUG ("%s: fstat error of file %s: %s", __func__,
1581 filename, strerror (errno));
1582 _wapi_set_last_error_from_errno ();
1586 return(INVALID_HANDLE_VALUE);
1588 #ifdef __native_client__
1589 /* Workaround: Native Client currently returns the same fake inode
1590 * for all files, so do a simple hash on the filename so we don't
1591 * use the same share info for each file.
1593 statbuf.st_ino = g_str_hash(filename);
1596 if (share_check (&statbuf, sharemode, fileaccess,
1597 &file_handle.share_info, fd) == FALSE) {
1598 SetLastError (ERROR_SHARING_VIOLATION);
1602 return (INVALID_HANDLE_VALUE);
1604 if (file_handle.share_info == NULL) {
1605 /* No space, so no more files can be opened */
1606 DEBUG ("%s: No space in the share table", __func__);
1608 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1612 return(INVALID_HANDLE_VALUE);
1615 file_handle.filename = filename;
1617 if(security!=NULL) {
1618 //file_handle->security_attributes=_wapi_handle_scratch_store (
1619 //security, sizeof(WapiSecurityAttributes));
1622 file_handle.fd = fd;
1623 file_handle.fileaccess=fileaccess;
1624 file_handle.sharemode=sharemode;
1625 file_handle.attrs=attrs;
1627 #ifdef HAVE_POSIX_FADVISE
1628 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1629 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1630 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1631 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1635 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1637 if (S_ISFIFO (statbuf.st_mode)) {
1638 handle_type = WAPI_HANDLE_PIPE;
1639 } else if (S_ISCHR (statbuf.st_mode)) {
1640 handle_type = WAPI_HANDLE_CONSOLE;
1642 handle_type = WAPI_HANDLE_FILE;
1645 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1646 if (handle == _WAPI_HANDLE_INVALID) {
1647 g_warning ("%s: error creating file handle", __func__);
1651 SetLastError (ERROR_GEN_FAILURE);
1652 return(INVALID_HANDLE_VALUE);
1655 DEBUG("%s: returning handle %p", __func__, handle);
1662 * @name: a pointer to a NULL-terminated unicode string, that names
1663 * the file to be deleted.
1665 * Deletes file @name.
1667 * Return value: %TRUE on success, %FALSE otherwise.
1669 gboolean DeleteFile(const gunichar2 *name)
1673 gboolean ret = FALSE;
1676 struct stat statbuf;
1677 struct _WapiFileShare *shareinfo;
1681 DEBUG("%s: name is NULL", __func__);
1683 SetLastError (ERROR_INVALID_NAME);
1687 filename=mono_unicode_to_external(name);
1688 if(filename==NULL) {
1689 DEBUG("%s: unicode conversion returned NULL", __func__);
1691 SetLastError (ERROR_INVALID_NAME);
1695 attrs = GetFileAttributes (name);
1696 if (attrs == INVALID_FILE_ATTRIBUTES) {
1697 DEBUG ("%s: file attributes error", __func__);
1698 /* Error set by GetFileAttributes() */
1704 /* Check to make sure sharing allows us to open the file for
1705 * writing. See bug 323389.
1707 * Do the checks that don't need an open file descriptor, for
1708 * simplicity's sake. If we really have to do the full checks
1709 * then we can implement that later.
1711 if (_wapi_stat (filename, &statbuf) < 0) {
1712 _wapi_set_last_path_error_from_errno (NULL, filename);
1717 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1718 &shareinfo) == FALSE) {
1719 SetLastError (ERROR_SHARING_VIOLATION);
1724 _wapi_handle_share_release (shareinfo);
1727 retval = _wapi_unlink (filename);
1730 _wapi_set_last_path_error_from_errno (NULL, filename);
1742 * @name: a pointer to a NULL-terminated unicode string, that names
1743 * the file to be moved.
1744 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1745 * new name for the file.
1747 * Renames file @name to @dest_name.
1748 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1749 * when it is the same file as the source. In that case it silently succeeds.
1751 * Return value: %TRUE on success, %FALSE otherwise.
1753 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1755 gchar *utf8_name, *utf8_dest_name;
1756 int result, errno_copy;
1757 struct stat stat_src, stat_dest;
1758 gboolean ret = FALSE;
1759 struct _WapiFileShare *shareinfo;
1762 DEBUG("%s: name is NULL", __func__);
1764 SetLastError (ERROR_INVALID_NAME);
1768 utf8_name = mono_unicode_to_external (name);
1769 if (utf8_name == NULL) {
1770 DEBUG ("%s: unicode conversion returned NULL", __func__);
1772 SetLastError (ERROR_INVALID_NAME);
1776 if(dest_name==NULL) {
1777 DEBUG("%s: name is NULL", __func__);
1780 SetLastError (ERROR_INVALID_NAME);
1784 utf8_dest_name = mono_unicode_to_external (dest_name);
1785 if (utf8_dest_name == NULL) {
1786 DEBUG ("%s: unicode conversion returned NULL", __func__);
1789 SetLastError (ERROR_INVALID_NAME);
1794 * In C# land we check for the existence of src, but not for dest.
1795 * We check it here and return the failure if dest exists and is not
1796 * the same file as src.
1798 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1799 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1800 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1802 g_free (utf8_dest_name);
1807 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1808 if (stat_dest.st_dev != stat_src.st_dev ||
1809 stat_dest.st_ino != stat_src.st_ino) {
1811 g_free (utf8_dest_name);
1812 SetLastError (ERROR_ALREADY_EXISTS);
1817 /* Check to make that we have delete sharing permission.
1818 * See https://bugzilla.xamarin.com/show_bug.cgi?id=17009
1820 * Do the checks that don't need an open file descriptor, for
1821 * simplicity's sake. If we really have to do the full checks
1822 * then we can implement that later.
1824 if (share_allows_delete (&stat_src, &shareinfo) == FALSE) {
1825 SetLastError (ERROR_SHARING_VIOLATION);
1829 _wapi_handle_share_release (shareinfo);
1831 result = _wapi_rename (utf8_name, utf8_dest_name);
1835 switch(errno_copy) {
1837 SetLastError (ERROR_ALREADY_EXISTS);
1841 /* Ignore here, it is dealt with below */
1845 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1850 g_free (utf8_dest_name);
1852 if (result != 0 && errno_copy == EXDEV) {
1853 if (S_ISDIR (stat_src.st_mode)) {
1854 SetLastError (ERROR_NOT_SAME_DEVICE);
1857 /* Try a copy to the new location, and delete the source */
1858 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1859 /* CopyFile will set the error */
1863 return(DeleteFile (name));
1874 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1878 int buf_size = st_src->st_blksize;
1880 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1881 buf = (char *) malloc (buf_size);
1884 remain = read (src_fd, buf, buf_size);
1886 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1890 _wapi_set_last_error_from_errno ();
1900 while (remain > 0) {
1901 if ((n = write (dest_fd, wbuf, remain)) < 0) {
1902 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1906 _wapi_set_last_error_from_errno ();
1907 DEBUG ("%s: write failed.", __func__);
1923 * @name: a pointer to a NULL-terminated unicode string, that names
1924 * the file to be copied.
1925 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1926 * new name for the file.
1927 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1929 * Copies file @name to @dest_name
1931 * Return value: %TRUE on success, %FALSE otherwise.
1933 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1934 gboolean fail_if_exists)
1936 gchar *utf8_src, *utf8_dest;
1937 int src_fd, dest_fd;
1938 struct stat st, dest_st;
1939 struct utimbuf dest_time;
1940 gboolean ret = TRUE;
1944 DEBUG("%s: name is NULL", __func__);
1946 SetLastError (ERROR_INVALID_NAME);
1950 utf8_src = mono_unicode_to_external (name);
1951 if (utf8_src == NULL) {
1952 DEBUG ("%s: unicode conversion of source returned NULL",
1955 SetLastError (ERROR_INVALID_PARAMETER);
1959 if(dest_name==NULL) {
1960 DEBUG("%s: dest is NULL", __func__);
1963 SetLastError (ERROR_INVALID_NAME);
1967 utf8_dest = mono_unicode_to_external (dest_name);
1968 if (utf8_dest == NULL) {
1969 DEBUG ("%s: unicode conversion of dest returned NULL",
1972 SetLastError (ERROR_INVALID_PARAMETER);
1979 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
1981 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
1989 if (fstat (src_fd, &st) < 0) {
1990 _wapi_set_last_error_from_errno ();
1999 /* Before trying to open/create the dest, we need to report a 'file busy'
2000 * error if src and dest are actually the same file. We do the check here to take
2001 * advantage of the IOMAP capability */
2002 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
2003 st.st_ino == dest_st.st_ino) {
2009 SetLastError (ERROR_SHARING_VIOLATION);
2013 if (fail_if_exists) {
2014 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2016 /* FIXME: it kinda sucks that this code path potentially scans
2017 * the directory twice due to the weird SetLastError()
2019 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2021 /* The file does not exist, try creating it */
2022 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2024 /* Apparently this error is set if we
2025 * overwrite the dest file
2027 SetLastError (ERROR_ALREADY_EXISTS);
2031 _wapi_set_last_error_from_errno ();
2040 if (!write_file (src_fd, dest_fd, &st, TRUE))
2046 dest_time.modtime = st.st_mtime;
2047 dest_time.actime = st.st_atime;
2048 ret_utime = utime (utf8_dest, &dest_time);
2049 if (ret_utime == -1)
2050 DEBUG ("%s: file [%s] utime failed: %s", __func__, utf8_dest, strerror(errno));
2059 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2064 DEBUG ("%s: %s is NULL", __func__, arg_name);
2065 SetLastError (ERROR_INVALID_NAME);
2069 utf8_ret = mono_unicode_to_external (arg);
2070 if (utf8_ret == NULL) {
2071 DEBUG ("%s: unicode conversion of %s returned NULL",
2072 __func__, arg_name);
2073 SetLastError (ERROR_INVALID_PARAMETER);
2081 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2082 const gunichar2 *backupFileName, guint32 replaceFlags,
2083 gpointer exclude, gpointer reserved)
2085 int result, backup_fd = -1,replaced_fd = -1;
2086 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2087 struct stat stBackup;
2088 gboolean ret = FALSE;
2090 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2092 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2093 goto replace_cleanup;
2094 if (backupFileName != NULL) {
2095 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2096 goto replace_cleanup;
2099 if (utf8_backupFileName) {
2100 // Open the backup file for read so we can restore the file if an error occurs.
2101 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2102 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2104 goto replace_cleanup;
2107 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2109 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2110 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2111 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2112 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2115 if (replaced_fd == -1)
2116 goto replace_cleanup;
2118 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2121 goto replace_cleanup;
2127 g_free (utf8_replacedFileName);
2128 g_free (utf8_replacementFileName);
2129 g_free (utf8_backupFileName);
2130 if (backup_fd != -1)
2132 if (replaced_fd != -1)
2133 close (replaced_fd);
2139 * @stdhandle: specifies the file descriptor
2141 * Returns a handle for stdin, stdout, or stderr. Always returns the
2142 * same handle for the same @stdhandle.
2144 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2147 static mono_mutex_t stdhandle_mutex;
2149 gpointer GetStdHandle(WapiStdHandle stdhandle)
2151 struct _WapiHandle_file *file_handle;
2158 case STD_INPUT_HANDLE:
2163 case STD_OUTPUT_HANDLE:
2168 case STD_ERROR_HANDLE:
2174 DEBUG("%s: unknown standard handle type", __func__);
2176 SetLastError (ERROR_INVALID_PARAMETER);
2177 return(INVALID_HANDLE_VALUE);
2180 handle = GINT_TO_POINTER (fd);
2182 pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2183 (void *)&stdhandle_mutex);
2184 thr_ret = mono_mutex_lock (&stdhandle_mutex);
2185 g_assert (thr_ret == 0);
2187 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2188 (gpointer *)&file_handle);
2190 /* Need to create this console handle */
2191 handle = _wapi_stdhandle_create (fd, name);
2193 if (handle == INVALID_HANDLE_VALUE) {
2194 SetLastError (ERROR_NO_MORE_FILES);
2198 /* Add a reference to this handle */
2199 _wapi_handle_ref (handle);
2203 thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2204 g_assert (thr_ret == 0);
2205 pthread_cleanup_pop (0);
2212 * @handle: The file handle to read from. The handle must have
2213 * %GENERIC_READ access.
2214 * @buffer: The buffer to store read data in
2215 * @numbytes: The maximum number of bytes to read
2216 * @bytesread: The actual number of bytes read is stored here. This
2217 * value can be zero if the handle is positioned at the end of the
2219 * @overlapped: points to a required %WapiOverlapped structure if
2220 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2223 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2224 * function reads up to @numbytes bytes from the file from the current
2225 * file position, and stores them in @buffer. If there are not enough
2226 * bytes left in the file, just the amount available will be read.
2227 * The actual number of bytes read is stored in @bytesread.
2229 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2230 * file position is ignored and the read position is taken from data
2231 * in the @overlapped structure.
2233 * Return value: %TRUE if the read succeeds (even if no bytes were
2234 * read due to an attempt to read past the end of the file), %FALSE on
2237 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2238 guint32 *bytesread, WapiOverlapped *overlapped)
2240 WapiHandleType type;
2242 type = _wapi_handle_type (handle);
2244 if(io_ops[type].readfile==NULL) {
2245 SetLastError (ERROR_INVALID_HANDLE);
2249 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2255 * @handle: The file handle to write to. The handle must have
2256 * %GENERIC_WRITE access.
2257 * @buffer: The buffer to read data from.
2258 * @numbytes: The maximum number of bytes to write.
2259 * @byteswritten: The actual number of bytes written is stored here.
2260 * If the handle is positioned at the file end, the length of the file
2261 * is extended. This parameter may be %NULL.
2262 * @overlapped: points to a required %WapiOverlapped structure if
2263 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2266 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2267 * function writes up to @numbytes bytes from @buffer to the file at
2268 * the current file position. If @handle is positioned at the end of
2269 * the file, the file is extended. The actual number of bytes written
2270 * is stored in @byteswritten.
2272 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2273 * file position is ignored and the write position is taken from data
2274 * in the @overlapped structure.
2276 * Return value: %TRUE if the write succeeds, %FALSE on error.
2278 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2279 guint32 *byteswritten, WapiOverlapped *overlapped)
2281 WapiHandleType type;
2283 type = _wapi_handle_type (handle);
2285 if(io_ops[type].writefile==NULL) {
2286 SetLastError (ERROR_INVALID_HANDLE);
2290 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2296 * @handle: Handle to open file. The handle must have
2297 * %GENERIC_WRITE access.
2299 * Flushes buffers of the file and causes all unwritten data to
2302 * Return value: %TRUE on success, %FALSE otherwise.
2304 gboolean FlushFileBuffers(gpointer handle)
2306 WapiHandleType type;
2308 type = _wapi_handle_type (handle);
2310 if(io_ops[type].flushfile==NULL) {
2311 SetLastError (ERROR_INVALID_HANDLE);
2315 return(io_ops[type].flushfile (handle));
2320 * @handle: The file handle to set. The handle must have
2321 * %GENERIC_WRITE access.
2323 * Moves the end-of-file position to the current position of the file
2324 * pointer. This function is used to truncate or extend a file.
2326 * Return value: %TRUE on success, %FALSE otherwise.
2328 gboolean SetEndOfFile(gpointer handle)
2330 WapiHandleType type;
2332 type = _wapi_handle_type (handle);
2334 if (io_ops[type].setendoffile == NULL) {
2335 SetLastError (ERROR_INVALID_HANDLE);
2339 return(io_ops[type].setendoffile (handle));
2344 * @handle: The file handle to set. The handle must have
2345 * %GENERIC_READ or %GENERIC_WRITE access.
2346 * @movedistance: Low 32 bits of a signed value that specifies the
2347 * number of bytes to move the file pointer.
2348 * @highmovedistance: Pointer to the high 32 bits of a signed value
2349 * that specifies the number of bytes to move the file pointer, or
2351 * @method: The starting point for the file pointer move.
2353 * Sets the file pointer of an open file.
2355 * The distance to move the file pointer is calculated from
2356 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2357 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2358 * is the low 32 bits and @highmovedistance a pointer to the high 32
2359 * bits of a 64 bit signed value. A positive distance moves the file
2360 * pointer forward from the position specified by @method; a negative
2361 * distance moves the file pointer backward.
2363 * If the library is compiled without large file support,
2364 * @highmovedistance is ignored and its value is set to zero on a
2365 * successful return.
2367 * Return value: On success, the low 32 bits of the new file pointer.
2368 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2369 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2371 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2372 gint32 *highmovedistance, WapiSeekMethod method)
2374 WapiHandleType type;
2376 type = _wapi_handle_type (handle);
2378 if (io_ops[type].seek == NULL) {
2379 SetLastError (ERROR_INVALID_HANDLE);
2380 return(INVALID_SET_FILE_POINTER);
2383 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2389 * @handle: The file handle to test.
2391 * Finds the type of file @handle.
2393 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2394 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2395 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2396 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2398 WapiFileType GetFileType(gpointer handle)
2400 WapiHandleType type;
2402 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2403 SetLastError (ERROR_INVALID_HANDLE);
2404 return(FILE_TYPE_UNKNOWN);
2407 type = _wapi_handle_type (handle);
2409 if (io_ops[type].getfiletype == NULL) {
2410 SetLastError (ERROR_INVALID_HANDLE);
2411 return(FILE_TYPE_UNKNOWN);
2414 return(io_ops[type].getfiletype ());
2419 * @handle: The file handle to query. The handle must have
2420 * %GENERIC_READ or %GENERIC_WRITE access.
2421 * @highsize: If non-%NULL, the high 32 bits of the file size are
2424 * Retrieves the size of the file @handle.
2426 * If the library is compiled without large file support, @highsize
2427 * has its value set to zero on a successful return.
2429 * Return value: On success, the low 32 bits of the file size. If
2430 * @highsize is non-%NULL then the high 32 bits of the file size are
2431 * stored here. On failure %INVALID_FILE_SIZE is returned.
2433 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2435 WapiHandleType type;
2437 type = _wapi_handle_type (handle);
2439 if (io_ops[type].getfilesize == NULL) {
2440 SetLastError (ERROR_INVALID_HANDLE);
2441 return(INVALID_FILE_SIZE);
2444 return(io_ops[type].getfilesize (handle, highsize));
2449 * @handle: The file handle to query. The handle must have
2450 * %GENERIC_READ access.
2451 * @create_time: Points to a %WapiFileTime structure to receive the
2452 * number of ticks since the epoch that file was created. May be
2454 * @last_access: Points to a %WapiFileTime structure to receive the
2455 * number of ticks since the epoch when file was last accessed. May be
2457 * @last_write: Points to a %WapiFileTime structure to receive the
2458 * number of ticks since the epoch when file was last written to. May
2461 * Finds the number of ticks since the epoch that the file referenced
2462 * by @handle was created, last accessed and last modified. A tick is
2463 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2466 * Create time isn't recorded on POSIX file systems or reported by
2467 * stat(2), so that time is guessed by returning the oldest of the
2470 * Return value: %TRUE on success, %FALSE otherwise.
2472 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2473 WapiFileTime *last_access, WapiFileTime *last_write)
2475 WapiHandleType type;
2477 type = _wapi_handle_type (handle);
2479 if (io_ops[type].getfiletime == NULL) {
2480 SetLastError (ERROR_INVALID_HANDLE);
2484 return(io_ops[type].getfiletime (handle, create_time, last_access,
2490 * @handle: The file handle to set. The handle must have
2491 * %GENERIC_WRITE access.
2492 * @create_time: Points to a %WapiFileTime structure that contains the
2493 * number of ticks since the epoch that the file was created. May be
2495 * @last_access: Points to a %WapiFileTime structure that contains the
2496 * number of ticks since the epoch when the file was last accessed.
2498 * @last_write: Points to a %WapiFileTime structure that contains the
2499 * number of ticks since the epoch when the file was last written to.
2502 * Sets the number of ticks since the epoch that the file referenced
2503 * by @handle was created, last accessed or last modified. A tick is
2504 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2507 * Create time isn't recorded on POSIX file systems, and is ignored.
2509 * Return value: %TRUE on success, %FALSE otherwise.
2511 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2512 const WapiFileTime *last_access,
2513 const WapiFileTime *last_write)
2515 WapiHandleType type;
2517 type = _wapi_handle_type (handle);
2519 if (io_ops[type].setfiletime == NULL) {
2520 SetLastError (ERROR_INVALID_HANDLE);
2524 return(io_ops[type].setfiletime (handle, create_time, last_access,
2528 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2529 * January 1 1601 GMT
2532 #define TICKS_PER_MILLISECOND 10000L
2533 #define TICKS_PER_SECOND 10000000L
2534 #define TICKS_PER_MINUTE 600000000L
2535 #define TICKS_PER_HOUR 36000000000LL
2536 #define TICKS_PER_DAY 864000000000LL
2538 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2540 static const guint16 mon_yday[2][13]={
2541 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2542 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2546 * FileTimeToSystemTime:
2547 * @file_time: Points to a %WapiFileTime structure that contains the
2548 * number of ticks to convert.
2549 * @system_time: Points to a %WapiSystemTime structure to receive the
2552 * Converts a tick count into broken-out time values.
2554 * Return value: %TRUE on success, %FALSE otherwise.
2556 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2557 WapiSystemTime *system_time)
2559 gint64 file_ticks, totaldays, rem, y;
2562 if(system_time==NULL) {
2563 DEBUG("%s: system_time NULL", __func__);
2565 SetLastError (ERROR_INVALID_PARAMETER);
2569 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2570 file_time->dwLowDateTime;
2572 /* Really compares if file_ticks>=0x8000000000000000
2573 * (LLONG_MAX+1) but we're working with a signed value for the
2574 * year and day calculation to work later
2577 DEBUG("%s: file_time too big", __func__);
2579 SetLastError (ERROR_INVALID_PARAMETER);
2583 totaldays=(file_ticks / TICKS_PER_DAY);
2584 rem = file_ticks % TICKS_PER_DAY;
2585 DEBUG("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2587 system_time->wHour=rem/TICKS_PER_HOUR;
2588 rem %= TICKS_PER_HOUR;
2589 DEBUG("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2591 system_time->wMinute = rem / TICKS_PER_MINUTE;
2592 rem %= TICKS_PER_MINUTE;
2593 DEBUG("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2596 system_time->wSecond = rem / TICKS_PER_SECOND;
2597 rem %= TICKS_PER_SECOND;
2598 DEBUG("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2601 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2602 DEBUG("%s: Milliseconds: %d", __func__,
2603 system_time->wMilliseconds);
2605 /* January 1, 1601 was a Monday, according to Emacs calendar */
2606 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2607 DEBUG("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2609 /* This algorithm to find year and month given days from epoch
2614 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2615 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2617 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2618 /* Guess a corrected year, assuming 365 days per year */
2619 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2620 DEBUG("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2623 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2624 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2626 /* Adjust days and y to match the guessed year. */
2627 totaldays -= ((yg - y) * 365
2628 + LEAPS_THRU_END_OF (yg - 1)
2629 - LEAPS_THRU_END_OF (y - 1));
2630 DEBUG("%s: totaldays: %lld", __func__, totaldays);
2632 DEBUG("%s: y: %lld", __func__, y);
2635 system_time->wYear = y;
2636 DEBUG("%s: Year: %d", __func__, system_time->wYear);
2638 ip = mon_yday[isleap(y)];
2640 for(y=11; totaldays < ip[y]; --y) {
2644 DEBUG("%s: totaldays: %lld", __func__, totaldays);
2646 system_time->wMonth = y + 1;
2647 DEBUG("%s: Month: %d", __func__, system_time->wMonth);
2649 system_time->wDay = totaldays + 1;
2650 DEBUG("%s: Day: %d", __func__, system_time->wDay);
2655 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2657 struct _WapiHandle_find find_handle = {0};
2659 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2662 if (pattern == NULL) {
2663 DEBUG ("%s: pattern is NULL", __func__);
2665 SetLastError (ERROR_PATH_NOT_FOUND);
2666 return(INVALID_HANDLE_VALUE);
2669 utf8_pattern = mono_unicode_to_external (pattern);
2670 if (utf8_pattern == NULL) {
2671 DEBUG ("%s: unicode conversion returned NULL", __func__);
2673 SetLastError (ERROR_INVALID_NAME);
2674 return(INVALID_HANDLE_VALUE);
2677 DEBUG ("%s: looking for [%s]", __func__, utf8_pattern);
2679 /* Figure out which bit of the pattern is the directory */
2680 dir_part = _wapi_dirname (utf8_pattern);
2681 entry_part = _wapi_basename (utf8_pattern);
2684 /* Don't do this check for now, it breaks if directories
2685 * really do have metachars in their names (see bug 58116).
2686 * FIXME: Figure out a better solution to keep some checks...
2688 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2689 SetLastError (ERROR_INVALID_NAME);
2691 g_free (entry_part);
2692 g_free (utf8_pattern);
2693 return(INVALID_HANDLE_VALUE);
2697 /* The pattern can specify a directory or a set of files.
2699 * The pattern can have wildcard characters ? and *, but only
2700 * in the section after the last directory delimiter. (Return
2701 * ERROR_INVALID_NAME if there are wildcards in earlier path
2702 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2703 * means "match one character", "??" seems to mean "match one
2704 * or two characters", "???" seems to mean "match one, two or
2705 * three characters", etc. Windows will also try and match
2706 * the mangled "short name" of files, so 8 character patterns
2707 * with wildcards will show some surprising results.
2709 * All the written documentation I can find says that '?'
2710 * should only match one character, and doesn't mention '??',
2711 * '???' etc. I'm going to assume that the strict behaviour
2712 * (ie '???' means three and only three characters) is the
2713 * correct one, because that lets me use fnmatch(3) rather
2714 * than mess around with regexes.
2717 find_handle.namelist = NULL;
2718 result = _wapi_io_scandir (dir_part, entry_part,
2719 &find_handle.namelist);
2722 /* No files, which windows seems to call
2725 SetLastError (ERROR_FILE_NOT_FOUND);
2726 g_free (utf8_pattern);
2727 g_free (entry_part);
2729 return (INVALID_HANDLE_VALUE);
2733 #ifdef DEBUG_ENABLED
2734 gint errnum = errno;
2736 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2737 DEBUG ("%s: scandir error: %s", __func__,
2738 g_strerror (errnum));
2739 g_free (utf8_pattern);
2740 g_free (entry_part);
2742 return (INVALID_HANDLE_VALUE);
2745 g_free (utf8_pattern);
2746 g_free (entry_part);
2748 DEBUG ("%s: Got %d matches", __func__, result);
2750 find_handle.dir_part = dir_part;
2751 find_handle.num = result;
2752 find_handle.count = 0;
2754 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2755 if (handle == _WAPI_HANDLE_INVALID) {
2756 g_warning ("%s: error creating find handle", __func__);
2758 g_free (entry_part);
2759 g_free (utf8_pattern);
2760 SetLastError (ERROR_GEN_FAILURE);
2762 return(INVALID_HANDLE_VALUE);
2765 if (handle != INVALID_HANDLE_VALUE &&
2766 !FindNextFile (handle, find_data)) {
2768 SetLastError (ERROR_NO_MORE_FILES);
2769 handle = INVALID_HANDLE_VALUE;
2775 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2777 struct _WapiHandle_find *find_handle;
2779 struct stat buf, linkbuf;
2782 gchar *utf8_filename, *utf8_basename;
2783 gunichar2 *utf16_basename;
2787 gboolean ret = FALSE;
2789 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2790 (gpointer *)&find_handle);
2792 g_warning ("%s: error looking up find handle %p", __func__,
2794 SetLastError (ERROR_INVALID_HANDLE);
2798 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2800 thr_ret = _wapi_handle_lock_handle (handle);
2801 g_assert (thr_ret == 0);
2804 if (find_handle->count >= find_handle->num) {
2805 SetLastError (ERROR_NO_MORE_FILES);
2809 /* stat next match */
2811 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2813 result = _wapi_stat (filename, &buf);
2814 if (result == -1 && errno == ENOENT) {
2815 /* Might be a dangling symlink */
2816 result = _wapi_lstat (filename, &buf);
2820 DEBUG ("%s: stat failed: %s", __func__, filename);
2826 #ifndef __native_client__
2827 result = _wapi_lstat (filename, &linkbuf);
2829 DEBUG ("%s: lstat failed: %s", __func__, filename);
2836 utf8_filename = mono_utf8_from_external (filename);
2837 if (utf8_filename == NULL) {
2838 /* We couldn't turn this filename into utf8 (eg the
2839 * encoding of the name wasn't convertible), so just
2842 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2849 DEBUG ("%s: Found [%s]", __func__, utf8_filename);
2851 /* fill data block */
2853 if (buf.st_mtime < buf.st_ctime)
2854 create_time = buf.st_mtime;
2856 create_time = buf.st_ctime;
2858 #ifdef __native_client__
2859 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, NULL);
2861 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2864 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2865 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2866 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2868 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2869 find_data->nFileSizeHigh = 0;
2870 find_data->nFileSizeLow = 0;
2872 find_data->nFileSizeHigh = buf.st_size >> 32;
2873 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2876 find_data->dwReserved0 = 0;
2877 find_data->dwReserved1 = 0;
2879 utf8_basename = _wapi_basename (utf8_filename);
2880 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2882 if(utf16_basename==NULL) {
2883 g_free (utf8_basename);
2884 g_free (utf8_filename);
2889 /* utf16 is 2 * utf8 */
2892 memset (find_data->cFileName, '\0', (MAX_PATH*2));
2894 /* Truncating a utf16 string like this might leave the last
2897 memcpy (find_data->cFileName, utf16_basename,
2898 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
2900 find_data->cAlternateFileName [0] = 0; /* not used */
2902 g_free (utf8_basename);
2903 g_free (utf8_filename);
2904 g_free (utf16_basename);
2907 thr_ret = _wapi_handle_unlock_handle (handle);
2908 g_assert (thr_ret == 0);
2909 pthread_cleanup_pop (0);
2916 * @wapi_handle: the find handle to close.
2918 * Closes find handle @wapi_handle
2920 * Return value: %TRUE on success, %FALSE otherwise.
2922 gboolean FindClose (gpointer handle)
2924 struct _WapiHandle_find *find_handle;
2928 if (handle == NULL) {
2929 SetLastError (ERROR_INVALID_HANDLE);
2933 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2934 (gpointer *)&find_handle);
2936 g_warning ("%s: error looking up find handle %p", __func__,
2938 SetLastError (ERROR_INVALID_HANDLE);
2942 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2944 thr_ret = _wapi_handle_lock_handle (handle);
2945 g_assert (thr_ret == 0);
2947 g_strfreev (find_handle->namelist);
2948 g_free (find_handle->dir_part);
2950 thr_ret = _wapi_handle_unlock_handle (handle);
2951 g_assert (thr_ret == 0);
2952 pthread_cleanup_pop (0);
2954 _wapi_handle_unref (handle);
2961 * @name: a pointer to a NULL-terminated unicode string, that names
2962 * the directory to be created.
2963 * @security: ignored for now
2965 * Creates directory @name
2967 * Return value: %TRUE on success, %FALSE otherwise.
2969 gboolean CreateDirectory (const gunichar2 *name,
2970 WapiSecurityAttributes *security)
2976 DEBUG("%s: name is NULL", __func__);
2978 SetLastError (ERROR_INVALID_NAME);
2982 utf8_name = mono_unicode_to_external (name);
2983 if (utf8_name == NULL) {
2984 DEBUG ("%s: unicode conversion returned NULL", __func__);
2986 SetLastError (ERROR_INVALID_NAME);
2990 result = _wapi_mkdir (utf8_name, 0777);
2997 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3004 * @name: a pointer to a NULL-terminated unicode string, that names
3005 * the directory to be removed.
3007 * Removes directory @name
3009 * Return value: %TRUE on success, %FALSE otherwise.
3011 gboolean RemoveDirectory (const gunichar2 *name)
3017 DEBUG("%s: name is NULL", __func__);
3019 SetLastError (ERROR_INVALID_NAME);
3023 utf8_name = mono_unicode_to_external (name);
3024 if (utf8_name == NULL) {
3025 DEBUG ("%s: unicode conversion returned NULL", __func__);
3027 SetLastError (ERROR_INVALID_NAME);
3031 result = _wapi_rmdir (utf8_name);
3033 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3044 * GetFileAttributes:
3045 * @name: a pointer to a NULL-terminated unicode filename.
3047 * Gets the attributes for @name;
3049 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3051 guint32 GetFileAttributes (const gunichar2 *name)
3054 struct stat buf, linkbuf;
3059 DEBUG("%s: name is NULL", __func__);
3061 SetLastError (ERROR_INVALID_NAME);
3065 utf8_name = mono_unicode_to_external (name);
3066 if (utf8_name == NULL) {
3067 DEBUG ("%s: unicode conversion returned NULL", __func__);
3069 SetLastError (ERROR_INVALID_PARAMETER);
3070 return (INVALID_FILE_ATTRIBUTES);
3073 result = _wapi_stat (utf8_name, &buf);
3074 if (result == -1 && errno == ENOENT) {
3075 /* Might be a dangling symlink... */
3076 result = _wapi_lstat (utf8_name, &buf);
3080 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3082 return (INVALID_FILE_ATTRIBUTES);
3085 #ifndef __native_client__
3086 result = _wapi_lstat (utf8_name, &linkbuf);
3088 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3090 return (INVALID_FILE_ATTRIBUTES);
3094 #ifdef __native_client__
3095 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, NULL);
3097 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3106 * GetFileAttributesEx:
3107 * @name: a pointer to a NULL-terminated unicode filename.
3108 * @level: must be GetFileExInfoStandard
3109 * @info: pointer to a WapiFileAttributesData structure
3111 * Gets attributes, size and filetimes for @name;
3113 * Return value: %TRUE on success, %FALSE on failure
3115 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3118 WapiFileAttributesData *data;
3120 struct stat buf, linkbuf;
3124 if (level != GetFileExInfoStandard) {
3125 DEBUG ("%s: info level %d not supported.", __func__,
3128 SetLastError (ERROR_INVALID_PARAMETER);
3133 DEBUG("%s: name is NULL", __func__);
3135 SetLastError (ERROR_INVALID_NAME);
3139 utf8_name = mono_unicode_to_external (name);
3140 if (utf8_name == NULL) {
3141 DEBUG ("%s: unicode conversion returned NULL", __func__);
3143 SetLastError (ERROR_INVALID_PARAMETER);
3147 result = _wapi_stat (utf8_name, &buf);
3148 if (result == -1 && errno == ENOENT) {
3149 /* Might be a dangling symlink... */
3150 result = _wapi_lstat (utf8_name, &buf);
3154 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3159 result = _wapi_lstat (utf8_name, &linkbuf);
3161 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3166 /* fill data block */
3168 data = (WapiFileAttributesData *)info;
3170 if (buf.st_mtime < buf.st_ctime)
3171 create_time = buf.st_mtime;
3173 create_time = buf.st_ctime;
3175 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3181 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3182 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3183 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3185 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3186 data->nFileSizeHigh = 0;
3187 data->nFileSizeLow = 0;
3190 data->nFileSizeHigh = buf.st_size >> 32;
3191 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3199 * @name: name of file
3200 * @attrs: attributes to set
3202 * Changes the attributes on a named file.
3204 * Return value: %TRUE on success, %FALSE on failure.
3206 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3208 /* FIXME: think of something clever to do on unix */
3214 * Currently we only handle one *internal* case, with a value that is
3215 * not standard: 0x80000000, which means `set executable bit'
3219 DEBUG("%s: name is NULL", __func__);
3221 SetLastError (ERROR_INVALID_NAME);
3225 utf8_name = mono_unicode_to_external (name);
3226 if (utf8_name == NULL) {
3227 DEBUG ("%s: unicode conversion returned NULL", __func__);
3229 SetLastError (ERROR_INVALID_NAME);
3233 result = _wapi_stat (utf8_name, &buf);
3234 if (result == -1 && errno == ENOENT) {
3235 /* Might be a dangling symlink... */
3236 result = _wapi_lstat (utf8_name, &buf);
3240 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3245 /* Contrary to the documentation, ms allows NORMAL to be
3246 * specified along with other attributes, so dont bother to
3247 * catch that case here.
3249 if (attrs & FILE_ATTRIBUTE_READONLY) {
3250 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3252 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3255 /* Ignore the other attributes for now */
3257 if (attrs & 0x80000000){
3258 mode_t exec_mask = 0;
3260 if ((buf.st_mode & S_IRUSR) != 0)
3261 exec_mask |= S_IXUSR;
3263 if ((buf.st_mode & S_IRGRP) != 0)
3264 exec_mask |= S_IXGRP;
3266 if ((buf.st_mode & S_IROTH) != 0)
3267 exec_mask |= S_IXOTH;
3269 result = chmod (utf8_name, buf.st_mode | exec_mask);
3271 /* Don't bother to reset executable (might need to change this
3281 * GetCurrentDirectory
3282 * @length: size of the buffer
3283 * @buffer: pointer to buffer that recieves path
3285 * Retrieves the current directory for the current process.
3287 * Return value: number of characters in buffer on success, zero on failure
3289 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3291 gunichar2 *utf16_path;
3295 #ifdef __native_client__
3296 gchar *path = g_get_current_dir ();
3297 if (length < strlen(path) + 1 || path == NULL)
3299 memcpy (buffer, path, strlen(path) + 1);
3301 if (getcwd ((char*)buffer, length) == NULL) {
3302 if (errno == ERANGE) { /*buffer length is not big enough */
3303 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*/
3306 utf16_path = mono_unicode_from_external (path, &bytes);
3307 g_free (utf16_path);
3311 _wapi_set_last_error_from_errno ();
3316 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3317 count = (bytes/2)+1;
3318 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3320 /* Add the terminator */
3321 memset (buffer, '\0', bytes+2);
3322 memcpy (buffer, utf16_path, bytes);
3324 g_free (utf16_path);
3330 * SetCurrentDirectory
3331 * @path: path to new directory
3333 * Changes the directory path for the current process.
3335 * Return value: %TRUE on success, %FALSE on failure.
3337 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3343 SetLastError (ERROR_INVALID_PARAMETER);
3347 utf8_path = mono_unicode_to_external (path);
3348 if (_wapi_chdir (utf8_path) != 0) {
3349 _wapi_set_last_error_from_errno ();
3359 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3360 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3362 struct _WapiHandle_file pipe_read_handle = {0};
3363 struct _WapiHandle_file pipe_write_handle = {0};
3364 gpointer read_handle;
3365 gpointer write_handle;
3369 mono_once (&io_ops_once, io_ops_init);
3371 DEBUG ("%s: Creating pipe", __func__);
3375 DEBUG ("%s: Error creating pipe: %s", __func__,
3378 _wapi_set_last_error_from_errno ();
3382 if (filedes[0] >= _wapi_fd_reserve ||
3383 filedes[1] >= _wapi_fd_reserve) {
3384 DEBUG ("%s: File descriptor is too big", __func__);
3386 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3394 /* filedes[0] is open for reading, filedes[1] for writing */
3396 pipe_read_handle.fd = filedes [0];
3397 pipe_read_handle.fileaccess = GENERIC_READ;
3398 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3400 if (read_handle == _WAPI_HANDLE_INVALID) {
3401 g_warning ("%s: error creating pipe read handle", __func__);
3404 SetLastError (ERROR_GEN_FAILURE);
3409 pipe_write_handle.fd = filedes [1];
3410 pipe_write_handle.fileaccess = GENERIC_WRITE;
3411 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3412 &pipe_write_handle);
3413 if (write_handle == _WAPI_HANDLE_INVALID) {
3414 g_warning ("%s: error creating pipe write handle", __func__);
3415 _wapi_handle_unref (read_handle);
3419 SetLastError (ERROR_GEN_FAILURE);
3424 *readpipe = read_handle;
3425 *writepipe = write_handle;
3427 DEBUG ("%s: Returning pipe: read handle %p, write handle %p",
3428 __func__, read_handle, write_handle);
3433 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3435 gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3436 gunichar2 *tmpdir16=NULL;
3441 if(tmpdir[strlen (tmpdir)]!='/') {
3443 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3446 tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3447 if(tmpdir16==NULL) {
3454 DEBUG ("%s: Size %d smaller than needed (%ld)",
3455 __func__, len, dirlen+1);
3459 /* Add the terminator */
3460 memset (buf, '\0', bytes+2);
3461 memcpy (buf, tmpdir16, bytes);
3467 if(tmpdir16!=NULL) {
3475 #ifdef HAVE_GETFSSTAT
3476 /* Darwin has getfsstat */
3477 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3479 struct statfs *stats;
3482 glong length, total = 0;
3484 n = getfsstat (NULL, 0, MNT_NOWAIT);
3487 size = n * sizeof (struct statfs);
3488 stats = (struct statfs *) g_malloc (size);
3491 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3495 for (i = 0; i < n; i++){
3496 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3497 if (total + length < len){
3498 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3499 buf [total+length] = 0;
3502 total += length + 1;
3511 /* In-place octal sequence replacement */
3513 unescape_octal (gchar *str)
3522 while (*rptr != '\0') {
3523 if (*rptr == '\\') {
3526 c = (*(rptr++) - '0') << 6;
3527 c += (*(rptr++) - '0') << 3;
3528 c += *(rptr++) - '0';
3530 } else if (wptr != rptr) {
3538 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3541 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3542 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3543 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3548 guint32 buffer_index;
3549 guint32 mountpoint_index;
3550 guint32 field_number;
3551 guint32 allocated_size;
3552 guint32 fsname_index;
3553 guint32 fstype_index;
3554 gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3555 gchar *mountpoint_allocated;
3556 gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3557 gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3558 gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3561 gboolean check_mount_source;
3562 } LinuxMountInfoParseState;
3564 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3565 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3566 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3567 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3569 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3573 LinuxMountInfoParseState state;
3574 gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3576 memset (buf, 0, len * sizeof (gunichar2));
3577 fd = open ("/proc/self/mountinfo", O_RDONLY);
3579 parser = GetLogicalDriveStrings_MountInfo;
3581 fd = open ("/proc/mounts", O_RDONLY);
3583 parser = GetLogicalDriveStrings_Mounts;
3587 ret = GetLogicalDriveStrings_Mtab (len, buf);
3591 memset (&state, 0, sizeof (LinuxMountInfoParseState));
3592 state.field_number = 1;
3593 state.delimiter = ' ';
3595 while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3596 state.buffer_index = 0;
3598 while ((*parser)(len, buf, &state)) {
3599 if (state.buffer [state.buffer_index] == '\n') {
3600 gboolean quit = add_drive_string (len, buf, &state);
3601 state.field_number = 1;
3602 state.buffer_index++;
3603 if (state.mountpoint_allocated) {
3604 g_free (state.mountpoint_allocated);
3605 state.mountpoint_allocated = NULL;
3622 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3626 if (state->field_number == 1)
3627 state->check_mount_source = TRUE;
3629 while (state->buffer_index < (guint32)state->nbytes) {
3630 if (state->buffer [state->buffer_index] == state->delimiter) {
3631 state->field_number++;
3632 switch (state->field_number) {
3634 state->mountpoint_index = 0;
3638 if (state->mountpoint_allocated)
3639 state->mountpoint_allocated [state->mountpoint_index] = 0;
3641 state->mountpoint [state->mountpoint_index] = 0;
3645 ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3647 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3649 state->buffer_index = state->nbytes;
3652 state->buffer_index++;
3654 } else if (state->buffer [state->buffer_index] == '\n')
3657 switch (state->field_number) {
3659 if (state->check_mount_source) {
3660 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3661 /* We can ignore the rest, it's a device
3663 state->check_mount_source = FALSE;
3664 state->fsname [state->fsname_index++] = '/';
3667 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3668 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3673 append_to_mountpoint (state);
3677 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3678 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3682 state->buffer_index++;
3688 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3690 while (state->buffer_index < (guint32)state->nbytes) {
3691 if (state->buffer [state->buffer_index] == state->delimiter) {
3692 state->field_number++;
3693 switch (state->field_number) {
3695 state->mountpoint_index = 0;
3699 if (state->mountpoint_allocated)
3700 state->mountpoint_allocated [state->mountpoint_index] = 0;
3702 state->mountpoint [state->mountpoint_index] = 0;
3706 state->delimiter = '-';
3710 state->delimiter = ' ';
3714 state->check_mount_source = TRUE;
3717 state->buffer_index++;
3719 } else if (state->buffer [state->buffer_index] == '\n')
3722 switch (state->field_number) {
3724 append_to_mountpoint (state);
3728 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3729 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3733 if (state->check_mount_source) {
3734 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3735 /* We can ignore the rest, it's a device
3737 state->check_mount_source = FALSE;
3738 state->fsname [state->fsname_index++] = '/';
3741 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3742 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3747 state->buffer_index++;
3754 append_to_mountpoint (LinuxMountInfoParseState *state)
3756 gchar ch = state->buffer [state->buffer_index];
3757 if (state->mountpoint_allocated) {
3758 if (state->mountpoint_index >= state->allocated_size) {
3759 guint32 newsize = (state->allocated_size << 1) + 1;
3760 gchar *newbuf = g_malloc0 (newsize * sizeof (gchar));
3762 memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3763 g_free (state->mountpoint_allocated);
3764 state->mountpoint_allocated = newbuf;
3765 state->allocated_size = newsize;
3767 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3769 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3770 state->allocated_size = (state->mountpoint_index << 1) + 1;
3771 state->mountpoint_allocated = g_malloc0 (state->allocated_size * sizeof (gchar));
3772 memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3773 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3775 state->mountpoint [state->mountpoint_index++] = ch;
3780 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3782 gboolean quit = FALSE;
3783 gboolean ignore_entry;
3785 if (state->fsname_index == 1 && state->fsname [0] == '/')
3786 ignore_entry = FALSE;
3787 else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0)
3788 ignore_entry = TRUE;
3789 else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3790 /* Ignore GNOME's gvfs */
3791 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3792 ignore_entry = TRUE;
3794 ignore_entry = FALSE;
3796 ignore_entry = TRUE;
3798 if (!ignore_entry) {
3801 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3803 unescape_octal (mountpoint);
3804 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3805 if (state->total + length + 1 > len) {
3807 state->total = len * 2;
3810 memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3811 state->total += length;
3815 state->fsname_index = 0;
3816 state->fstype_index = 0;
3822 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3824 return GetLogicalDriveStrings_Mtab (len, buf);
3828 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3831 gunichar2 *ptr, *dir;
3832 glong length, total = 0;
3836 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3841 /* Sigh, mntent and friends don't work well.
3842 * It stops on the first line that doesn't begin with a '/'.
3843 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3844 fp = fopen ("/etc/mtab", "rt");
3846 fp = fopen ("/etc/mnttab", "rt");
3852 while (fgets (buffer, 512, fp) != NULL) {
3856 splitted = g_strsplit (buffer, " ", 0);
3857 if (!*splitted || !*(splitted + 1)) {
3858 g_strfreev (splitted);
3862 unescape_octal (*(splitted + 1));
3863 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3864 g_strfreev (splitted);
3865 if (total + length + 1 > len) {
3868 return len * 2; /* guess */
3871 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3873 total += length + 1;
3878 /* Commented out, does not work with my mtab!!! - Gonz */
3879 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3883 gunichar2 *ptr, *dir;
3884 glong len, total = 0;
3887 fp = setmntent ("/etc/mtab", "rt");
3889 fp = setmntent ("/etc/mnttab", "rt");
3895 while ((mnt = getmntent (fp)) != NULL) {
3896 g_print ("GOT %s\n", mnt->mnt_dir);
3897 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3898 if (total + len + 1 > len) {
3899 return len * 2; /* guess */
3902 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3914 #if (defined(HAVE_STATVFS) || defined(HAVE_STATFS)) && !defined(PLATFORM_ANDROID)
3915 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3916 WapiULargeInteger *total_number_of_bytes,
3917 WapiULargeInteger *total_number_of_free_bytes)
3920 struct statvfs fsstat;
3921 #elif defined(HAVE_STATFS)
3922 struct statfs fsstat;
3924 gboolean isreadonly;
3925 gchar *utf8_path_name;
3927 unsigned long block_size;
3929 if (path_name == NULL) {
3930 utf8_path_name = g_strdup (g_get_current_dir());
3931 if (utf8_path_name == NULL) {
3932 SetLastError (ERROR_DIRECTORY);
3937 utf8_path_name = mono_unicode_to_external (path_name);
3938 if (utf8_path_name == NULL) {
3939 DEBUG("%s: unicode conversion returned NULL", __func__);
3941 SetLastError (ERROR_INVALID_NAME);
3948 ret = statvfs (utf8_path_name, &fsstat);
3949 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
3950 block_size = fsstat.f_frsize;
3951 #elif defined(HAVE_STATFS)
3952 ret = statfs (utf8_path_name, &fsstat);
3953 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
3954 block_size = fsstat.f_bsize;
3956 } while(ret == -1 && errno == EINTR);
3958 g_free(utf8_path_name);
3961 _wapi_set_last_error_from_errno ();
3962 DEBUG ("%s: statvfs failed: %s", __func__, strerror (errno));
3966 /* total number of free bytes for non-root */
3967 if (free_bytes_avail != NULL) {
3969 free_bytes_avail->QuadPart = 0;
3972 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
3976 /* total number of bytes available for non-root */
3977 if (total_number_of_bytes != NULL) {
3978 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
3981 /* total number of bytes available for root */
3982 if (total_number_of_free_bytes != NULL) {
3984 total_number_of_free_bytes->QuadPart = 0;
3987 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
3994 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3995 WapiULargeInteger *total_number_of_bytes,
3996 WapiULargeInteger *total_number_of_free_bytes)
3998 if (free_bytes_avail != NULL) {
3999 free_bytes_avail->QuadPart = (guint64) -1;
4002 if (total_number_of_bytes != NULL) {
4003 total_number_of_bytes->QuadPart = (guint64) -1;
4006 if (total_number_of_free_bytes != NULL) {
4007 total_number_of_free_bytes->QuadPart = (guint64) -1;
4015 * General Unix support
4020 const long fstypeid;
4022 const gchar* fstype;
4025 static _wapi_drive_type _wapi_drive_types[] = {
4027 { DRIVE_REMOTE, "afp" },
4028 { DRIVE_REMOTE, "autofs" },
4029 { DRIVE_CDROM, "cddafs" },
4030 { DRIVE_CDROM, "cd9660" },
4031 { DRIVE_RAMDISK, "devfs" },
4032 { DRIVE_FIXED, "exfat" },
4033 { DRIVE_RAMDISK, "fdesc" },
4034 { DRIVE_REMOTE, "ftp" },
4035 { DRIVE_FIXED, "hfs" },
4036 { DRIVE_FIXED, "msdos" },
4037 { DRIVE_REMOTE, "nfs" },
4038 { DRIVE_FIXED, "ntfs" },
4039 { DRIVE_REMOTE, "smbfs" },
4040 { DRIVE_FIXED, "udf" },
4041 { DRIVE_REMOTE, "webdav" },
4042 { DRIVE_UNKNOWN, NULL }
4044 { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
4045 { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
4046 { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
4047 { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
4048 { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
4049 { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
4050 { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
4051 { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
4052 { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
4053 { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
4054 { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
4055 { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
4056 { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
4057 { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
4058 { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
4059 { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
4060 { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
4061 { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4062 { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4063 { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4064 { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4065 { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4066 { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4067 { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4068 { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4069 { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4070 { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4071 { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4072 { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4073 { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4074 { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4075 { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4076 { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4077 { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4078 { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4079 { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4080 { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4081 { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4082 { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4083 { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4084 { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4085 { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4086 { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4087 { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4088 { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4089 { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4090 { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4091 { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4092 { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4093 { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4094 { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4095 { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4096 { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4097 { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4098 { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4099 { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4100 { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4101 { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4102 { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4103 { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4104 { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4105 { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4106 { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4107 { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4108 { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4109 { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4110 { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4111 { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4112 { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4113 { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4114 { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4115 { DRIVE_UNKNOWN, 0, NULL}
4117 { DRIVE_RAMDISK, "ramfs" },
4118 { DRIVE_RAMDISK, "tmpfs" },
4119 { DRIVE_RAMDISK, "proc" },
4120 { DRIVE_RAMDISK, "sysfs" },
4121 { DRIVE_RAMDISK, "debugfs" },
4122 { DRIVE_RAMDISK, "devpts" },
4123 { DRIVE_RAMDISK, "securityfs" },
4124 { DRIVE_CDROM, "iso9660" },
4125 { DRIVE_FIXED, "ext2" },
4126 { DRIVE_FIXED, "ext3" },
4127 { DRIVE_FIXED, "ext4" },
4128 { DRIVE_FIXED, "sysv" },
4129 { DRIVE_FIXED, "reiserfs" },
4130 { DRIVE_FIXED, "ufs" },
4131 { DRIVE_FIXED, "vfat" },
4132 { DRIVE_FIXED, "msdos" },
4133 { DRIVE_FIXED, "udf" },
4134 { DRIVE_FIXED, "hfs" },
4135 { DRIVE_FIXED, "hpfs" },
4136 { DRIVE_FIXED, "qnx4" },
4137 { DRIVE_FIXED, "ntfs" },
4138 { DRIVE_FIXED, "ntfs-3g" },
4139 { DRIVE_REMOTE, "smbfs" },
4140 { DRIVE_REMOTE, "fuse" },
4141 { DRIVE_REMOTE, "nfs" },
4142 { DRIVE_REMOTE, "nfs4" },
4143 { DRIVE_REMOTE, "cifs" },
4144 { DRIVE_REMOTE, "ncpfs" },
4145 { DRIVE_REMOTE, "coda" },
4146 { DRIVE_REMOTE, "afs" },
4147 { DRIVE_UNKNOWN, NULL }
4152 static guint32 _wapi_get_drive_type(long f_type)
4154 _wapi_drive_type *current;
4156 current = &_wapi_drive_types[0];
4157 while (current->drive_type != DRIVE_UNKNOWN) {
4158 if (current->fstypeid == f_type)
4159 return current->drive_type;
4163 return DRIVE_UNKNOWN;
4166 static guint32 _wapi_get_drive_type(const gchar* fstype)
4168 _wapi_drive_type *current;
4170 current = &_wapi_drive_types[0];
4171 while (current->drive_type != DRIVE_UNKNOWN) {
4172 if (strcmp (current->fstype, fstype) == 0)
4178 return current->drive_type;
4182 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4184 GetDriveTypeFromPath (const char *utf8_root_path_name)
4188 if (statfs (utf8_root_path_name, &buf) == -1)
4189 return DRIVE_UNKNOWN;
4191 return _wapi_get_drive_type (buf.f_fstypename);
4193 return _wapi_get_drive_type (buf.f_type);
4198 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4205 fp = fopen ("/etc/mtab", "rt");
4207 fp = fopen ("/etc/mnttab", "rt");
4209 return(DRIVE_UNKNOWN);
4212 drive_type = DRIVE_NO_ROOT_DIR;
4213 while (fgets (buffer, 512, fp) != NULL) {
4214 splitted = g_strsplit (buffer, " ", 0);
4215 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4216 g_strfreev (splitted);
4220 /* compare given root_path_name with the one from mtab,
4221 if length of utf8_root_path_name is zero it must be the root dir */
4222 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4223 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4224 drive_type = _wapi_get_drive_type (*(splitted + 2));
4225 /* it is possible this path might be mounted again with
4226 a known type...keep looking */
4227 if (drive_type != DRIVE_UNKNOWN) {
4228 g_strfreev (splitted);
4233 g_strfreev (splitted);
4241 guint32 GetDriveType(const gunichar2 *root_path_name)
4243 gchar *utf8_root_path_name;
4246 if (root_path_name == NULL) {
4247 utf8_root_path_name = g_strdup (g_get_current_dir());
4248 if (utf8_root_path_name == NULL) {
4249 return(DRIVE_NO_ROOT_DIR);
4253 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4254 if (utf8_root_path_name == NULL) {
4255 DEBUG("%s: unicode conversion returned NULL", __func__);
4256 return(DRIVE_NO_ROOT_DIR);
4259 /* strip trailing slash for compare below */
4260 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4261 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4264 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4265 g_free (utf8_root_path_name);
4267 return (drive_type);
4271 get_fstypename (gchar *utfpath)
4273 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4276 _wapi_drive_type *current;
4278 if (statfs (utfpath, &stat) == -1)
4281 return g_strdup (stat.f_fstypename);
4283 current = &_wapi_drive_types[0];
4284 while (current->drive_type != DRIVE_UNKNOWN) {
4285 if (stat.f_type == current->fstypeid)
4286 return g_strdup (current->fstype);
4296 /* Linux has struct statfs which has a different layout */
4297 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__)
4299 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4303 gboolean status = FALSE;
4306 // We only support getting the file system type
4307 if (fsbuffer == NULL)
4310 utfpath = mono_unicode_to_external (path);
4311 if ((fstypename = get_fstypename (utfpath)) != NULL){
4312 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4313 if (ret != NULL && len < fsbuffersize){
4314 memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4320 g_free (fstypename);
4329 _wapi_io_init (void)
4331 mono_mutex_init (&stdhandle_mutex);