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.
18 #ifdef HAVE_SYS_STATVFS_H
19 #include <sys/statvfs.h>
20 #elif defined(HAVE_SYS_STATFS_H)
21 #include <sys/statfs.h>
23 #if defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H)
24 #include <sys/param.h>
25 #include <sys/mount.h>
27 #include <sys/types.h>
33 #include <sys/ioctl.h>
37 #include <mono/io-layer/wapi.h>
38 #include <mono/io-layer/wapi-private.h>
39 #include <mono/io-layer/handles-private.h>
40 #include <mono/io-layer/io-private.h>
41 #include <mono/io-layer/timefuncs-private.h>
42 #include <mono/io-layer/thread-private.h>
43 #include <mono/io-layer/io-portability.h>
44 #include <mono/utils/strenc.h>
48 static void file_close (gpointer handle, gpointer data);
49 static WapiFileType file_getfiletype(void);
50 static gboolean file_read(gpointer handle, gpointer buffer,
51 guint32 numbytes, guint32 *bytesread,
52 WapiOverlapped *overlapped);
53 static gboolean file_write(gpointer handle, gconstpointer buffer,
54 guint32 numbytes, guint32 *byteswritten,
55 WapiOverlapped *overlapped);
56 static gboolean file_flush(gpointer handle);
57 static guint32 file_seek(gpointer handle, gint32 movedistance,
58 gint32 *highmovedistance, WapiSeekMethod method);
59 static gboolean file_setendoffile(gpointer handle);
60 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
61 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
62 WapiFileTime *last_access,
63 WapiFileTime *last_write);
64 static gboolean file_setfiletime(gpointer handle,
65 const WapiFileTime *create_time,
66 const WapiFileTime *last_access,
67 const WapiFileTime *last_write);
69 /* File handle is only signalled for overlapped IO */
70 struct _WapiHandleOps _wapi_file_ops = {
71 file_close, /* close */
75 NULL, /* special_wait */
79 void _wapi_file_details (gpointer handle_info)
81 struct _WapiHandle_file *file = (struct _WapiHandle_file *)handle_info;
83 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
85 file->fileaccess&GENERIC_READ?'R':'.',
86 file->fileaccess&GENERIC_WRITE?'W':'.',
87 file->fileaccess&GENERIC_EXECUTE?'X':'.',
88 file->sharemode&FILE_SHARE_READ?'R':'.',
89 file->sharemode&FILE_SHARE_WRITE?'W':'.',
90 file->sharemode&FILE_SHARE_DELETE?'D':'.',
94 static void console_close (gpointer handle, gpointer data);
95 static WapiFileType console_getfiletype(void);
96 static gboolean console_read(gpointer handle, gpointer buffer,
97 guint32 numbytes, guint32 *bytesread,
98 WapiOverlapped *overlapped);
99 static gboolean console_write(gpointer handle, gconstpointer buffer,
100 guint32 numbytes, guint32 *byteswritten,
101 WapiOverlapped *overlapped);
103 /* Console is mostly the same as file, except it can block waiting for
106 struct _WapiHandleOps _wapi_console_ops = {
107 console_close, /* close */
111 NULL, /* special_wait */
115 void _wapi_console_details (gpointer handle_info)
117 _wapi_file_details (handle_info);
120 /* Find handle has no ops.
122 struct _WapiHandleOps _wapi_find_ops = {
127 NULL, /* special_wait */
131 static void pipe_close (gpointer handle, gpointer data);
132 static WapiFileType pipe_getfiletype (void);
133 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
134 guint32 *bytesread, WapiOverlapped *overlapped);
135 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
136 guint32 numbytes, guint32 *byteswritten,
137 WapiOverlapped *overlapped);
141 struct _WapiHandleOps _wapi_pipe_ops = {
142 pipe_close, /* close */
146 NULL, /* special_wait */
150 void _wapi_pipe_details (gpointer handle_info)
152 _wapi_file_details (handle_info);
155 static const struct {
156 /* File, console and pipe handles */
157 WapiFileType (*getfiletype)(void);
159 /* File, console and pipe handles */
160 gboolean (*readfile)(gpointer handle, gpointer buffer,
161 guint32 numbytes, guint32 *bytesread,
162 WapiOverlapped *overlapped);
163 gboolean (*writefile)(gpointer handle, gconstpointer buffer,
164 guint32 numbytes, guint32 *byteswritten,
165 WapiOverlapped *overlapped);
166 gboolean (*flushfile)(gpointer handle);
169 guint32 (*seek)(gpointer handle, gint32 movedistance,
170 gint32 *highmovedistance, WapiSeekMethod method);
171 gboolean (*setendoffile)(gpointer handle);
172 guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
173 gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
174 WapiFileTime *last_access,
175 WapiFileTime *last_write);
176 gboolean (*setfiletime)(gpointer handle,
177 const WapiFileTime *create_time,
178 const WapiFileTime *last_access,
179 const WapiFileTime *last_write);
180 } io_ops[WAPI_HANDLE_COUNT]={
181 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
184 file_read, file_write,
185 file_flush, file_seek,
191 {console_getfiletype,
194 NULL, NULL, NULL, NULL, NULL, NULL},
196 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
198 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
200 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
202 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
203 /* socket (will need at least read and write) */
204 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
206 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
208 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
213 NULL, NULL, NULL, NULL, NULL, NULL},
216 static mono_once_t io_ops_once=MONO_ONCE_INIT;
217 static gboolean lock_while_writing = FALSE;
219 static void io_ops_init (void)
221 /* _wapi_handle_register_capabilities (WAPI_HANDLE_FILE, */
222 /* WAPI_HANDLE_CAP_WAIT); */
223 /* _wapi_handle_register_capabilities (WAPI_HANDLE_CONSOLE, */
224 /* WAPI_HANDLE_CAP_WAIT); */
226 if (g_getenv ("MONO_STRICT_IO_EMULATION") != NULL) {
227 lock_while_writing = TRUE;
231 /* Some utility functions.
234 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
241 /* FIXME: this could definitely be better, but there seems to
242 * be no pattern to the attributes that are set
245 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
246 if (S_ISSOCK (buf->st_mode))
247 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
249 filename = _wapi_basename (pathname);
251 if (S_ISDIR (buf->st_mode)) {
252 attrs = FILE_ATTRIBUTE_DIRECTORY;
253 if (!(buf->st_mode & S_IWUSR)) {
254 attrs |= FILE_ATTRIBUTE_READONLY;
256 if (filename[0] == '.') {
257 attrs |= FILE_ATTRIBUTE_HIDDEN;
260 if (!(buf->st_mode & S_IWUSR)) {
261 attrs = FILE_ATTRIBUTE_READONLY;
263 if (filename[0] == '.') {
264 attrs |= FILE_ATTRIBUTE_HIDDEN;
266 } else if (filename[0] == '.') {
267 attrs = FILE_ATTRIBUTE_HIDDEN;
269 attrs = FILE_ATTRIBUTE_NORMAL;
274 if (S_ISLNK (lbuf->st_mode)) {
275 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
285 _wapi_set_last_error_from_errno (void)
287 SetLastError (_wapi_get_win32_file_error (errno));
290 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
293 if (errno == ENOENT) {
294 /* Check the path - if it's a missing directory then
295 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
301 dirname = _wapi_dirname (path);
303 dirname = g_strdup (dir);
306 if (_wapi_access (dirname, F_OK) == 0) {
307 SetLastError (ERROR_FILE_NOT_FOUND);
309 SetLastError (ERROR_PATH_NOT_FOUND);
314 _wapi_set_last_error_from_errno ();
320 static void file_close (gpointer handle, gpointer data)
322 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
325 g_message("%s: closing file handle %p [%s]", __func__, handle,
326 file_handle->filename);
329 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
330 _wapi_unlink (file_handle->filename);
332 g_free (file_handle->filename);
334 if (file_handle->share_info)
335 _wapi_handle_share_release (file_handle->share_info);
337 close (GPOINTER_TO_UINT(handle));
340 static WapiFileType file_getfiletype(void)
342 return(FILE_TYPE_DISK);
345 static gboolean file_read(gpointer handle, gpointer buffer,
346 guint32 numbytes, guint32 *bytesread,
347 WapiOverlapped *overlapped)
349 struct _WapiHandle_file *file_handle;
351 int fd = GPOINTER_TO_UINT(handle);
354 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
355 (gpointer *)&file_handle);
357 g_warning ("%s: error looking up file handle %p", __func__,
359 SetLastError (ERROR_INVALID_HANDLE);
363 if(bytesread!=NULL) {
367 if(!(file_handle->fileaccess & GENERIC_READ) &&
368 !(file_handle->fileaccess & GENERIC_ALL)) {
370 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
371 __func__, handle, file_handle->fileaccess);
374 SetLastError (ERROR_ACCESS_DENIED);
379 ret = read (fd, buffer, numbytes);
380 } while (ret == -1 && errno == EINTR &&
381 !_wapi_thread_cur_apc_pending());
387 g_message("%s: read of handle %p error: %s", __func__,
388 handle, strerror(err));
390 SetLastError (_wapi_get_win32_file_error (err));
394 if (bytesread != NULL) {
401 static gboolean file_write(gpointer handle, gconstpointer buffer,
402 guint32 numbytes, guint32 *byteswritten,
403 WapiOverlapped *overlapped G_GNUC_UNUSED)
405 struct _WapiHandle_file *file_handle;
408 off_t current_pos = 0;
409 int fd = GPOINTER_TO_UINT(handle);
411 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
412 (gpointer *)&file_handle);
414 g_warning ("%s: error looking up file handle %p", __func__,
416 SetLastError (ERROR_INVALID_HANDLE);
420 if(byteswritten!=NULL) {
424 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
425 !(file_handle->fileaccess & GENERIC_ALL)) {
427 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
430 SetLastError (ERROR_ACCESS_DENIED);
434 if (lock_while_writing) {
435 /* Need to lock the region we're about to write to,
436 * because we only do advisory locking on POSIX
439 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
440 if (current_pos == -1) {
442 g_message ("%s: handle %p lseek failed: %s", __func__,
443 handle, strerror (errno));
445 _wapi_set_last_error_from_errno ();
449 if (_wapi_lock_file_region (fd, current_pos,
450 numbytes) == FALSE) {
451 /* The error has already been set */
457 ret = write (fd, buffer, numbytes);
458 } while (ret == -1 && errno == EINTR &&
459 !_wapi_thread_cur_apc_pending());
461 if (lock_while_writing) {
462 _wapi_unlock_file_region (fd, current_pos, numbytes);
466 if (errno == EINTR) {
469 _wapi_set_last_error_from_errno ();
472 g_message("%s: write of handle %p error: %s",
473 __func__, handle, strerror(errno));
479 if (byteswritten != NULL) {
485 static gboolean file_flush(gpointer handle)
487 struct _WapiHandle_file *file_handle;
490 int fd = GPOINTER_TO_UINT(handle);
492 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
493 (gpointer *)&file_handle);
495 g_warning ("%s: error looking up file handle %p", __func__,
497 SetLastError (ERROR_INVALID_HANDLE);
501 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
502 !(file_handle->fileaccess & GENERIC_ALL)) {
504 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
507 SetLastError (ERROR_ACCESS_DENIED);
514 g_message("%s: fsync of handle %p error: %s", __func__, handle,
518 _wapi_set_last_error_from_errno ();
525 static guint32 file_seek(gpointer handle, gint32 movedistance,
526 gint32 *highmovedistance, WapiSeekMethod method)
528 struct _WapiHandle_file *file_handle;
530 off_t offset, newpos;
533 int fd = GPOINTER_TO_UINT(handle);
535 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
536 (gpointer *)&file_handle);
538 g_warning ("%s: error looking up file handle %p", __func__,
540 SetLastError (ERROR_INVALID_HANDLE);
541 return(INVALID_SET_FILE_POINTER);
544 if(!(file_handle->fileaccess & GENERIC_READ) &&
545 !(file_handle->fileaccess & GENERIC_WRITE) &&
546 !(file_handle->fileaccess & GENERIC_ALL)) {
548 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
551 SetLastError (ERROR_ACCESS_DENIED);
552 return(INVALID_SET_FILE_POINTER);
567 g_message("%s: invalid seek type %d", __func__, method);
570 SetLastError (ERROR_INVALID_PARAMETER);
571 return(INVALID_SET_FILE_POINTER);
574 #ifdef HAVE_LARGE_FILE_SUPPORT
575 if(highmovedistance==NULL) {
578 g_message("%s: setting offset to %lld (low %d)", __func__,
579 offset, movedistance);
582 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
585 g_message("%s: setting offset to %lld 0x%llx (high %d 0x%x, low %d 0x%x)", __func__, offset, offset, *highmovedistance, *highmovedistance, movedistance, movedistance);
593 #ifdef HAVE_LARGE_FILE_SUPPORT
594 g_message("%s: moving handle %p by %lld bytes from %d", __func__,
595 handle, offset, whence);
597 g_message("%s: moving handle %p fd %d by %ld bytes from %d", __func__,
598 handle, offset, whence);
602 newpos=lseek(fd, offset, whence);
605 g_message("%s: lseek on handle %p returned error %s",
606 __func__, handle, strerror(errno));
609 _wapi_set_last_error_from_errno ();
610 return(INVALID_SET_FILE_POINTER);
614 #ifdef HAVE_LARGE_FILE_SUPPORT
615 g_message("%s: lseek returns %lld", __func__, newpos);
617 g_message ("%s: lseek returns %ld", __func__, newpos);
621 #ifdef HAVE_LARGE_FILE_SUPPORT
622 ret=newpos & 0xFFFFFFFF;
623 if(highmovedistance!=NULL) {
624 *highmovedistance=newpos>>32;
628 if(highmovedistance!=NULL) {
629 /* Accurate, but potentially dodgy :-) */
635 g_message ("%s: move of handle %p returning %d/%d", __func__,
636 handle, ret, highmovedistance==NULL?0:*highmovedistance);
642 static gboolean file_setendoffile(gpointer handle)
644 struct _WapiHandle_file *file_handle;
649 int fd = GPOINTER_TO_UINT(handle);
651 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
652 (gpointer *)&file_handle);
654 g_warning ("%s: error looking up file handle %p", __func__,
656 SetLastError (ERROR_INVALID_HANDLE);
660 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
661 !(file_handle->fileaccess & GENERIC_ALL)) {
663 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
666 SetLastError (ERROR_ACCESS_DENIED);
670 /* Find the current file position, and the file length. If
671 * the file position is greater than the length, write to
672 * extend the file with a hole. If the file position is less
673 * than the length, truncate the file.
676 ret=fstat(fd, &statbuf);
679 g_message ("%s: handle %p fstat failed: %s", __func__,
680 handle, strerror(errno));
683 _wapi_set_last_error_from_errno ();
686 size=statbuf.st_size;
688 pos=lseek(fd, (off_t)0, SEEK_CUR);
691 g_message("%s: handle %p lseek failed: %s", __func__,
692 handle, strerror(errno));
695 _wapi_set_last_error_from_errno ();
699 #ifdef FTRUNCATE_DOESNT_EXTEND
700 /* I haven't bothered to write the configure.in stuff for this
701 * because I don't know if any platform needs it. I'm leaving
702 * this code just in case though
705 /* Extend the file. Use write() here, because some
706 * manuals say that ftruncate() behaviour is undefined
707 * when the file needs extending. The POSIX spec says
708 * that on XSI-conformant systems it extends, so if
709 * every system we care about conforms, then we can
713 ret = write (fd, "", 1);
714 } while (ret == -1 && errno == EINTR &&
715 !_wapi_thread_cur_apc_pending());
719 g_message("%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
722 _wapi_set_last_error_from_errno ();
726 /* And put the file position back after the write */
727 ret = lseek (fd, pos, SEEK_SET);
730 g_message ("%s: handle %p second lseek failed: %s",
731 __func__, handle, strerror(errno));
734 _wapi_set_last_error_from_errno ();
740 /* always truncate, because the extend write() adds an extra
741 * byte to the end of the file
744 ret=ftruncate(fd, pos);
746 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
749 g_message("%s: handle %p ftruncate failed: %s", __func__,
750 handle, strerror(errno));
753 _wapi_set_last_error_from_errno ();
760 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
762 struct _WapiHandle_file *file_handle;
767 int fd = GPOINTER_TO_UINT(handle);
769 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
770 (gpointer *)&file_handle);
772 g_warning ("%s: error looking up file handle %p", __func__,
774 SetLastError (ERROR_INVALID_HANDLE);
775 return(INVALID_FILE_SIZE);
778 if(!(file_handle->fileaccess & GENERIC_READ) &&
779 !(file_handle->fileaccess & GENERIC_WRITE) &&
780 !(file_handle->fileaccess & GENERIC_ALL)) {
782 g_message("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
785 SetLastError (ERROR_ACCESS_DENIED);
786 return(INVALID_FILE_SIZE);
789 /* If the file has a size with the low bits 0xFFFFFFFF the
790 * caller can't tell if this is an error, so clear the error
793 SetLastError (ERROR_SUCCESS);
795 ret = fstat(fd, &statbuf);
798 g_message ("%s: handle %p fstat failed: %s", __func__,
799 handle, strerror(errno));
802 _wapi_set_last_error_from_errno ();
803 return(INVALID_FILE_SIZE);
806 /* fstat indicates block devices as zero-length, so go a different path */
808 if (S_ISBLK(statbuf.st_mode)) {
810 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
812 g_message ("%s: handle %p ioctl BLKGETSIZE64 failed: %s",
813 __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;
826 g_message ("%s: Returning block device size %d/%d",
827 __func__, size, *highsize);
834 #ifdef HAVE_LARGE_FILE_SUPPORT
835 size = statbuf.st_size & 0xFFFFFFFF;
836 if (highsize != NULL) {
837 *highsize = statbuf.st_size>>32;
840 if (highsize != NULL) {
841 /* Accurate, but potentially dodgy :-) */
844 size = statbuf.st_size;
848 g_message ("%s: Returning size %d/%d", __func__, size, *highsize);
854 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
855 WapiFileTime *last_access,
856 WapiFileTime *last_write)
858 struct _WapiHandle_file *file_handle;
861 guint64 create_ticks, access_ticks, write_ticks;
863 int fd = GPOINTER_TO_UINT(handle);
865 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
866 (gpointer *)&file_handle);
868 g_warning ("%s: error looking up file handle %p", __func__,
870 SetLastError (ERROR_INVALID_HANDLE);
874 if(!(file_handle->fileaccess & GENERIC_READ) &&
875 !(file_handle->fileaccess & GENERIC_ALL)) {
877 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
878 __func__, handle, file_handle->fileaccess);
881 SetLastError (ERROR_ACCESS_DENIED);
885 ret=fstat(fd, &statbuf);
888 g_message("%s: handle %p fstat failed: %s", __func__, handle,
892 _wapi_set_last_error_from_errno ();
897 g_message("%s: atime: %ld ctime: %ld mtime: %ld", __func__,
898 statbuf.st_atime, statbuf.st_ctime,
902 /* Try and guess a meaningful create time by using the older
905 /* The magic constant comes from msdn documentation
906 * "Converting a time_t Value to a File Time"
908 if(statbuf.st_atime < statbuf.st_ctime) {
909 create_ticks=((guint64)statbuf.st_atime*10000000)
910 + 116444736000000000ULL;
912 create_ticks=((guint64)statbuf.st_ctime*10000000)
913 + 116444736000000000ULL;
916 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
917 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
920 g_message("%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
921 access_ticks, create_ticks, write_ticks);
924 if(create_time!=NULL) {
925 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
926 create_time->dwHighDateTime = create_ticks >> 32;
929 if(last_access!=NULL) {
930 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
931 last_access->dwHighDateTime = access_ticks >> 32;
934 if(last_write!=NULL) {
935 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
936 last_write->dwHighDateTime = write_ticks >> 32;
942 static gboolean file_setfiletime(gpointer handle,
943 const WapiFileTime *create_time G_GNUC_UNUSED,
944 const WapiFileTime *last_access,
945 const WapiFileTime *last_write)
947 struct _WapiHandle_file *file_handle;
949 struct utimbuf utbuf;
951 guint64 access_ticks, write_ticks;
953 int fd = GPOINTER_TO_UINT(handle);
955 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
956 (gpointer *)&file_handle);
958 g_warning ("%s: error looking up file handle %p", __func__,
960 SetLastError (ERROR_INVALID_HANDLE);
964 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
965 !(file_handle->fileaccess & GENERIC_ALL)) {
967 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
970 SetLastError (ERROR_ACCESS_DENIED);
974 if(file_handle->filename == NULL) {
976 g_message("%s: handle %p unknown filename", __func__, handle);
979 SetLastError (ERROR_INVALID_HANDLE);
983 /* Get the current times, so we can put the same times back in
984 * the event that one of the FileTime structs is NULL
986 ret=fstat (fd, &statbuf);
989 g_message("%s: handle %p fstat failed: %s", __func__, handle,
993 SetLastError (ERROR_INVALID_PARAMETER);
997 if(last_access!=NULL) {
998 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
999 last_access->dwLowDateTime;
1000 /* This is (time_t)0. We can actually go to INT_MIN,
1001 * but this will do for now.
1003 if (access_ticks < 116444736000000000ULL) {
1005 g_message ("%s: attempt to set access time too early",
1008 SetLastError (ERROR_INVALID_PARAMETER);
1012 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
1014 utbuf.actime=statbuf.st_atime;
1017 if(last_write!=NULL) {
1018 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
1019 last_write->dwLowDateTime;
1020 /* This is (time_t)0. We can actually go to INT_MIN,
1021 * but this will do for now.
1023 if (write_ticks < 116444736000000000ULL) {
1025 g_message ("%s: attempt to set write time too early",
1028 SetLastError (ERROR_INVALID_PARAMETER);
1032 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1034 utbuf.modtime=statbuf.st_mtime;
1038 g_message ("%s: setting handle %p access %ld write %ld", __func__,
1039 handle, utbuf.actime, utbuf.modtime);
1042 ret = _wapi_utime (file_handle->filename, &utbuf);
1045 g_message ("%s: handle %p [%s] utime failed: %s", __func__,
1046 handle, file_handle->filename, strerror(errno));
1049 SetLastError (ERROR_INVALID_PARAMETER);
1056 static void console_close (gpointer handle, gpointer data)
1058 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1061 g_message("%s: closing console handle %p", __func__, handle);
1064 g_free (console_handle->filename);
1066 close (GPOINTER_TO_UINT(handle));
1069 static WapiFileType console_getfiletype(void)
1071 return(FILE_TYPE_CHAR);
1074 static gboolean console_read(gpointer handle, gpointer buffer,
1075 guint32 numbytes, guint32 *bytesread,
1076 WapiOverlapped *overlapped G_GNUC_UNUSED)
1078 struct _WapiHandle_file *console_handle;
1081 int fd = GPOINTER_TO_UINT(handle);
1083 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1084 (gpointer *)&console_handle);
1086 g_warning ("%s: error looking up console handle %p", __func__,
1088 SetLastError (ERROR_INVALID_HANDLE);
1092 if(bytesread!=NULL) {
1096 if(!(console_handle->fileaccess & GENERIC_READ) &&
1097 !(console_handle->fileaccess & GENERIC_ALL)) {
1099 g_message ("%s: handle %p doesn't have GENERIC_READ access: %u",
1100 __func__, handle, console_handle->fileaccess);
1103 SetLastError (ERROR_ACCESS_DENIED);
1108 ret=read(fd, buffer, numbytes);
1109 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1113 g_message("%s: read of handle %p error: %s", __func__, handle,
1117 _wapi_set_last_error_from_errno ();
1121 if(bytesread!=NULL) {
1128 static gboolean console_write(gpointer handle, gconstpointer buffer,
1129 guint32 numbytes, guint32 *byteswritten,
1130 WapiOverlapped *overlapped G_GNUC_UNUSED)
1132 struct _WapiHandle_file *console_handle;
1135 int fd = GPOINTER_TO_UINT(handle);
1137 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1138 (gpointer *)&console_handle);
1140 g_warning ("%s: error looking up console handle %p", __func__,
1142 SetLastError (ERROR_INVALID_HANDLE);
1146 if(byteswritten!=NULL) {
1150 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1151 !(console_handle->fileaccess & GENERIC_ALL)) {
1153 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, console_handle->fileaccess);
1156 SetLastError (ERROR_ACCESS_DENIED);
1161 ret = write(fd, buffer, numbytes);
1162 } while (ret == -1 && errno == EINTR &&
1163 !_wapi_thread_cur_apc_pending());
1166 if (errno == EINTR) {
1169 _wapi_set_last_error_from_errno ();
1172 g_message ("%s: write of handle %p error: %s",
1173 __func__, handle, strerror(errno));
1179 if(byteswritten!=NULL) {
1186 static void pipe_close (gpointer handle, gpointer data G_GNUC_UNUSED)
1189 g_message("%s: closing pipe handle %p", __func__, handle);
1192 /* No filename with pipe handles */
1194 close(GPOINTER_TO_UINT(handle));
1197 static WapiFileType pipe_getfiletype(void)
1199 return(FILE_TYPE_PIPE);
1202 static gboolean pipe_read (gpointer handle, gpointer buffer,
1203 guint32 numbytes, guint32 *bytesread,
1204 WapiOverlapped *overlapped G_GNUC_UNUSED)
1206 struct _WapiHandle_file *pipe_handle;
1209 int fd = GPOINTER_TO_UINT(handle);
1211 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1212 (gpointer *)&pipe_handle);
1214 g_warning ("%s: error looking up pipe handle %p", __func__,
1216 SetLastError (ERROR_INVALID_HANDLE);
1220 if(bytesread!=NULL) {
1224 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1225 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1227 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
1228 __func__, handle, pipe_handle->fileaccess);
1231 SetLastError (ERROR_ACCESS_DENIED);
1236 g_message ("%s: reading up to %d bytes from pipe %p", __func__,
1241 ret=read(fd, buffer, numbytes);
1242 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1245 if (errno == EINTR) {
1248 _wapi_set_last_error_from_errno ();
1251 g_message("%s: read of handle %p error: %s", __func__,
1252 handle, strerror(errno));
1260 g_message ("%s: read %d bytes from pipe", __func__, ret);
1263 if(bytesread!=NULL) {
1270 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1271 guint32 numbytes, guint32 *byteswritten,
1272 WapiOverlapped *overlapped G_GNUC_UNUSED)
1274 struct _WapiHandle_file *pipe_handle;
1277 int fd = GPOINTER_TO_UINT(handle);
1279 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1280 (gpointer *)&pipe_handle);
1282 g_warning ("%s: error looking up pipe handle %p", __func__,
1284 SetLastError (ERROR_INVALID_HANDLE);
1288 if(byteswritten!=NULL) {
1292 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1293 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1295 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, pipe_handle->fileaccess);
1298 SetLastError (ERROR_ACCESS_DENIED);
1303 g_message ("%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1308 ret = write (fd, buffer, numbytes);
1309 } while (ret == -1 && errno == EINTR &&
1310 !_wapi_thread_cur_apc_pending());
1313 if (errno == EINTR) {
1316 _wapi_set_last_error_from_errno ();
1319 g_message("%s: write of handle %p error: %s", __func__,
1320 handle, strerror(errno));
1326 if(byteswritten!=NULL) {
1333 static int convert_flags(guint32 fileaccess, guint32 createmode)
1337 switch(fileaccess) {
1344 case GENERIC_READ|GENERIC_WRITE:
1349 g_message("%s: Unknown access type 0x%x", __func__,
1355 switch(createmode) {
1357 flags|=O_CREAT|O_EXCL;
1360 flags|=O_CREAT|O_TRUNC;
1367 case TRUNCATE_EXISTING:
1372 g_message("%s: Unknown create mode 0x%x", __func__,
1382 static mode_t convert_perms(guint32 sharemode)
1386 if(sharemode&FILE_SHARE_READ) {
1389 if(sharemode&FILE_SHARE_WRITE) {
1397 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1399 struct _WapiFileShare **share_info)
1401 gboolean file_already_shared;
1402 guint32 file_existing_share, file_existing_access;
1404 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);
1406 if (file_already_shared) {
1407 /* The reference to this share info was incremented
1408 * when we looked it up, so be careful to put it back
1409 * if we conclude we can't use this file.
1411 if (file_existing_share == 0) {
1412 /* Quick and easy, no possibility to share */
1414 g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
1417 _wapi_handle_share_release (*share_info);
1422 if (((file_existing_share == FILE_SHARE_READ) &&
1423 (fileaccess != GENERIC_READ)) ||
1424 ((file_existing_share == FILE_SHARE_WRITE) &&
1425 (fileaccess != GENERIC_WRITE))) {
1426 /* New access mode doesn't match up */
1428 g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
1431 _wapi_handle_share_release (*share_info);
1436 if (((file_existing_access & GENERIC_READ) &&
1437 !(sharemode & FILE_SHARE_READ)) ||
1438 ((file_existing_access & GENERIC_WRITE) &&
1439 !(sharemode & FILE_SHARE_WRITE))) {
1440 /* New share mode doesn't match up */
1442 g_message ("%s: Access mode prevents open: requested share: 0x%x, file has access: 0x%x", __func__, sharemode, file_existing_access);
1445 _wapi_handle_share_release (*share_info);
1451 g_message ("%s: New file!", __func__);
1458 static gboolean share_check (struct stat *statbuf, guint32 sharemode,
1460 struct _WapiFileShare **share_info, int fd)
1462 if (share_allows_open (statbuf, sharemode, fileaccess,
1463 share_info) == TRUE) {
1467 /* Got a share violation. Double check that the file is still
1468 * open by someone, in case a process crashed while still
1469 * holding a file handle. This will also cope with someone
1470 * using Mono.Posix to close the file. This is cheaper and
1471 * less intrusive to other processes than initiating a handle
1475 _wapi_handle_check_share (*share_info, fd);
1476 if (share_allows_open (statbuf, sharemode, fileaccess,
1477 share_info) == TRUE) {
1481 /* Still violating. It's possible that a process crashed
1482 * while still holding a file handle, and that a non-mono
1483 * process has the file open. (For example, C-c mcs while
1484 * editing a source file.) As a last resort, run a handle
1485 * collection, which will remove stale share entries.
1487 _wapi_handle_collect ();
1489 return(share_allows_open (statbuf, sharemode, fileaccess, share_info));
1494 * @name: a pointer to a NULL-terminated unicode string, that names
1495 * the file or other object to create.
1496 * @fileaccess: specifies the file access mode
1497 * @sharemode: whether the file should be shared. This parameter is
1498 * currently ignored.
1499 * @security: Ignored for now.
1500 * @createmode: specifies whether to create a new file, whether to
1501 * overwrite an existing file, whether to truncate the file, etc.
1502 * @attrs: specifies file attributes and flags. On win32 attributes
1503 * are characteristics of the file, not the handle, and are ignored
1504 * when an existing file is opened. Flags give the library hints on
1505 * how to process a file to optimise performance.
1506 * @template: the handle of an open %GENERIC_READ file that specifies
1507 * attributes to apply to a newly created file, ignoring @attrs.
1508 * Normally this parameter is NULL. This parameter is ignored when an
1509 * existing file is opened.
1511 * Creates a new file handle. This only applies to normal files:
1512 * pipes are handled by CreatePipe(), and console handles are created
1513 * with GetStdHandle().
1515 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1517 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1518 guint32 sharemode, WapiSecurityAttributes *security,
1519 guint32 createmode, guint32 attrs,
1520 gpointer template G_GNUC_UNUSED)
1522 struct _WapiHandle_file file_handle = {0};
1524 int flags=convert_flags(fileaccess, createmode);
1525 /*mode_t perms=convert_perms(sharemode);*/
1526 /* we don't use sharemode, because that relates to sharing of
1527 * the file when the file is open and is already handled by
1528 * other code, perms instead are the on-disk permissions and
1529 * this is a sane default.
1535 struct stat statbuf;
1537 mono_once (&io_ops_once, io_ops_init);
1539 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1542 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1543 SetLastError (ERROR_ENCRYPTION_FAILED);
1544 return INVALID_HANDLE_VALUE;
1549 g_message ("%s: name is NULL", __func__);
1552 SetLastError (ERROR_INVALID_NAME);
1553 return(INVALID_HANDLE_VALUE);
1556 filename = mono_unicode_to_external (name);
1557 if (filename == NULL) {
1559 g_message("%s: unicode conversion returned NULL", __func__);
1562 SetLastError (ERROR_INVALID_NAME);
1563 return(INVALID_HANDLE_VALUE);
1567 g_message ("%s: Opening %s with share 0x%x and access 0x%x", __func__,
1568 filename, sharemode, fileaccess);
1571 fd = _wapi_open (filename, flags, perms);
1573 /* If we were trying to open a directory with write permissions
1574 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1575 * EISDIR. However, this is a bit bogus because calls to
1576 * manipulate the directory (e.g. SetFileTime) will still work on
1577 * the directory because they use other API calls
1578 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1579 * to open the directory again without write permission.
1581 if (fd == -1 && errno == EISDIR)
1583 /* Try again but don't try to make it writable */
1584 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1589 g_message("%s: Error opening file %s: %s", __func__, filename,
1592 _wapi_set_last_path_error_from_errno (NULL, filename);
1595 return(INVALID_HANDLE_VALUE);
1598 if (fd >= _wapi_fd_reserve) {
1600 g_message ("%s: File descriptor is too big", __func__);
1603 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1608 return(INVALID_HANDLE_VALUE);
1611 ret = fstat (fd, &statbuf);
1614 g_message ("%s: fstat error of file %s: %s", __func__,
1615 filename, strerror (errno));
1617 _wapi_set_last_error_from_errno ();
1621 return(INVALID_HANDLE_VALUE);
1624 if (share_check (&statbuf, sharemode, fileaccess,
1625 &file_handle.share_info, fd) == FALSE) {
1626 SetLastError (ERROR_SHARING_VIOLATION);
1630 return (INVALID_HANDLE_VALUE);
1632 if (file_handle.share_info == NULL) {
1633 /* No space, so no more files can be opened */
1635 g_message ("%s: No space in the share table", __func__);
1638 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1642 return(INVALID_HANDLE_VALUE);
1645 file_handle.filename = filename;
1647 if(security!=NULL) {
1648 //file_handle->security_attributes=_wapi_handle_scratch_store (
1649 //security, sizeof(WapiSecurityAttributes));
1652 file_handle.fileaccess=fileaccess;
1653 file_handle.sharemode=sharemode;
1654 file_handle.attrs=attrs;
1656 #ifdef HAVE_POSIX_FADVISE
1657 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1658 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1659 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1660 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1664 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1666 if (S_ISFIFO (statbuf.st_mode)) {
1667 handle_type = WAPI_HANDLE_PIPE;
1668 } else if (S_ISCHR (statbuf.st_mode)) {
1669 handle_type = WAPI_HANDLE_CONSOLE;
1671 handle_type = WAPI_HANDLE_FILE;
1674 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1675 if (handle == _WAPI_HANDLE_INVALID) {
1676 g_warning ("%s: error creating file handle", __func__);
1680 SetLastError (ERROR_GEN_FAILURE);
1681 return(INVALID_HANDLE_VALUE);
1685 g_message("%s: returning handle %p", __func__, handle);
1693 * @name: a pointer to a NULL-terminated unicode string, that names
1694 * the file to be deleted.
1696 * Deletes file @name.
1698 * Return value: %TRUE on success, %FALSE otherwise.
1700 gboolean DeleteFile(const gunichar2 *name)
1704 gboolean ret = FALSE;
1707 struct stat statbuf;
1708 struct _WapiFileShare *shareinfo;
1713 g_message("%s: name is NULL", __func__);
1716 SetLastError (ERROR_INVALID_NAME);
1720 filename=mono_unicode_to_external(name);
1721 if(filename==NULL) {
1723 g_message("%s: unicode conversion returned NULL", __func__);
1726 SetLastError (ERROR_INVALID_NAME);
1730 attrs = GetFileAttributes (name);
1731 if (attrs == INVALID_FILE_ATTRIBUTES) {
1733 g_message ("%s: file attributes error", __func__);
1735 /* Error set by GetFileAttributes() */
1740 if (attrs & FILE_ATTRIBUTE_READONLY) {
1742 g_message ("%s: file %s is readonly", __func__, filename);
1744 SetLastError (ERROR_ACCESS_DENIED);
1750 /* Check to make sure sharing allows us to open the file for
1751 * writing. See bug 323389.
1753 * Do the checks that don't need an open file descriptor, for
1754 * simplicity's sake. If we really have to do the full checks
1755 * then we can implement that later.
1757 if (_wapi_stat (filename, &statbuf) < 0) {
1758 _wapi_set_last_path_error_from_errno (NULL, filename);
1763 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1764 &shareinfo) == FALSE) {
1765 SetLastError (ERROR_SHARING_VIOLATION);
1770 _wapi_handle_share_release (shareinfo);
1773 retval = _wapi_unlink (filename);
1776 _wapi_set_last_path_error_from_errno (NULL, filename);
1788 * @name: a pointer to a NULL-terminated unicode string, that names
1789 * the file to be moved.
1790 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1791 * new name for the file.
1793 * Renames file @name to @dest_name.
1794 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1795 * when it is the same file as the source. In that case it silently succeeds.
1797 * Return value: %TRUE on success, %FALSE otherwise.
1799 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1801 gchar *utf8_name, *utf8_dest_name;
1802 int result, errno_copy;
1803 struct stat stat_src, stat_dest;
1804 gboolean ret = FALSE;
1805 struct _WapiFileShare *shareinfo;
1809 g_message("%s: name is NULL", __func__);
1812 SetLastError (ERROR_INVALID_NAME);
1816 utf8_name = mono_unicode_to_external (name);
1817 if (utf8_name == NULL) {
1819 g_message ("%s: unicode conversion returned NULL", __func__);
1822 SetLastError (ERROR_INVALID_NAME);
1826 if(dest_name==NULL) {
1828 g_message("%s: name is NULL", __func__);
1832 SetLastError (ERROR_INVALID_NAME);
1836 utf8_dest_name = mono_unicode_to_external (dest_name);
1837 if (utf8_dest_name == NULL) {
1839 g_message ("%s: unicode conversion returned NULL", __func__);
1843 SetLastError (ERROR_INVALID_NAME);
1848 * In C# land we check for the existence of src, but not for dest.
1849 * We check it here and return the failure if dest exists and is not
1850 * the same file as src.
1852 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1853 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1854 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1856 g_free (utf8_dest_name);
1861 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1862 if (stat_dest.st_dev != stat_src.st_dev ||
1863 stat_dest.st_ino != stat_src.st_ino) {
1865 g_free (utf8_dest_name);
1866 SetLastError (ERROR_ALREADY_EXISTS);
1871 /* Check to make sure sharing allows us to open the file for
1872 * writing. See bug 377049.
1874 * Do the checks that don't need an open file descriptor, for
1875 * simplicity's sake. If we really have to do the full checks
1876 * then we can implement that later.
1878 if (share_allows_open (&stat_src, 0, GENERIC_WRITE,
1879 &shareinfo) == FALSE) {
1880 SetLastError (ERROR_SHARING_VIOLATION);
1884 _wapi_handle_share_release (shareinfo);
1886 result = _wapi_rename (utf8_name, utf8_dest_name);
1890 switch(errno_copy) {
1892 SetLastError (ERROR_ALREADY_EXISTS);
1896 /* Ignore here, it is dealt with below */
1900 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1905 g_free (utf8_dest_name);
1907 if (result != 0 && errno_copy == EXDEV) {
1908 if (S_ISDIR (stat_src.st_mode)) {
1909 SetLastError (ERROR_NOT_SAME_DEVICE);
1912 /* Try a copy to the new location, and delete the source */
1913 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1914 /* CopyFile will set the error */
1918 return(DeleteFile (name));
1929 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1933 int buf_size = st_src->st_blksize;
1935 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1936 buf = (char *) malloc (buf_size);
1939 remain = read (src_fd, buf, buf_size);
1941 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1945 _wapi_set_last_error_from_errno ();
1955 while (remain > 0) {
1956 if ((n = write (dest_fd, wbuf, remain)) < 0) {
1957 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1961 _wapi_set_last_error_from_errno ();
1963 g_message ("%s: write failed.", __func__);
1980 * @name: a pointer to a NULL-terminated unicode string, that names
1981 * the file to be copied.
1982 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1983 * new name for the file.
1984 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1986 * Copies file @name to @dest_name
1988 * Return value: %TRUE on success, %FALSE otherwise.
1990 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1991 gboolean fail_if_exists)
1993 gchar *utf8_src, *utf8_dest;
1994 int src_fd, dest_fd;
1995 struct stat st, dest_st;
1996 gboolean ret = TRUE;
2000 g_message("%s: name is NULL", __func__);
2003 SetLastError (ERROR_INVALID_NAME);
2007 utf8_src = mono_unicode_to_external (name);
2008 if (utf8_src == NULL) {
2010 g_message ("%s: unicode conversion of source returned NULL",
2014 SetLastError (ERROR_INVALID_PARAMETER);
2018 if(dest_name==NULL) {
2020 g_message("%s: dest is NULL", __func__);
2024 SetLastError (ERROR_INVALID_NAME);
2028 utf8_dest = mono_unicode_to_external (dest_name);
2029 if (utf8_dest == NULL) {
2031 g_message ("%s: unicode conversion of dest returned NULL",
2035 SetLastError (ERROR_INVALID_PARAMETER);
2042 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2044 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2052 if (fstat (src_fd, &st) < 0) {
2053 _wapi_set_last_error_from_errno ();
2062 /* Before trying to open/create the dest, we need to report a 'file busy'
2063 * error if src and dest are actually the same file. We do the check here to take
2064 * advantage of the IOMAP capability */
2065 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
2066 st.st_ino == dest_st.st_ino) {
2072 SetLastError (ERROR_SHARING_VIOLATION);
2076 if (fail_if_exists) {
2077 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2079 /* FIXME: it kinda sucks that this code path potentially scans
2080 * the directory twice due to the weird SetLastError()
2082 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2084 /* The file does not exist, try creating it */
2085 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2087 /* Apparently this error is set if we
2088 * overwrite the dest file
2090 SetLastError (ERROR_ALREADY_EXISTS);
2094 _wapi_set_last_error_from_errno ();
2103 if (!write_file (src_fd, dest_fd, &st, TRUE))
2115 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2121 g_message ("%s: %s is NULL", __func__, arg_name);
2123 SetLastError (ERROR_INVALID_NAME);
2127 utf8_ret = mono_unicode_to_external (arg);
2128 if (utf8_ret == NULL) {
2130 g_message ("%s: unicode conversion of %s returned NULL",
2131 __func__, arg_name);
2133 SetLastError (ERROR_INVALID_PARAMETER);
2141 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2142 const gunichar2 *backupFileName, guint32 replaceFlags,
2143 gpointer exclude, gpointer reserved)
2145 int result, errno_copy, backup_fd = -1,replaced_fd = -1;
2146 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2147 struct stat stBackup;
2148 gboolean ret = FALSE;
2150 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2152 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2153 goto replace_cleanup;
2154 if (backupFileName != NULL) {
2155 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2156 goto replace_cleanup;
2159 if (utf8_backupFileName) {
2160 // Open the backup file for read so we can restore the file if an error occurs.
2161 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2162 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2165 goto replace_cleanup;
2168 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2171 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2172 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2173 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2174 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2177 if (replaced_fd == -1)
2178 goto replace_cleanup;
2180 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2183 goto replace_cleanup;
2189 g_free (utf8_replacedFileName);
2190 g_free (utf8_replacementFileName);
2191 g_free (utf8_backupFileName);
2192 if (backup_fd != -1)
2194 if (replaced_fd != -1)
2195 close (replaced_fd);
2201 * @stdhandle: specifies the file descriptor
2203 * Returns a handle for stdin, stdout, or stderr. Always returns the
2204 * same handle for the same @stdhandle.
2206 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2209 static mono_mutex_t stdhandle_mutex = MONO_MUTEX_INITIALIZER;
2211 gpointer GetStdHandle(WapiStdHandle stdhandle)
2213 struct _WapiHandle_file *file_handle;
2220 case STD_INPUT_HANDLE:
2225 case STD_OUTPUT_HANDLE:
2230 case STD_ERROR_HANDLE:
2237 g_message("%s: unknown standard handle type", __func__);
2240 SetLastError (ERROR_INVALID_PARAMETER);
2241 return(INVALID_HANDLE_VALUE);
2244 handle = GINT_TO_POINTER (fd);
2246 pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2247 (void *)&stdhandle_mutex);
2248 thr_ret = mono_mutex_lock (&stdhandle_mutex);
2249 g_assert (thr_ret == 0);
2251 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2252 (gpointer *)&file_handle);
2254 /* Need to create this console handle */
2255 handle = _wapi_stdhandle_create (fd, name);
2257 if (handle == INVALID_HANDLE_VALUE) {
2258 SetLastError (ERROR_NO_MORE_FILES);
2262 /* Add a reference to this handle */
2263 _wapi_handle_ref (handle);
2267 thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2268 g_assert (thr_ret == 0);
2269 pthread_cleanup_pop (0);
2276 * @handle: The file handle to read from. The handle must have
2277 * %GENERIC_READ access.
2278 * @buffer: The buffer to store read data in
2279 * @numbytes: The maximum number of bytes to read
2280 * @bytesread: The actual number of bytes read is stored here. This
2281 * value can be zero if the handle is positioned at the end of the
2283 * @overlapped: points to a required %WapiOverlapped structure if
2284 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2287 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2288 * function reads up to @numbytes bytes from the file from the current
2289 * file position, and stores them in @buffer. If there are not enough
2290 * bytes left in the file, just the amount available will be read.
2291 * The actual number of bytes read is stored in @bytesread.
2293 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2294 * file position is ignored and the read position is taken from data
2295 * in the @overlapped structure.
2297 * Return value: %TRUE if the read succeeds (even if no bytes were
2298 * read due to an attempt to read past the end of the file), %FALSE on
2301 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2302 guint32 *bytesread, WapiOverlapped *overlapped)
2304 WapiHandleType type;
2306 type = _wapi_handle_type (handle);
2308 if(io_ops[type].readfile==NULL) {
2309 SetLastError (ERROR_INVALID_HANDLE);
2313 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2319 * @handle: The file handle to write to. The handle must have
2320 * %GENERIC_WRITE access.
2321 * @buffer: The buffer to read data from.
2322 * @numbytes: The maximum number of bytes to write.
2323 * @byteswritten: The actual number of bytes written is stored here.
2324 * If the handle is positioned at the file end, the length of the file
2325 * is extended. This parameter may be %NULL.
2326 * @overlapped: points to a required %WapiOverlapped structure if
2327 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2330 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2331 * function writes up to @numbytes bytes from @buffer to the file at
2332 * the current file position. If @handle is positioned at the end of
2333 * the file, the file is extended. The actual number of bytes written
2334 * is stored in @byteswritten.
2336 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2337 * file position is ignored and the write position is taken from data
2338 * in the @overlapped structure.
2340 * Return value: %TRUE if the write succeeds, %FALSE on error.
2342 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2343 guint32 *byteswritten, WapiOverlapped *overlapped)
2345 WapiHandleType type;
2347 type = _wapi_handle_type (handle);
2349 if(io_ops[type].writefile==NULL) {
2350 SetLastError (ERROR_INVALID_HANDLE);
2354 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2360 * @handle: Handle to open file. The handle must have
2361 * %GENERIC_WRITE access.
2363 * Flushes buffers of the file and causes all unwritten data to
2366 * Return value: %TRUE on success, %FALSE otherwise.
2368 gboolean FlushFileBuffers(gpointer handle)
2370 WapiHandleType type;
2372 type = _wapi_handle_type (handle);
2374 if(io_ops[type].flushfile==NULL) {
2375 SetLastError (ERROR_INVALID_HANDLE);
2379 return(io_ops[type].flushfile (handle));
2384 * @handle: The file handle to set. The handle must have
2385 * %GENERIC_WRITE access.
2387 * Moves the end-of-file position to the current position of the file
2388 * pointer. This function is used to truncate or extend a file.
2390 * Return value: %TRUE on success, %FALSE otherwise.
2392 gboolean SetEndOfFile(gpointer handle)
2394 WapiHandleType type;
2396 type = _wapi_handle_type (handle);
2398 if (io_ops[type].setendoffile == NULL) {
2399 SetLastError (ERROR_INVALID_HANDLE);
2403 return(io_ops[type].setendoffile (handle));
2408 * @handle: The file handle to set. The handle must have
2409 * %GENERIC_READ or %GENERIC_WRITE access.
2410 * @movedistance: Low 32 bits of a signed value that specifies the
2411 * number of bytes to move the file pointer.
2412 * @highmovedistance: Pointer to the high 32 bits of a signed value
2413 * that specifies the number of bytes to move the file pointer, or
2415 * @method: The starting point for the file pointer move.
2417 * Sets the file pointer of an open file.
2419 * The distance to move the file pointer is calculated from
2420 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2421 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2422 * is the low 32 bits and @highmovedistance a pointer to the high 32
2423 * bits of a 64 bit signed value. A positive distance moves the file
2424 * pointer forward from the position specified by @method; a negative
2425 * distance moves the file pointer backward.
2427 * If the library is compiled without large file support,
2428 * @highmovedistance is ignored and its value is set to zero on a
2429 * successful return.
2431 * Return value: On success, the low 32 bits of the new file pointer.
2432 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2433 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2435 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2436 gint32 *highmovedistance, WapiSeekMethod method)
2438 WapiHandleType type;
2440 type = _wapi_handle_type (handle);
2442 if (io_ops[type].seek == NULL) {
2443 SetLastError (ERROR_INVALID_HANDLE);
2444 return(INVALID_SET_FILE_POINTER);
2447 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2453 * @handle: The file handle to test.
2455 * Finds the type of file @handle.
2457 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2458 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2459 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2460 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2462 WapiFileType GetFileType(gpointer handle)
2464 WapiHandleType type;
2466 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2467 SetLastError (ERROR_INVALID_HANDLE);
2468 return(FILE_TYPE_UNKNOWN);
2471 type = _wapi_handle_type (handle);
2473 if (io_ops[type].getfiletype == NULL) {
2474 SetLastError (ERROR_INVALID_HANDLE);
2475 return(FILE_TYPE_UNKNOWN);
2478 return(io_ops[type].getfiletype ());
2483 * @handle: The file handle to query. The handle must have
2484 * %GENERIC_READ or %GENERIC_WRITE access.
2485 * @highsize: If non-%NULL, the high 32 bits of the file size are
2488 * Retrieves the size of the file @handle.
2490 * If the library is compiled without large file support, @highsize
2491 * has its value set to zero on a successful return.
2493 * Return value: On success, the low 32 bits of the file size. If
2494 * @highsize is non-%NULL then the high 32 bits of the file size are
2495 * stored here. On failure %INVALID_FILE_SIZE is returned.
2497 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2499 WapiHandleType type;
2501 type = _wapi_handle_type (handle);
2503 if (io_ops[type].getfilesize == NULL) {
2504 SetLastError (ERROR_INVALID_HANDLE);
2505 return(INVALID_FILE_SIZE);
2508 return(io_ops[type].getfilesize (handle, highsize));
2513 * @handle: The file handle to query. The handle must have
2514 * %GENERIC_READ access.
2515 * @create_time: Points to a %WapiFileTime structure to receive the
2516 * number of ticks since the epoch that file was created. May be
2518 * @last_access: Points to a %WapiFileTime structure to receive the
2519 * number of ticks since the epoch when file was last accessed. May be
2521 * @last_write: Points to a %WapiFileTime structure to receive the
2522 * number of ticks since the epoch when file was last written to. May
2525 * Finds the number of ticks since the epoch that the file referenced
2526 * by @handle was created, last accessed and last modified. A tick is
2527 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2530 * Create time isn't recorded on POSIX file systems or reported by
2531 * stat(2), so that time is guessed by returning the oldest of the
2534 * Return value: %TRUE on success, %FALSE otherwise.
2536 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2537 WapiFileTime *last_access, WapiFileTime *last_write)
2539 WapiHandleType type;
2541 type = _wapi_handle_type (handle);
2543 if (io_ops[type].getfiletime == NULL) {
2544 SetLastError (ERROR_INVALID_HANDLE);
2548 return(io_ops[type].getfiletime (handle, create_time, last_access,
2554 * @handle: The file handle to set. The handle must have
2555 * %GENERIC_WRITE access.
2556 * @create_time: Points to a %WapiFileTime structure that contains the
2557 * number of ticks since the epoch that the file was created. May be
2559 * @last_access: Points to a %WapiFileTime structure that contains the
2560 * number of ticks since the epoch when the file was last accessed.
2562 * @last_write: Points to a %WapiFileTime structure that contains the
2563 * number of ticks since the epoch when the file was last written to.
2566 * Sets the number of ticks since the epoch that the file referenced
2567 * by @handle was created, last accessed or last modified. A tick is
2568 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2571 * Create time isn't recorded on POSIX file systems, and is ignored.
2573 * Return value: %TRUE on success, %FALSE otherwise.
2575 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2576 const WapiFileTime *last_access,
2577 const WapiFileTime *last_write)
2579 WapiHandleType type;
2581 type = _wapi_handle_type (handle);
2583 if (io_ops[type].setfiletime == NULL) {
2584 SetLastError (ERROR_INVALID_HANDLE);
2588 return(io_ops[type].setfiletime (handle, create_time, last_access,
2592 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2593 * January 1 1601 GMT
2596 #define TICKS_PER_MILLISECOND 10000L
2597 #define TICKS_PER_SECOND 10000000L
2598 #define TICKS_PER_MINUTE 600000000L
2599 #define TICKS_PER_HOUR 36000000000LL
2600 #define TICKS_PER_DAY 864000000000LL
2602 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2604 static const guint16 mon_yday[2][13]={
2605 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2606 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2610 * FileTimeToSystemTime:
2611 * @file_time: Points to a %WapiFileTime structure that contains the
2612 * number of ticks to convert.
2613 * @system_time: Points to a %WapiSystemTime structure to receive the
2616 * Converts a tick count into broken-out time values.
2618 * Return value: %TRUE on success, %FALSE otherwise.
2620 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2621 WapiSystemTime *system_time)
2623 gint64 file_ticks, totaldays, rem, y;
2626 if(system_time==NULL) {
2628 g_message("%s: system_time NULL", __func__);
2631 SetLastError (ERROR_INVALID_PARAMETER);
2635 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2636 file_time->dwLowDateTime;
2638 /* Really compares if file_ticks>=0x8000000000000000
2639 * (LLONG_MAX+1) but we're working with a signed value for the
2640 * year and day calculation to work later
2644 g_message("%s: file_time too big", __func__);
2647 SetLastError (ERROR_INVALID_PARAMETER);
2651 totaldays=(file_ticks / TICKS_PER_DAY);
2652 rem = file_ticks % TICKS_PER_DAY;
2654 g_message("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2657 system_time->wHour=rem/TICKS_PER_HOUR;
2658 rem %= TICKS_PER_HOUR;
2660 g_message("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2663 system_time->wMinute = rem / TICKS_PER_MINUTE;
2664 rem %= TICKS_PER_MINUTE;
2666 g_message("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2670 system_time->wSecond = rem / TICKS_PER_SECOND;
2671 rem %= TICKS_PER_SECOND;
2673 g_message("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2677 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2679 g_message("%s: Milliseconds: %d", __func__,
2680 system_time->wMilliseconds);
2683 /* January 1, 1601 was a Monday, according to Emacs calendar */
2684 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2686 g_message("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2689 /* This algorithm to find year and month given days from epoch
2694 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2695 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2697 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2698 /* Guess a corrected year, assuming 365 days per year */
2699 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2701 g_message("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2704 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2705 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2708 /* Adjust days and y to match the guessed year. */
2709 totaldays -= ((yg - y) * 365
2710 + LEAPS_THRU_END_OF (yg - 1)
2711 - LEAPS_THRU_END_OF (y - 1));
2713 g_message("%s: totaldays: %lld", __func__, totaldays);
2717 g_message("%s: y: %lld", __func__, y);
2721 system_time->wYear = y;
2723 g_message("%s: Year: %d", __func__, system_time->wYear);
2726 ip = mon_yday[isleap(y)];
2728 for(y=11; totaldays < ip[y]; --y) {
2733 g_message("%s: totaldays: %lld", __func__, totaldays);
2736 system_time->wMonth = y + 1;
2738 g_message("%s: Month: %d", __func__, system_time->wMonth);
2741 system_time->wDay = totaldays + 1;
2743 g_message("%s: Day: %d", __func__, system_time->wDay);
2749 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2751 struct _WapiHandle_find find_handle = {0};
2753 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2756 if (pattern == NULL) {
2758 g_message ("%s: pattern is NULL", __func__);
2761 SetLastError (ERROR_PATH_NOT_FOUND);
2762 return(INVALID_HANDLE_VALUE);
2765 utf8_pattern = mono_unicode_to_external (pattern);
2766 if (utf8_pattern == NULL) {
2768 g_message ("%s: unicode conversion returned NULL", __func__);
2771 SetLastError (ERROR_INVALID_NAME);
2772 return(INVALID_HANDLE_VALUE);
2776 g_message ("%s: looking for [%s]", __func__, utf8_pattern);
2779 /* Figure out which bit of the pattern is the directory */
2780 dir_part = _wapi_dirname (utf8_pattern);
2781 entry_part = _wapi_basename (utf8_pattern);
2784 /* Don't do this check for now, it breaks if directories
2785 * really do have metachars in their names (see bug 58116).
2786 * FIXME: Figure out a better solution to keep some checks...
2788 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2789 SetLastError (ERROR_INVALID_NAME);
2791 g_free (entry_part);
2792 g_free (utf8_pattern);
2793 return(INVALID_HANDLE_VALUE);
2797 /* The pattern can specify a directory or a set of files.
2799 * The pattern can have wildcard characters ? and *, but only
2800 * in the section after the last directory delimiter. (Return
2801 * ERROR_INVALID_NAME if there are wildcards in earlier path
2802 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2803 * means "match one character", "??" seems to mean "match one
2804 * or two characters", "???" seems to mean "match one, two or
2805 * three characters", etc. Windows will also try and match
2806 * the mangled "short name" of files, so 8 character patterns
2807 * with wildcards will show some surprising results.
2809 * All the written documentation I can find says that '?'
2810 * should only match one character, and doesn't mention '??',
2811 * '???' etc. I'm going to assume that the strict behaviour
2812 * (ie '???' means three and only three characters) is the
2813 * correct one, because that lets me use fnmatch(3) rather
2814 * than mess around with regexes.
2817 find_handle.namelist = NULL;
2818 result = _wapi_io_scandir (dir_part, entry_part,
2819 &find_handle.namelist);
2822 /* No files, which windows seems to call
2825 SetLastError (ERROR_FILE_NOT_FOUND);
2826 g_free (utf8_pattern);
2827 g_free (entry_part);
2829 return (INVALID_HANDLE_VALUE);
2834 gint errnum = errno;
2836 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2838 g_message ("%s: scandir error: %s", __func__,
2839 g_strerror (errnum));
2841 g_free (utf8_pattern);
2842 g_free (entry_part);
2844 return (INVALID_HANDLE_VALUE);
2847 g_free (utf8_pattern);
2848 g_free (entry_part);
2851 g_message ("%s: Got %d matches", __func__, result);
2854 find_handle.dir_part = dir_part;
2855 find_handle.num = result;
2856 find_handle.count = 0;
2858 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2859 if (handle == _WAPI_HANDLE_INVALID) {
2860 g_warning ("%s: error creating find handle", __func__);
2862 g_free (entry_part);
2863 g_free (utf8_pattern);
2864 SetLastError (ERROR_GEN_FAILURE);
2866 return(INVALID_HANDLE_VALUE);
2869 if (handle != INVALID_HANDLE_VALUE &&
2870 !FindNextFile (handle, find_data)) {
2872 SetLastError (ERROR_NO_MORE_FILES);
2873 handle = INVALID_HANDLE_VALUE;
2879 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2881 struct _WapiHandle_find *find_handle;
2883 struct stat buf, linkbuf;
2886 gchar *utf8_filename, *utf8_basename;
2887 gunichar2 *utf16_basename;
2891 gboolean ret = FALSE;
2893 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2894 (gpointer *)&find_handle);
2896 g_warning ("%s: error looking up find handle %p", __func__,
2898 SetLastError (ERROR_INVALID_HANDLE);
2902 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2904 thr_ret = _wapi_handle_lock_handle (handle);
2905 g_assert (thr_ret == 0);
2908 if (find_handle->count >= find_handle->num) {
2909 SetLastError (ERROR_NO_MORE_FILES);
2913 /* stat next match */
2915 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2917 result = _wapi_stat (filename, &buf);
2918 if (result == -1 && errno == ENOENT) {
2919 /* Might be a dangling symlink */
2920 result = _wapi_lstat (filename, &buf);
2925 g_message ("%s: stat failed: %s", __func__, filename);
2932 result = _wapi_lstat (filename, &linkbuf);
2935 g_message ("%s: lstat failed: %s", __func__, filename);
2942 utf8_filename = mono_utf8_from_external (filename);
2943 if (utf8_filename == NULL) {
2944 /* We couldn't turn this filename into utf8 (eg the
2945 * encoding of the name wasn't convertible), so just
2948 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2956 g_message ("%s: Found [%s]", __func__, utf8_filename);
2959 /* fill data block */
2961 if (buf.st_mtime < buf.st_ctime)
2962 create_time = buf.st_mtime;
2964 create_time = buf.st_ctime;
2966 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2968 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2969 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2970 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2972 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2973 find_data->nFileSizeHigh = 0;
2974 find_data->nFileSizeLow = 0;
2976 find_data->nFileSizeHigh = buf.st_size >> 32;
2977 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2980 find_data->dwReserved0 = 0;
2981 find_data->dwReserved1 = 0;
2983 utf8_basename = _wapi_basename (utf8_filename);
2984 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2986 if(utf16_basename==NULL) {
2987 g_free (utf8_basename);
2988 g_free (utf8_filename);
2993 /* utf16 is 2 * utf8 */
2996 memset (find_data->cFileName, '\0', (MAX_PATH*2));
2998 /* Truncating a utf16 string like this might leave the last
3001 memcpy (find_data->cFileName, utf16_basename,
3002 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3004 find_data->cAlternateFileName [0] = 0; /* not used */
3006 g_free (utf8_basename);
3007 g_free (utf8_filename);
3008 g_free (utf16_basename);
3011 thr_ret = _wapi_handle_unlock_handle (handle);
3012 g_assert (thr_ret == 0);
3013 pthread_cleanup_pop (0);
3020 * @wapi_handle: the find handle to close.
3022 * Closes find handle @wapi_handle
3024 * Return value: %TRUE on success, %FALSE otherwise.
3026 gboolean FindClose (gpointer handle)
3028 struct _WapiHandle_find *find_handle;
3032 if (handle == NULL) {
3033 SetLastError (ERROR_INVALID_HANDLE);
3037 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
3038 (gpointer *)&find_handle);
3040 g_warning ("%s: error looking up find handle %p", __func__,
3042 SetLastError (ERROR_INVALID_HANDLE);
3046 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
3048 thr_ret = _wapi_handle_lock_handle (handle);
3049 g_assert (thr_ret == 0);
3051 g_strfreev (find_handle->namelist);
3052 g_free (find_handle->dir_part);
3054 thr_ret = _wapi_handle_unlock_handle (handle);
3055 g_assert (thr_ret == 0);
3056 pthread_cleanup_pop (0);
3058 _wapi_handle_unref (handle);
3065 * @name: a pointer to a NULL-terminated unicode string, that names
3066 * the directory to be created.
3067 * @security: ignored for now
3069 * Creates directory @name
3071 * Return value: %TRUE on success, %FALSE otherwise.
3073 gboolean CreateDirectory (const gunichar2 *name,
3074 WapiSecurityAttributes *security)
3081 g_message("%s: name is NULL", __func__);
3084 SetLastError (ERROR_INVALID_NAME);
3088 utf8_name = mono_unicode_to_external (name);
3089 if (utf8_name == NULL) {
3091 g_message ("%s: unicode conversion returned NULL", __func__);
3094 SetLastError (ERROR_INVALID_NAME);
3098 result = _wapi_mkdir (utf8_name, 0777);
3105 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3112 * @name: a pointer to a NULL-terminated unicode string, that names
3113 * the directory to be removed.
3115 * Removes directory @name
3117 * Return value: %TRUE on success, %FALSE otherwise.
3119 gboolean RemoveDirectory (const gunichar2 *name)
3126 g_message("%s: name is NULL", __func__);
3129 SetLastError (ERROR_INVALID_NAME);
3133 utf8_name = mono_unicode_to_external (name);
3134 if (utf8_name == NULL) {
3136 g_message ("%s: unicode conversion returned NULL", __func__);
3139 SetLastError (ERROR_INVALID_NAME);
3143 result = _wapi_rmdir (utf8_name);
3145 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3156 * GetFileAttributes:
3157 * @name: a pointer to a NULL-terminated unicode filename.
3159 * Gets the attributes for @name;
3161 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3163 guint32 GetFileAttributes (const gunichar2 *name)
3166 struct stat buf, linkbuf;
3172 g_message("%s: name is NULL", __func__);
3175 SetLastError (ERROR_INVALID_NAME);
3179 utf8_name = mono_unicode_to_external (name);
3180 if (utf8_name == NULL) {
3182 g_message ("%s: unicode conversion returned NULL", __func__);
3185 SetLastError (ERROR_INVALID_PARAMETER);
3186 return (INVALID_FILE_ATTRIBUTES);
3189 result = _wapi_stat (utf8_name, &buf);
3190 if (result == -1 && errno == ENOENT) {
3191 /* Might be a dangling symlink... */
3192 result = _wapi_lstat (utf8_name, &buf);
3196 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3198 return (INVALID_FILE_ATTRIBUTES);
3201 result = _wapi_lstat (utf8_name, &linkbuf);
3203 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3205 return (INVALID_FILE_ATTRIBUTES);
3208 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3216 * GetFileAttributesEx:
3217 * @name: a pointer to a NULL-terminated unicode filename.
3218 * @level: must be GetFileExInfoStandard
3219 * @info: pointer to a WapiFileAttributesData structure
3221 * Gets attributes, size and filetimes for @name;
3223 * Return value: %TRUE on success, %FALSE on failure
3225 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3228 WapiFileAttributesData *data;
3230 struct stat buf, linkbuf;
3234 if (level != GetFileExInfoStandard) {
3236 g_message ("%s: info level %d not supported.", __func__,
3240 SetLastError (ERROR_INVALID_PARAMETER);
3246 g_message("%s: name is NULL", __func__);
3249 SetLastError (ERROR_INVALID_NAME);
3253 utf8_name = mono_unicode_to_external (name);
3254 if (utf8_name == NULL) {
3256 g_message ("%s: unicode conversion returned NULL", __func__);
3259 SetLastError (ERROR_INVALID_PARAMETER);
3263 result = _wapi_stat (utf8_name, &buf);
3264 if (result == -1 && errno == ENOENT) {
3265 /* Might be a dangling symlink... */
3266 result = _wapi_lstat (utf8_name, &buf);
3270 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3275 result = _wapi_lstat (utf8_name, &linkbuf);
3277 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3282 /* fill data block */
3284 data = (WapiFileAttributesData *)info;
3286 if (buf.st_mtime < buf.st_ctime)
3287 create_time = buf.st_mtime;
3289 create_time = buf.st_ctime;
3291 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3297 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3298 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3299 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3301 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3302 data->nFileSizeHigh = 0;
3303 data->nFileSizeLow = 0;
3306 data->nFileSizeHigh = buf.st_size >> 32;
3307 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3315 * @name: name of file
3316 * @attrs: attributes to set
3318 * Changes the attributes on a named file.
3320 * Return value: %TRUE on success, %FALSE on failure.
3322 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3324 /* FIXME: think of something clever to do on unix */
3330 * Currently we only handle one *internal* case, with a value that is
3331 * not standard: 0x80000000, which means `set executable bit'
3336 g_message("%s: name is NULL", __func__);
3339 SetLastError (ERROR_INVALID_NAME);
3343 utf8_name = mono_unicode_to_external (name);
3344 if (utf8_name == NULL) {
3346 g_message ("%s: unicode conversion returned NULL", __func__);
3349 SetLastError (ERROR_INVALID_NAME);
3353 result = _wapi_stat (utf8_name, &buf);
3355 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3360 /* Contrary to the documentation, ms allows NORMAL to be
3361 * specified along with other attributes, so dont bother to
3362 * catch that case here.
3364 if (attrs & FILE_ATTRIBUTE_READONLY) {
3365 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3367 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3370 /* Ignore the other attributes for now */
3372 if (attrs & 0x80000000){
3373 mode_t exec_mask = 0;
3375 if ((buf.st_mode & S_IRUSR) != 0)
3376 exec_mask |= S_IXUSR;
3378 if ((buf.st_mode & S_IRGRP) != 0)
3379 exec_mask |= S_IXGRP;
3381 if ((buf.st_mode & S_IROTH) != 0)
3382 exec_mask |= S_IXOTH;
3384 result = chmod (utf8_name, buf.st_mode | exec_mask);
3386 /* Don't bother to reset executable (might need to change this
3396 * GetCurrentDirectory
3397 * @length: size of the buffer
3398 * @buffer: pointer to buffer that recieves path
3400 * Retrieves the current directory for the current process.
3402 * Return value: number of characters in buffer on success, zero on failure
3404 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3406 gunichar2 *utf16_path;
3410 if (getcwd ((char*)buffer, length) == NULL) {
3411 if (errno == ERANGE) { /*buffer length is not big enough */
3412 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*/
3415 utf16_path = mono_unicode_from_external (path, &bytes);
3416 g_free (utf16_path);
3420 _wapi_set_last_error_from_errno ();
3424 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3425 count = (bytes/2)+1;
3426 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3428 /* Add the terminator */
3429 memset (buffer, '\0', bytes+2);
3430 memcpy (buffer, utf16_path, bytes);
3432 g_free (utf16_path);
3438 * SetCurrentDirectory
3439 * @path: path to new directory
3441 * Changes the directory path for the current process.
3443 * Return value: %TRUE on success, %FALSE on failure.
3445 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3451 SetLastError (ERROR_INVALID_PARAMETER);
3455 utf8_path = mono_unicode_to_external (path);
3456 if (_wapi_chdir (utf8_path) != 0) {
3457 _wapi_set_last_error_from_errno ();
3467 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3468 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3470 struct _WapiHandle_file pipe_read_handle = {0};
3471 struct _WapiHandle_file pipe_write_handle = {0};
3472 gpointer read_handle;
3473 gpointer write_handle;
3477 mono_once (&io_ops_once, io_ops_init);
3480 g_message ("%s: Creating pipe", __func__);
3486 g_message ("%s: Error creating pipe: %s", __func__,
3490 _wapi_set_last_error_from_errno ();
3494 if (filedes[0] >= _wapi_fd_reserve ||
3495 filedes[1] >= _wapi_fd_reserve) {
3497 g_message ("%s: File descriptor is too big", __func__);
3500 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3508 /* filedes[0] is open for reading, filedes[1] for writing */
3510 pipe_read_handle.fileaccess = GENERIC_READ;
3511 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3513 if (read_handle == _WAPI_HANDLE_INVALID) {
3514 g_warning ("%s: error creating pipe read handle", __func__);
3517 SetLastError (ERROR_GEN_FAILURE);
3522 pipe_write_handle.fileaccess = GENERIC_WRITE;
3523 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3524 &pipe_write_handle);
3525 if (write_handle == _WAPI_HANDLE_INVALID) {
3526 g_warning ("%s: error creating pipe write handle", __func__);
3527 _wapi_handle_unref (read_handle);
3531 SetLastError (ERROR_GEN_FAILURE);
3536 *readpipe = read_handle;
3537 *writepipe = write_handle;
3540 g_message ("%s: Returning pipe: read handle %p, write handle %p",
3541 __func__, read_handle, write_handle);
3547 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3549 gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3550 gunichar2 *tmpdir16=NULL;
3555 if(tmpdir[strlen (tmpdir)]!='/') {
3557 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3560 tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3561 if(tmpdir16==NULL) {
3569 g_message ("%s: Size %d smaller than needed (%ld)",
3570 __func__, len, dirlen+1);
3575 /* Add the terminator */
3576 memset (buf, '\0', bytes+2);
3577 memcpy (buf, tmpdir16, bytes);
3583 if(tmpdir16!=NULL) {
3591 #ifdef HAVE_GETFSSTAT
3592 /* Darwin has getfsstat */
3593 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3595 struct statfs *stats;
3598 glong length, total = 0;
3600 n = getfsstat (NULL, 0, MNT_NOWAIT);
3603 size = n * sizeof (struct statfs);
3604 stats = (struct statfs *) g_malloc (size);
3607 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3611 for (i = 0; i < n; i++){
3612 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3613 if (total + length < len){
3614 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3615 buf [total+length] = 0;
3618 total += length + 1;
3627 /* In-place octal sequence replacement */
3629 unescape_octal (gchar *str)
3638 while (*rptr != '\0') {
3639 if (*rptr == '\\') {
3642 c = (*(rptr++) - '0') << 6;
3643 c += (*(rptr++) - '0') << 3;
3644 c += *(rptr++) - '0';
3646 } else if (wptr != rptr) {
3656 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3659 gunichar2 *ptr, *dir;
3660 glong length, total = 0;
3664 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3669 /* Sigh, mntent and friends don't work well.
3670 * It stops on the first line that doesn't begin with a '/'.
3671 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3672 fp = fopen ("/etc/mtab", "rt");
3674 fp = fopen ("/etc/mnttab", "rt");
3680 while (fgets (buffer, 512, fp) != NULL) {
3684 splitted = g_strsplit (buffer, " ", 0);
3685 if (!*splitted || !*(splitted + 1)) {
3686 g_strfreev (splitted);
3690 unescape_octal (*(splitted + 1));
3691 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3692 g_strfreev (splitted);
3693 if (total + length + 1 > len) {
3696 return len * 2; /* guess */
3699 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3701 total += length + 1;
3706 /* Commented out, does not work with my mtab!!! - Gonz */
3707 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3711 gunichar2 *ptr, *dir;
3712 glong len, total = 0;
3715 fp = setmntent ("/etc/mtab", "rt");
3717 fp = setmntent ("/etc/mnttab", "rt");
3723 while ((mnt = getmntent (fp)) != NULL) {
3724 g_print ("GOT %s\n", mnt->mnt_dir);
3725 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3726 if (total + len + 1 > len) {
3727 return len * 2; /* guess */
3730 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3742 #if (defined(HAVE_STATVFS) || defined(HAVE_STATFS)) && !defined(PLATFORM_ANDROID)
3743 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3744 WapiULargeInteger *total_number_of_bytes,
3745 WapiULargeInteger *total_number_of_free_bytes)
3748 struct statvfs fsstat;
3749 #elif defined(HAVE_STATFS)
3750 struct statfs fsstat;
3752 gboolean isreadonly;
3753 gchar *utf8_path_name;
3755 unsigned long block_size;
3757 if (path_name == NULL) {
3758 utf8_path_name = g_strdup (g_get_current_dir());
3759 if (utf8_path_name == NULL) {
3760 SetLastError (ERROR_DIRECTORY);
3765 utf8_path_name = mono_unicode_to_external (path_name);
3766 if (utf8_path_name == NULL) {
3768 g_message("%s: unicode conversion returned NULL", __func__);
3771 SetLastError (ERROR_INVALID_NAME);
3778 ret = statvfs (utf8_path_name, &fsstat);
3779 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
3780 block_size = fsstat.f_frsize;
3781 #elif defined(HAVE_STATFS)
3782 ret = statfs (utf8_path_name, &fsstat);
3783 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
3784 block_size = fsstat.f_bsize;
3786 } while(ret == -1 && errno == EINTR);
3788 g_free(utf8_path_name);
3791 _wapi_set_last_error_from_errno ();
3793 g_message ("%s: statvfs failed: %s", __func__, strerror (errno));
3798 /* total number of free bytes for non-root */
3799 if (free_bytes_avail != NULL) {
3801 free_bytes_avail->QuadPart = 0;
3804 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
3808 /* total number of bytes available for non-root */
3809 if (total_number_of_bytes != NULL) {
3810 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
3813 /* total number of bytes available for root */
3814 if (total_number_of_free_bytes != NULL) {
3816 total_number_of_free_bytes->QuadPart = 0;
3819 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
3826 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3827 WapiULargeInteger *total_number_of_bytes,
3828 WapiULargeInteger *total_number_of_free_bytes)
3830 if (free_bytes_avail != NULL) {
3831 free_bytes_avail->QuadPart = (guint64) -1;
3834 if (total_number_of_bytes != NULL) {
3835 total_number_of_bytes->QuadPart = (guint64) -1;
3838 if (total_number_of_free_bytes != NULL) {
3839 total_number_of_free_bytes->QuadPart = (guint64) -1;
3847 * General Unix support
3851 const gchar* fstype;
3854 static _wapi_drive_type _wapi_drive_types[] = {
3856 { DRIVE_REMOTE, "afp" },
3857 { DRIVE_REMOTE, "autofs" },
3858 { DRIVE_CDROM, "cddafs" },
3859 { DRIVE_CDROM, "cd9660" },
3860 { DRIVE_RAMDISK, "devfs" },
3861 { DRIVE_FIXED, "exfat" },
3862 { DRIVE_RAMDISK, "fdesc" },
3863 { DRIVE_REMOTE, "ftp" },
3864 { DRIVE_FIXED, "hfs" },
3865 { DRIVE_FIXED, "msdos" },
3866 { DRIVE_REMOTE, "nfs" },
3867 { DRIVE_FIXED, "ntfs" },
3868 { DRIVE_REMOTE, "smbfs" },
3869 { DRIVE_FIXED, "udf" },
3870 { DRIVE_REMOTE, "webdav" },
3872 { DRIVE_RAMDISK, "ramfs" },
3873 { DRIVE_RAMDISK, "tmpfs" },
3874 { DRIVE_RAMDISK, "proc" },
3875 { DRIVE_RAMDISK, "sysfs" },
3876 { DRIVE_RAMDISK, "debugfs" },
3877 { DRIVE_RAMDISK, "devpts" },
3878 { DRIVE_RAMDISK, "securityfs" },
3879 { DRIVE_CDROM, "iso9660" },
3880 { DRIVE_FIXED, "ext2" },
3881 { DRIVE_FIXED, "ext3" },
3882 { DRIVE_FIXED, "ext4" },
3883 { DRIVE_FIXED, "sysv" },
3884 { DRIVE_FIXED, "reiserfs" },
3885 { DRIVE_FIXED, "ufs" },
3886 { DRIVE_FIXED, "vfat" },
3887 { DRIVE_FIXED, "msdos" },
3888 { DRIVE_FIXED, "udf" },
3889 { DRIVE_FIXED, "hfs" },
3890 { DRIVE_FIXED, "hpfs" },
3891 { DRIVE_FIXED, "qnx4" },
3892 { DRIVE_FIXED, "ntfs" },
3893 { DRIVE_FIXED, "ntfs-3g" },
3894 { DRIVE_REMOTE, "smbfs" },
3895 { DRIVE_REMOTE, "fuse" },
3896 { DRIVE_REMOTE, "nfs" },
3897 { DRIVE_REMOTE, "nfs4" },
3898 { DRIVE_REMOTE, "cifs" },
3899 { DRIVE_REMOTE, "ncpfs" },
3900 { DRIVE_REMOTE, "coda" },
3901 { DRIVE_REMOTE, "afs" },
3903 { DRIVE_UNKNOWN, NULL }
3906 static guint32 _wapi_get_drive_type(const gchar* fstype)
3908 _wapi_drive_type *current;
3910 current = &_wapi_drive_types[0];
3911 while (current->drive_type != DRIVE_UNKNOWN) {
3912 if (strcmp (current->fstype, fstype) == 0)
3918 return current->drive_type;
3921 #if HAVE_SYS_MOUNT_H
3923 GetDriveTypeFromPath (const char *path)
3927 if (statfs (path, &buf) == -1)
3928 return DRIVE_UNKNOWN;
3929 return _wapi_get_drive_type (buf.f_fstypename);
3933 GetDriveTypeFromPath (const gchar *path)
3940 fp = fopen ("/etc/mtab", "rt");
3942 fp = fopen ("/etc/mnttab", "rt");
3944 g_free (utf8_root_path_name);
3945 return(DRIVE_UNKNOWN);
3949 drive_type = DRIVE_NO_ROOT_DIR;
3950 while (fgets (buffer, 512, fp) != NULL) {
3951 splitted = g_strsplit (buffer, " ", 0);
3952 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
3953 g_strfreev (splitted);
3957 /* compare given root_path_name with the one from mtab,
3958 if length of utf8_root_path_name is zero it must be the root dir */
3959 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
3960 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
3961 drive_type = _wapi_get_drive_type (*(splitted + 2));
3962 g_strfreev (splitted);
3966 g_strfreev (splitted);
3973 guint32 GetDriveType(const gunichar2 *root_path_name)
3975 gchar *utf8_root_path_name;
3978 if (root_path_name == NULL) {
3979 utf8_root_path_name = g_strdup (g_get_current_dir());
3980 if (utf8_root_path_name == NULL) {
3981 return(DRIVE_NO_ROOT_DIR);
3985 utf8_root_path_name = mono_unicode_to_external (root_path_name);
3986 if (utf8_root_path_name == NULL) {
3988 g_message("%s: unicode conversion returned NULL", __func__);
3990 return(DRIVE_NO_ROOT_DIR);
3993 /* strip trailing slash for compare below */
3994 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
3995 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
3998 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
3999 g_free (utf8_root_path_name);
4001 return (drive_type);
4004 #if defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H)
4006 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4010 gboolean status = 0;
4013 // We only support getting the file system type
4014 if (fsbuffer == NULL)
4017 utfpath = mono_unicode_to_external (path);
4018 if (statfs (utfpath, &stat) != -1){
4019 gunichar2 *ret = g_utf8_to_utf16 (stat.f_fstypename, -1, NULL, &len, NULL);
4020 if (ret != NULL && len < fsbuffersize){
4021 memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4033 * Linux does not this case, as the processing is done in managed code, by parsing /etc/mtab
4036 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)