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.
243 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
250 /* FIXME: this could definitely be better, but there seems to
251 * be no pattern to the attributes that are set
254 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
255 if (S_ISSOCK (buf->st_mode))
256 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
258 filename = _wapi_basename (pathname);
260 if (S_ISDIR (buf->st_mode)) {
261 attrs = FILE_ATTRIBUTE_DIRECTORY;
262 if (!(buf->st_mode & S_IWUSR)) {
263 attrs |= FILE_ATTRIBUTE_READONLY;
265 if (filename[0] == '.') {
266 attrs |= FILE_ATTRIBUTE_HIDDEN;
269 if (!(buf->st_mode & S_IWUSR)) {
270 attrs = FILE_ATTRIBUTE_READONLY;
272 if (filename[0] == '.') {
273 attrs |= FILE_ATTRIBUTE_HIDDEN;
275 } else if (filename[0] == '.') {
276 attrs = FILE_ATTRIBUTE_HIDDEN;
278 attrs = FILE_ATTRIBUTE_NORMAL;
283 if (S_ISLNK (lbuf->st_mode)) {
284 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
294 _wapi_set_last_error_from_errno (void)
296 SetLastError (_wapi_get_win32_file_error (errno));
299 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
302 if (errno == ENOENT) {
303 /* Check the path - if it's a missing directory then
304 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
310 dirname = _wapi_dirname (path);
312 dirname = g_strdup (dir);
315 if (_wapi_access (dirname, F_OK) == 0) {
316 SetLastError (ERROR_FILE_NOT_FOUND);
318 SetLastError (ERROR_PATH_NOT_FOUND);
323 _wapi_set_last_error_from_errno ();
329 static void file_close (gpointer handle, gpointer data)
331 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
332 int fd = file_handle->fd;
334 DEBUG("%s: closing file handle %p [%s]", __func__, handle,
335 file_handle->filename);
337 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
338 _wapi_unlink (file_handle->filename);
340 g_free (file_handle->filename);
342 if (file_handle->share_info)
343 _wapi_handle_share_release (file_handle->share_info);
348 static WapiFileType file_getfiletype(void)
350 return(FILE_TYPE_DISK);
353 static gboolean file_read(gpointer handle, gpointer buffer,
354 guint32 numbytes, guint32 *bytesread,
355 WapiOverlapped *overlapped)
357 struct _WapiHandle_file *file_handle;
361 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
362 (gpointer *)&file_handle);
364 g_warning ("%s: error looking up file handle %p", __func__,
366 SetLastError (ERROR_INVALID_HANDLE);
370 fd = file_handle->fd;
371 if(bytesread!=NULL) {
375 if(!(file_handle->fileaccess & GENERIC_READ) &&
376 !(file_handle->fileaccess & GENERIC_ALL)) {
377 DEBUG("%s: handle %p doesn't have GENERIC_READ access: %u",
378 __func__, handle, file_handle->fileaccess);
380 SetLastError (ERROR_ACCESS_DENIED);
385 ret = read (fd, buffer, numbytes);
386 } while (ret == -1 && errno == EINTR &&
387 !_wapi_thread_cur_apc_pending());
392 DEBUG("%s: read of handle %p error: %s", __func__,
393 handle, strerror(err));
394 SetLastError (_wapi_get_win32_file_error (err));
398 if (bytesread != NULL) {
405 static gboolean file_write(gpointer handle, gconstpointer buffer,
406 guint32 numbytes, guint32 *byteswritten,
407 WapiOverlapped *overlapped G_GNUC_UNUSED)
409 struct _WapiHandle_file *file_handle;
412 off_t current_pos = 0;
414 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
415 (gpointer *)&file_handle);
417 g_warning ("%s: error looking up file handle %p", __func__,
419 SetLastError (ERROR_INVALID_HANDLE);
423 fd = file_handle->fd;
425 if(byteswritten!=NULL) {
429 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
430 !(file_handle->fileaccess & GENERIC_ALL)) {
431 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
433 SetLastError (ERROR_ACCESS_DENIED);
437 if (lock_while_writing) {
438 /* Need to lock the region we're about to write to,
439 * because we only do advisory locking on POSIX
442 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
443 if (current_pos == -1) {
444 DEBUG ("%s: handle %p lseek failed: %s", __func__,
445 handle, strerror (errno));
446 _wapi_set_last_error_from_errno ();
450 if (_wapi_lock_file_region (fd, current_pos,
451 numbytes) == FALSE) {
452 /* The error has already been set */
458 ret = write (fd, buffer, numbytes);
459 } while (ret == -1 && errno == EINTR &&
460 !_wapi_thread_cur_apc_pending());
462 if (lock_while_writing) {
463 _wapi_unlock_file_region (fd, current_pos, numbytes);
467 if (errno == EINTR) {
470 _wapi_set_last_error_from_errno ();
472 DEBUG("%s: write of handle %p error: %s",
473 __func__, handle, strerror(errno));
478 if (byteswritten != NULL) {
484 static gboolean file_flush(gpointer handle)
486 struct _WapiHandle_file *file_handle;
490 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
491 (gpointer *)&file_handle);
493 g_warning ("%s: error looking up file handle %p", __func__,
495 SetLastError (ERROR_INVALID_HANDLE);
499 fd = file_handle->fd;
501 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
502 !(file_handle->fileaccess & GENERIC_ALL)) {
503 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
505 SetLastError (ERROR_ACCESS_DENIED);
511 DEBUG("%s: fsync of handle %p error: %s", __func__, handle,
514 _wapi_set_last_error_from_errno ();
521 static guint32 file_seek(gpointer handle, gint32 movedistance,
522 gint32 *highmovedistance, WapiSeekMethod method)
524 struct _WapiHandle_file *file_handle;
526 off_t offset, newpos;
530 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
531 (gpointer *)&file_handle);
533 g_warning ("%s: error looking up file handle %p", __func__,
535 SetLastError (ERROR_INVALID_HANDLE);
536 return(INVALID_SET_FILE_POINTER);
539 fd = file_handle->fd;
541 if(!(file_handle->fileaccess & GENERIC_READ) &&
542 !(file_handle->fileaccess & GENERIC_WRITE) &&
543 !(file_handle->fileaccess & GENERIC_ALL)) {
544 DEBUG ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
546 SetLastError (ERROR_ACCESS_DENIED);
547 return(INVALID_SET_FILE_POINTER);
561 DEBUG("%s: invalid seek type %d", __func__, method);
563 SetLastError (ERROR_INVALID_PARAMETER);
564 return(INVALID_SET_FILE_POINTER);
567 #ifdef HAVE_LARGE_FILE_SUPPORT
568 if(highmovedistance==NULL) {
570 DEBUG("%s: setting offset to %lld (low %d)", __func__,
571 offset, movedistance);
573 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
575 DEBUG("%s: setting offset to %lld 0x%llx (high %d 0x%x, low %d 0x%x)", __func__, offset, offset, *highmovedistance, *highmovedistance, movedistance, movedistance);
581 #ifdef HAVE_LARGE_FILE_SUPPORT
582 DEBUG ("%s: moving handle %p by %lld bytes from %d", __func__,
583 handle, offset, whence);
585 DEBUG ("%s: moving handle %p fd %d by %ld bytes from %d", __func__,
586 handle, offset, whence);
589 newpos=lseek(fd, offset, whence);
591 DEBUG("%s: lseek on handle %p returned error %s",
592 __func__, handle, strerror(errno));
594 _wapi_set_last_error_from_errno ();
595 return(INVALID_SET_FILE_POINTER);
598 #ifdef HAVE_LARGE_FILE_SUPPORT
599 DEBUG ("%s: lseek returns %lld", __func__, newpos);
601 DEBUG ("%s: lseek returns %ld", __func__, newpos);
604 #ifdef HAVE_LARGE_FILE_SUPPORT
605 ret=newpos & 0xFFFFFFFF;
606 if(highmovedistance!=NULL) {
607 *highmovedistance=newpos>>32;
611 if(highmovedistance!=NULL) {
612 /* Accurate, but potentially dodgy :-) */
617 DEBUG ("%s: move of handle %p returning %d/%d", __func__,
618 handle, ret, highmovedistance==NULL?0:*highmovedistance);
623 static gboolean file_setendoffile(gpointer handle)
625 struct _WapiHandle_file *file_handle;
631 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
632 (gpointer *)&file_handle);
634 g_warning ("%s: error looking up file handle %p", __func__,
636 SetLastError (ERROR_INVALID_HANDLE);
639 fd = file_handle->fd;
641 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
642 !(file_handle->fileaccess & GENERIC_ALL)) {
643 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
645 SetLastError (ERROR_ACCESS_DENIED);
649 /* Find the current file position, and the file length. If
650 * the file position is greater than the length, write to
651 * extend the file with a hole. If the file position is less
652 * than the length, truncate the file.
655 ret=fstat(fd, &statbuf);
657 DEBUG ("%s: handle %p fstat failed: %s", __func__,
658 handle, strerror(errno));
660 _wapi_set_last_error_from_errno ();
663 size=statbuf.st_size;
665 pos=lseek(fd, (off_t)0, SEEK_CUR);
667 DEBUG("%s: handle %p lseek failed: %s", __func__,
668 handle, strerror(errno));
670 _wapi_set_last_error_from_errno ();
674 #ifdef FTRUNCATE_DOESNT_EXTEND
675 /* I haven't bothered to write the configure.in stuff for this
676 * because I don't know if any platform needs it. I'm leaving
677 * this code just in case though
680 /* Extend the file. Use write() here, because some
681 * manuals say that ftruncate() behaviour is undefined
682 * when the file needs extending. The POSIX spec says
683 * that on XSI-conformant systems it extends, so if
684 * every system we care about conforms, then we can
688 ret = write (fd, "", 1);
689 } while (ret == -1 && errno == EINTR &&
690 !_wapi_thread_cur_apc_pending());
693 DEBUG("%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
695 _wapi_set_last_error_from_errno ();
699 /* And put the file position back after the write */
700 ret = lseek (fd, pos, SEEK_SET);
702 DEBUG ("%s: handle %p second lseek failed: %s",
703 __func__, handle, strerror(errno));
705 _wapi_set_last_error_from_errno ();
711 /* always truncate, because the extend write() adds an extra
712 * byte to the end of the file
715 ret=ftruncate(fd, pos);
717 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
719 DEBUG("%s: handle %p ftruncate failed: %s", __func__,
720 handle, strerror(errno));
722 _wapi_set_last_error_from_errno ();
729 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
731 struct _WapiHandle_file *file_handle;
738 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
739 (gpointer *)&file_handle);
741 g_warning ("%s: error looking up file handle %p", __func__,
743 SetLastError (ERROR_INVALID_HANDLE);
744 return(INVALID_FILE_SIZE);
746 fd = file_handle->fd;
748 if(!(file_handle->fileaccess & GENERIC_READ) &&
749 !(file_handle->fileaccess & GENERIC_WRITE) &&
750 !(file_handle->fileaccess & GENERIC_ALL)) {
751 DEBUG("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
753 SetLastError (ERROR_ACCESS_DENIED);
754 return(INVALID_FILE_SIZE);
757 /* If the file has a size with the low bits 0xFFFFFFFF the
758 * caller can't tell if this is an error, so clear the error
761 SetLastError (ERROR_SUCCESS);
763 ret = fstat(fd, &statbuf);
765 DEBUG ("%s: handle %p fstat failed: %s", __func__,
766 handle, strerror(errno));
768 _wapi_set_last_error_from_errno ();
769 return(INVALID_FILE_SIZE);
772 /* fstat indicates block devices as zero-length, so go a different path */
774 if (S_ISBLK(statbuf.st_mode)) {
776 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
777 DEBUG ("%s: handle %p ioctl BLKGETSIZE64 failed: %s",
778 __func__, handle, strerror(errno));
780 _wapi_set_last_error_from_errno ();
781 return(INVALID_FILE_SIZE);
784 size = bigsize & 0xFFFFFFFF;
785 if (highsize != NULL) {
786 *highsize = bigsize>>32;
789 DEBUG ("%s: Returning block device size %d/%d",
790 __func__, size, *highsize);
796 #ifdef HAVE_LARGE_FILE_SUPPORT
797 size = statbuf.st_size & 0xFFFFFFFF;
798 if (highsize != NULL) {
799 *highsize = statbuf.st_size>>32;
802 if (highsize != NULL) {
803 /* Accurate, but potentially dodgy :-) */
806 size = statbuf.st_size;
809 DEBUG ("%s: Returning size %d/%d", __func__, size, *highsize);
814 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
815 WapiFileTime *last_access,
816 WapiFileTime *last_write)
818 struct _WapiHandle_file *file_handle;
821 guint64 create_ticks, access_ticks, write_ticks;
824 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
825 (gpointer *)&file_handle);
827 g_warning ("%s: error looking up file handle %p", __func__,
829 SetLastError (ERROR_INVALID_HANDLE);
832 fd = file_handle->fd;
834 if(!(file_handle->fileaccess & GENERIC_READ) &&
835 !(file_handle->fileaccess & GENERIC_ALL)) {
836 DEBUG("%s: handle %p doesn't have GENERIC_READ access: %u",
837 __func__, handle, file_handle->fileaccess);
839 SetLastError (ERROR_ACCESS_DENIED);
843 ret=fstat(fd, &statbuf);
845 DEBUG("%s: handle %p fstat failed: %s", __func__, handle,
848 _wapi_set_last_error_from_errno ();
852 DEBUG("%s: atime: %ld ctime: %ld mtime: %ld", __func__,
853 statbuf.st_atime, statbuf.st_ctime,
856 /* Try and guess a meaningful create time by using the older
859 /* The magic constant comes from msdn documentation
860 * "Converting a time_t Value to a File Time"
862 if(statbuf.st_atime < statbuf.st_ctime) {
863 create_ticks=((guint64)statbuf.st_atime*10000000)
864 + 116444736000000000ULL;
866 create_ticks=((guint64)statbuf.st_ctime*10000000)
867 + 116444736000000000ULL;
870 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
871 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
873 DEBUG("%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
874 access_ticks, create_ticks, write_ticks);
876 if(create_time!=NULL) {
877 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
878 create_time->dwHighDateTime = create_ticks >> 32;
881 if(last_access!=NULL) {
882 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
883 last_access->dwHighDateTime = access_ticks >> 32;
886 if(last_write!=NULL) {
887 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
888 last_write->dwHighDateTime = write_ticks >> 32;
894 static gboolean file_setfiletime(gpointer handle,
895 const WapiFileTime *create_time G_GNUC_UNUSED,
896 const WapiFileTime *last_access,
897 const WapiFileTime *last_write)
899 struct _WapiHandle_file *file_handle;
901 struct utimbuf utbuf;
903 guint64 access_ticks, write_ticks;
906 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
907 (gpointer *)&file_handle);
909 g_warning ("%s: error looking up file handle %p", __func__,
911 SetLastError (ERROR_INVALID_HANDLE);
914 fd = file_handle->fd;
916 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
917 !(file_handle->fileaccess & GENERIC_ALL)) {
918 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
920 SetLastError (ERROR_ACCESS_DENIED);
924 if(file_handle->filename == NULL) {
925 DEBUG("%s: handle %p unknown filename", __func__, handle);
927 SetLastError (ERROR_INVALID_HANDLE);
931 /* Get the current times, so we can put the same times back in
932 * the event that one of the FileTime structs is NULL
934 ret=fstat (fd, &statbuf);
936 DEBUG("%s: handle %p fstat failed: %s", __func__, handle,
939 SetLastError (ERROR_INVALID_PARAMETER);
943 if(last_access!=NULL) {
944 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
945 last_access->dwLowDateTime;
946 /* This is (time_t)0. We can actually go to INT_MIN,
947 * but this will do for now.
949 if (access_ticks < 116444736000000000ULL) {
950 DEBUG ("%s: attempt to set access time too early",
952 SetLastError (ERROR_INVALID_PARAMETER);
956 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
958 utbuf.actime=statbuf.st_atime;
961 if(last_write!=NULL) {
962 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
963 last_write->dwLowDateTime;
964 /* This is (time_t)0. We can actually go to INT_MIN,
965 * but this will do for now.
967 if (write_ticks < 116444736000000000ULL) {
968 DEBUG ("%s: attempt to set write time too early",
970 SetLastError (ERROR_INVALID_PARAMETER);
974 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
976 utbuf.modtime=statbuf.st_mtime;
979 DEBUG ("%s: setting handle %p access %ld write %ld", __func__,
980 handle, utbuf.actime, utbuf.modtime);
982 ret = _wapi_utime (file_handle->filename, &utbuf);
984 DEBUG ("%s: handle %p [%s] utime failed: %s", __func__,
985 handle, file_handle->filename, strerror(errno));
987 SetLastError (ERROR_INVALID_PARAMETER);
994 static void console_close (gpointer handle, gpointer data)
996 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
997 int fd = console_handle->fd;
999 DEBUG("%s: closing console handle %p", __func__, handle);
1001 g_free (console_handle->filename);
1006 static WapiFileType console_getfiletype(void)
1008 return(FILE_TYPE_CHAR);
1011 static gboolean console_read(gpointer handle, gpointer buffer,
1012 guint32 numbytes, guint32 *bytesread,
1013 WapiOverlapped *overlapped G_GNUC_UNUSED)
1015 struct _WapiHandle_file *console_handle;
1019 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1020 (gpointer *)&console_handle);
1022 g_warning ("%s: error looking up console handle %p", __func__,
1024 SetLastError (ERROR_INVALID_HANDLE);
1027 fd = console_handle->fd;
1029 if(bytesread!=NULL) {
1033 if(!(console_handle->fileaccess & GENERIC_READ) &&
1034 !(console_handle->fileaccess & GENERIC_ALL)) {
1035 DEBUG ("%s: handle %p doesn't have GENERIC_READ access: %u",
1036 __func__, handle, console_handle->fileaccess);
1038 SetLastError (ERROR_ACCESS_DENIED);
1043 ret=read(fd, buffer, numbytes);
1044 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1047 DEBUG("%s: read of handle %p error: %s", __func__, handle,
1050 _wapi_set_last_error_from_errno ();
1054 if(bytesread!=NULL) {
1061 static gboolean console_write(gpointer handle, gconstpointer buffer,
1062 guint32 numbytes, guint32 *byteswritten,
1063 WapiOverlapped *overlapped G_GNUC_UNUSED)
1065 struct _WapiHandle_file *console_handle;
1069 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1070 (gpointer *)&console_handle);
1072 g_warning ("%s: error looking up console handle %p", __func__,
1074 SetLastError (ERROR_INVALID_HANDLE);
1077 fd = console_handle->fd;
1079 if(byteswritten!=NULL) {
1083 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1084 !(console_handle->fileaccess & GENERIC_ALL)) {
1085 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, console_handle->fileaccess);
1087 SetLastError (ERROR_ACCESS_DENIED);
1092 ret = write(fd, buffer, numbytes);
1093 } while (ret == -1 && errno == EINTR &&
1094 !_wapi_thread_cur_apc_pending());
1097 if (errno == EINTR) {
1100 _wapi_set_last_error_from_errno ();
1102 DEBUG ("%s: write of handle %p error: %s",
1103 __func__, handle, strerror(errno));
1108 if(byteswritten!=NULL) {
1115 static void pipe_close (gpointer handle, gpointer data)
1117 struct _WapiHandle_file *pipe_handle = (struct _WapiHandle_file*)data;
1118 int fd = pipe_handle->fd;
1120 DEBUG("%s: closing pipe handle %p", __func__, handle);
1122 /* No filename with pipe handles */
1127 static WapiFileType pipe_getfiletype(void)
1129 return(FILE_TYPE_PIPE);
1132 static gboolean pipe_read (gpointer handle, gpointer buffer,
1133 guint32 numbytes, guint32 *bytesread,
1134 WapiOverlapped *overlapped G_GNUC_UNUSED)
1136 struct _WapiHandle_file *pipe_handle;
1140 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1141 (gpointer *)&pipe_handle);
1143 g_warning ("%s: error looking up pipe handle %p", __func__,
1145 SetLastError (ERROR_INVALID_HANDLE);
1148 fd = pipe_handle->fd;
1150 if(bytesread!=NULL) {
1154 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1155 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1156 DEBUG("%s: handle %p doesn't have GENERIC_READ access: %u",
1157 __func__, handle, pipe_handle->fileaccess);
1159 SetLastError (ERROR_ACCESS_DENIED);
1163 DEBUG ("%s: reading up to %d bytes from pipe %p", __func__,
1167 ret=read(fd, buffer, numbytes);
1168 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1171 if (errno == EINTR) {
1174 _wapi_set_last_error_from_errno ();
1176 DEBUG("%s: read of handle %p error: %s", __func__,
1177 handle, strerror(errno));
1183 DEBUG ("%s: read %d bytes from pipe", __func__, ret);
1185 if(bytesread!=NULL) {
1192 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1193 guint32 numbytes, guint32 *byteswritten,
1194 WapiOverlapped *overlapped G_GNUC_UNUSED)
1196 struct _WapiHandle_file *pipe_handle;
1200 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1201 (gpointer *)&pipe_handle);
1203 g_warning ("%s: error looking up pipe handle %p", __func__,
1205 SetLastError (ERROR_INVALID_HANDLE);
1208 fd = pipe_handle->fd;
1210 if(byteswritten!=NULL) {
1214 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1215 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1216 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, pipe_handle->fileaccess);
1218 SetLastError (ERROR_ACCESS_DENIED);
1222 DEBUG ("%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1226 ret = write (fd, buffer, numbytes);
1227 } while (ret == -1 && errno == EINTR &&
1228 !_wapi_thread_cur_apc_pending());
1231 if (errno == EINTR) {
1234 _wapi_set_last_error_from_errno ();
1236 DEBUG("%s: write of handle %p error: %s", __func__,
1237 handle, strerror(errno));
1242 if(byteswritten!=NULL) {
1249 static int convert_flags(guint32 fileaccess, guint32 createmode)
1253 switch(fileaccess) {
1260 case GENERIC_READ|GENERIC_WRITE:
1264 DEBUG("%s: Unknown access type 0x%x", __func__,
1269 switch(createmode) {
1271 flags|=O_CREAT|O_EXCL;
1274 flags|=O_CREAT|O_TRUNC;
1281 case TRUNCATE_EXISTING:
1285 DEBUG("%s: Unknown create mode 0x%x", __func__,
1294 static mode_t convert_perms(guint32 sharemode)
1298 if(sharemode&FILE_SHARE_READ) {
1301 if(sharemode&FILE_SHARE_WRITE) {
1309 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1311 struct _WapiFileShare **share_info)
1313 gboolean file_already_shared;
1314 guint32 file_existing_share, file_existing_access;
1316 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);
1318 if (file_already_shared) {
1319 /* The reference to this share info was incremented
1320 * when we looked it up, so be careful to put it back
1321 * if we conclude we can't use this file.
1323 if (file_existing_share == 0) {
1324 /* Quick and easy, no possibility to share */
1325 DEBUG ("%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
1327 _wapi_handle_share_release (*share_info);
1332 if (((file_existing_share == FILE_SHARE_READ) &&
1333 (fileaccess != GENERIC_READ)) ||
1334 ((file_existing_share == FILE_SHARE_WRITE) &&
1335 (fileaccess != GENERIC_WRITE))) {
1336 /* New access mode doesn't match up */
1337 DEBUG ("%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
1339 _wapi_handle_share_release (*share_info);
1344 if (((file_existing_access & GENERIC_READ) &&
1345 !(sharemode & FILE_SHARE_READ)) ||
1346 ((file_existing_access & GENERIC_WRITE) &&
1347 !(sharemode & FILE_SHARE_WRITE))) {
1348 /* New share mode doesn't match up */
1349 DEBUG ("%s: Access mode prevents open: requested share: 0x%x, file has access: 0x%x", __func__, sharemode, file_existing_access);
1351 _wapi_handle_share_release (*share_info);
1356 DEBUG ("%s: New file!", __func__);
1362 static gboolean share_check (struct stat *statbuf, guint32 sharemode,
1364 struct _WapiFileShare **share_info, int fd)
1366 if (share_allows_open (statbuf, sharemode, fileaccess,
1367 share_info) == TRUE) {
1371 /* Got a share violation. Double check that the file is still
1372 * open by someone, in case a process crashed while still
1373 * holding a file handle. This will also cope with someone
1374 * using Mono.Posix to close the file. This is cheaper and
1375 * less intrusive to other processes than initiating a handle
1379 _wapi_handle_check_share (*share_info, fd);
1380 if (share_allows_open (statbuf, sharemode, fileaccess,
1381 share_info) == TRUE) {
1385 /* Still violating. It's possible that a process crashed
1386 * while still holding a file handle, and that a non-mono
1387 * process has the file open. (For example, C-c mcs while
1388 * editing a source file.) As a last resort, run a handle
1389 * collection, which will remove stale share entries.
1391 _wapi_handle_collect ();
1393 return(share_allows_open (statbuf, sharemode, fileaccess, share_info));
1398 * @name: a pointer to a NULL-terminated unicode string, that names
1399 * the file or other object to create.
1400 * @fileaccess: specifies the file access mode
1401 * @sharemode: whether the file should be shared. This parameter is
1402 * currently ignored.
1403 * @security: Ignored for now.
1404 * @createmode: specifies whether to create a new file, whether to
1405 * overwrite an existing file, whether to truncate the file, etc.
1406 * @attrs: specifies file attributes and flags. On win32 attributes
1407 * are characteristics of the file, not the handle, and are ignored
1408 * when an existing file is opened. Flags give the library hints on
1409 * how to process a file to optimise performance.
1410 * @template: the handle of an open %GENERIC_READ file that specifies
1411 * attributes to apply to a newly created file, ignoring @attrs.
1412 * Normally this parameter is NULL. This parameter is ignored when an
1413 * existing file is opened.
1415 * Creates a new file handle. This only applies to normal files:
1416 * pipes are handled by CreatePipe(), and console handles are created
1417 * with GetStdHandle().
1419 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1421 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1422 guint32 sharemode, WapiSecurityAttributes *security,
1423 guint32 createmode, guint32 attrs,
1424 gpointer template G_GNUC_UNUSED)
1426 struct _WapiHandle_file file_handle = {0};
1428 int flags=convert_flags(fileaccess, createmode);
1429 /*mode_t perms=convert_perms(sharemode);*/
1430 /* we don't use sharemode, because that relates to sharing of
1431 * the file when the file is open and is already handled by
1432 * other code, perms instead are the on-disk permissions and
1433 * this is a sane default.
1439 struct stat statbuf;
1441 mono_once (&io_ops_once, io_ops_init);
1443 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1446 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1447 SetLastError (ERROR_ENCRYPTION_FAILED);
1448 return INVALID_HANDLE_VALUE;
1452 DEBUG ("%s: name is NULL", __func__);
1454 SetLastError (ERROR_INVALID_NAME);
1455 return(INVALID_HANDLE_VALUE);
1458 filename = mono_unicode_to_external (name);
1459 if (filename == NULL) {
1460 DEBUG("%s: unicode conversion returned NULL", __func__);
1462 SetLastError (ERROR_INVALID_NAME);
1463 return(INVALID_HANDLE_VALUE);
1466 DEBUG ("%s: Opening %s with share 0x%x and access 0x%x", __func__,
1467 filename, sharemode, fileaccess);
1469 fd = _wapi_open (filename, flags, perms);
1471 /* If we were trying to open a directory with write permissions
1472 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1473 * EISDIR. However, this is a bit bogus because calls to
1474 * manipulate the directory (e.g. SetFileTime) will still work on
1475 * the directory because they use other API calls
1476 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1477 * to open the directory again without write permission.
1479 if (fd == -1 && errno == EISDIR)
1481 /* Try again but don't try to make it writable */
1482 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1486 DEBUG("%s: Error opening file %s: %s", __func__, filename,
1488 _wapi_set_last_path_error_from_errno (NULL, filename);
1491 return(INVALID_HANDLE_VALUE);
1494 if (fd >= _wapi_fd_reserve) {
1495 DEBUG ("%s: File descriptor is too big", __func__);
1497 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1502 return(INVALID_HANDLE_VALUE);
1505 ret = fstat (fd, &statbuf);
1507 DEBUG ("%s: fstat error of file %s: %s", __func__,
1508 filename, strerror (errno));
1509 _wapi_set_last_error_from_errno ();
1513 return(INVALID_HANDLE_VALUE);
1516 if (share_check (&statbuf, sharemode, fileaccess,
1517 &file_handle.share_info, fd) == FALSE) {
1518 SetLastError (ERROR_SHARING_VIOLATION);
1522 return (INVALID_HANDLE_VALUE);
1524 if (file_handle.share_info == NULL) {
1525 /* No space, so no more files can be opened */
1526 DEBUG ("%s: No space in the share table", __func__);
1528 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1532 return(INVALID_HANDLE_VALUE);
1535 file_handle.filename = filename;
1537 if(security!=NULL) {
1538 //file_handle->security_attributes=_wapi_handle_scratch_store (
1539 //security, sizeof(WapiSecurityAttributes));
1542 file_handle.fd = fd;
1543 file_handle.fileaccess=fileaccess;
1544 file_handle.sharemode=sharemode;
1545 file_handle.attrs=attrs;
1547 #ifdef HAVE_POSIX_FADVISE
1548 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1549 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1550 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1551 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1555 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1557 if (S_ISFIFO (statbuf.st_mode)) {
1558 handle_type = WAPI_HANDLE_PIPE;
1559 } else if (S_ISCHR (statbuf.st_mode)) {
1560 handle_type = WAPI_HANDLE_CONSOLE;
1562 handle_type = WAPI_HANDLE_FILE;
1565 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1566 if (handle == _WAPI_HANDLE_INVALID) {
1567 g_warning ("%s: error creating file handle", __func__);
1571 SetLastError (ERROR_GEN_FAILURE);
1572 return(INVALID_HANDLE_VALUE);
1575 DEBUG("%s: returning handle %p", __func__, handle);
1582 * @name: a pointer to a NULL-terminated unicode string, that names
1583 * the file to be deleted.
1585 * Deletes file @name.
1587 * Return value: %TRUE on success, %FALSE otherwise.
1589 gboolean DeleteFile(const gunichar2 *name)
1593 gboolean ret = FALSE;
1596 struct stat statbuf;
1597 struct _WapiFileShare *shareinfo;
1601 DEBUG("%s: name is NULL", __func__);
1603 SetLastError (ERROR_INVALID_NAME);
1607 filename=mono_unicode_to_external(name);
1608 if(filename==NULL) {
1609 DEBUG("%s: unicode conversion returned NULL", __func__);
1611 SetLastError (ERROR_INVALID_NAME);
1615 attrs = GetFileAttributes (name);
1616 if (attrs == INVALID_FILE_ATTRIBUTES) {
1617 DEBUG ("%s: file attributes error", __func__);
1618 /* Error set by GetFileAttributes() */
1624 /* Check to make sure sharing allows us to open the file for
1625 * writing. See bug 323389.
1627 * Do the checks that don't need an open file descriptor, for
1628 * simplicity's sake. If we really have to do the full checks
1629 * then we can implement that later.
1631 if (_wapi_stat (filename, &statbuf) < 0) {
1632 _wapi_set_last_path_error_from_errno (NULL, filename);
1637 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1638 &shareinfo) == FALSE) {
1639 SetLastError (ERROR_SHARING_VIOLATION);
1644 _wapi_handle_share_release (shareinfo);
1647 retval = _wapi_unlink (filename);
1650 _wapi_set_last_path_error_from_errno (NULL, filename);
1662 * @name: a pointer to a NULL-terminated unicode string, that names
1663 * the file to be moved.
1664 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1665 * new name for the file.
1667 * Renames file @name to @dest_name.
1668 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1669 * when it is the same file as the source. In that case it silently succeeds.
1671 * Return value: %TRUE on success, %FALSE otherwise.
1673 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1675 gchar *utf8_name, *utf8_dest_name;
1676 int result, errno_copy;
1677 struct stat stat_src, stat_dest;
1678 gboolean ret = FALSE;
1679 struct _WapiFileShare *shareinfo;
1682 DEBUG("%s: name is NULL", __func__);
1684 SetLastError (ERROR_INVALID_NAME);
1688 utf8_name = mono_unicode_to_external (name);
1689 if (utf8_name == NULL) {
1690 DEBUG ("%s: unicode conversion returned NULL", __func__);
1692 SetLastError (ERROR_INVALID_NAME);
1696 if(dest_name==NULL) {
1697 DEBUG("%s: name is NULL", __func__);
1700 SetLastError (ERROR_INVALID_NAME);
1704 utf8_dest_name = mono_unicode_to_external (dest_name);
1705 if (utf8_dest_name == NULL) {
1706 DEBUG ("%s: unicode conversion returned NULL", __func__);
1709 SetLastError (ERROR_INVALID_NAME);
1714 * In C# land we check for the existence of src, but not for dest.
1715 * We check it here and return the failure if dest exists and is not
1716 * the same file as src.
1718 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1719 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1720 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1722 g_free (utf8_dest_name);
1727 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1728 if (stat_dest.st_dev != stat_src.st_dev ||
1729 stat_dest.st_ino != stat_src.st_ino) {
1731 g_free (utf8_dest_name);
1732 SetLastError (ERROR_ALREADY_EXISTS);
1737 /* Check to make sure sharing allows us to open the file for
1738 * writing. See bug 377049.
1740 * Do the checks that don't need an open file descriptor, for
1741 * simplicity's sake. If we really have to do the full checks
1742 * then we can implement that later.
1744 if (share_allows_open (&stat_src, 0, GENERIC_WRITE,
1745 &shareinfo) == FALSE) {
1746 SetLastError (ERROR_SHARING_VIOLATION);
1750 _wapi_handle_share_release (shareinfo);
1752 result = _wapi_rename (utf8_name, utf8_dest_name);
1756 switch(errno_copy) {
1758 SetLastError (ERROR_ALREADY_EXISTS);
1762 /* Ignore here, it is dealt with below */
1766 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1771 g_free (utf8_dest_name);
1773 if (result != 0 && errno_copy == EXDEV) {
1774 if (S_ISDIR (stat_src.st_mode)) {
1775 SetLastError (ERROR_NOT_SAME_DEVICE);
1778 /* Try a copy to the new location, and delete the source */
1779 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1780 /* CopyFile will set the error */
1784 return(DeleteFile (name));
1795 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1799 int buf_size = st_src->st_blksize;
1801 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1802 buf = (char *) malloc (buf_size);
1805 remain = read (src_fd, buf, buf_size);
1807 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1811 _wapi_set_last_error_from_errno ();
1821 while (remain > 0) {
1822 if ((n = write (dest_fd, wbuf, remain)) < 0) {
1823 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1827 _wapi_set_last_error_from_errno ();
1828 DEBUG ("%s: write failed.", __func__);
1844 * @name: a pointer to a NULL-terminated unicode string, that names
1845 * the file to be copied.
1846 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1847 * new name for the file.
1848 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1850 * Copies file @name to @dest_name
1852 * Return value: %TRUE on success, %FALSE otherwise.
1854 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1855 gboolean fail_if_exists)
1857 gchar *utf8_src, *utf8_dest;
1858 int src_fd, dest_fd;
1859 struct stat st, dest_st;
1860 struct utimbuf dest_time;
1861 gboolean ret = TRUE;
1865 DEBUG("%s: name is NULL", __func__);
1867 SetLastError (ERROR_INVALID_NAME);
1871 utf8_src = mono_unicode_to_external (name);
1872 if (utf8_src == NULL) {
1873 DEBUG ("%s: unicode conversion of source returned NULL",
1876 SetLastError (ERROR_INVALID_PARAMETER);
1880 if(dest_name==NULL) {
1881 DEBUG("%s: dest is NULL", __func__);
1884 SetLastError (ERROR_INVALID_NAME);
1888 utf8_dest = mono_unicode_to_external (dest_name);
1889 if (utf8_dest == NULL) {
1890 DEBUG ("%s: unicode conversion of dest returned NULL",
1893 SetLastError (ERROR_INVALID_PARAMETER);
1900 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
1902 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
1910 if (fstat (src_fd, &st) < 0) {
1911 _wapi_set_last_error_from_errno ();
1920 /* Before trying to open/create the dest, we need to report a 'file busy'
1921 * error if src and dest are actually the same file. We do the check here to take
1922 * advantage of the IOMAP capability */
1923 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
1924 st.st_ino == dest_st.st_ino) {
1930 SetLastError (ERROR_SHARING_VIOLATION);
1934 if (fail_if_exists) {
1935 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
1937 /* FIXME: it kinda sucks that this code path potentially scans
1938 * the directory twice due to the weird SetLastError()
1940 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
1942 /* The file does not exist, try creating it */
1943 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
1945 /* Apparently this error is set if we
1946 * overwrite the dest file
1948 SetLastError (ERROR_ALREADY_EXISTS);
1952 _wapi_set_last_error_from_errno ();
1961 if (!write_file (src_fd, dest_fd, &st, TRUE))
1967 dest_time.modtime = st.st_mtime;
1968 dest_time.actime = st.st_atime;
1969 ret_utime = utime (utf8_dest, &dest_time);
1970 if (ret_utime == -1)
1971 DEBUG ("%s: file [%s] utime failed: %s", __func__, utf8_dest, strerror(errno));
1980 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
1985 DEBUG ("%s: %s is NULL", __func__, arg_name);
1986 SetLastError (ERROR_INVALID_NAME);
1990 utf8_ret = mono_unicode_to_external (arg);
1991 if (utf8_ret == NULL) {
1992 DEBUG ("%s: unicode conversion of %s returned NULL",
1993 __func__, arg_name);
1994 SetLastError (ERROR_INVALID_PARAMETER);
2002 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2003 const gunichar2 *backupFileName, guint32 replaceFlags,
2004 gpointer exclude, gpointer reserved)
2006 int result, errno_copy, backup_fd = -1,replaced_fd = -1;
2007 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2008 struct stat stBackup;
2009 gboolean ret = FALSE;
2011 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2013 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2014 goto replace_cleanup;
2015 if (backupFileName != NULL) {
2016 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2017 goto replace_cleanup;
2020 if (utf8_backupFileName) {
2021 // Open the backup file for read so we can restore the file if an error occurs.
2022 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2023 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2026 goto replace_cleanup;
2029 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2032 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2033 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2034 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2035 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2038 if (replaced_fd == -1)
2039 goto replace_cleanup;
2041 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2044 goto replace_cleanup;
2050 g_free (utf8_replacedFileName);
2051 g_free (utf8_replacementFileName);
2052 g_free (utf8_backupFileName);
2053 if (backup_fd != -1)
2055 if (replaced_fd != -1)
2056 close (replaced_fd);
2062 * @stdhandle: specifies the file descriptor
2064 * Returns a handle for stdin, stdout, or stderr. Always returns the
2065 * same handle for the same @stdhandle.
2067 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2070 static mono_mutex_t stdhandle_mutex = MONO_MUTEX_INITIALIZER;
2072 gpointer GetStdHandle(WapiStdHandle stdhandle)
2074 struct _WapiHandle_file *file_handle;
2081 case STD_INPUT_HANDLE:
2086 case STD_OUTPUT_HANDLE:
2091 case STD_ERROR_HANDLE:
2097 DEBUG("%s: unknown standard handle type", __func__);
2099 SetLastError (ERROR_INVALID_PARAMETER);
2100 return(INVALID_HANDLE_VALUE);
2103 handle = GINT_TO_POINTER (fd);
2105 pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2106 (void *)&stdhandle_mutex);
2107 thr_ret = mono_mutex_lock (&stdhandle_mutex);
2108 g_assert (thr_ret == 0);
2110 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2111 (gpointer *)&file_handle);
2113 /* Need to create this console handle */
2114 handle = _wapi_stdhandle_create (fd, name);
2116 if (handle == INVALID_HANDLE_VALUE) {
2117 SetLastError (ERROR_NO_MORE_FILES);
2121 /* Add a reference to this handle */
2122 _wapi_handle_ref (handle);
2126 thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2127 g_assert (thr_ret == 0);
2128 pthread_cleanup_pop (0);
2135 * @handle: The file handle to read from. The handle must have
2136 * %GENERIC_READ access.
2137 * @buffer: The buffer to store read data in
2138 * @numbytes: The maximum number of bytes to read
2139 * @bytesread: The actual number of bytes read is stored here. This
2140 * value can be zero if the handle is positioned at the end of the
2142 * @overlapped: points to a required %WapiOverlapped structure if
2143 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2146 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2147 * function reads up to @numbytes bytes from the file from the current
2148 * file position, and stores them in @buffer. If there are not enough
2149 * bytes left in the file, just the amount available will be read.
2150 * The actual number of bytes read is stored in @bytesread.
2152 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2153 * file position is ignored and the read position is taken from data
2154 * in the @overlapped structure.
2156 * Return value: %TRUE if the read succeeds (even if no bytes were
2157 * read due to an attempt to read past the end of the file), %FALSE on
2160 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2161 guint32 *bytesread, WapiOverlapped *overlapped)
2163 WapiHandleType type;
2165 type = _wapi_handle_type (handle);
2167 if(io_ops[type].readfile==NULL) {
2168 SetLastError (ERROR_INVALID_HANDLE);
2172 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2178 * @handle: The file handle to write to. The handle must have
2179 * %GENERIC_WRITE access.
2180 * @buffer: The buffer to read data from.
2181 * @numbytes: The maximum number of bytes to write.
2182 * @byteswritten: The actual number of bytes written is stored here.
2183 * If the handle is positioned at the file end, the length of the file
2184 * is extended. This parameter may be %NULL.
2185 * @overlapped: points to a required %WapiOverlapped structure if
2186 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2189 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2190 * function writes up to @numbytes bytes from @buffer to the file at
2191 * the current file position. If @handle is positioned at the end of
2192 * the file, the file is extended. The actual number of bytes written
2193 * is stored in @byteswritten.
2195 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2196 * file position is ignored and the write position is taken from data
2197 * in the @overlapped structure.
2199 * Return value: %TRUE if the write succeeds, %FALSE on error.
2201 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2202 guint32 *byteswritten, WapiOverlapped *overlapped)
2204 WapiHandleType type;
2206 type = _wapi_handle_type (handle);
2208 if(io_ops[type].writefile==NULL) {
2209 SetLastError (ERROR_INVALID_HANDLE);
2213 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2219 * @handle: Handle to open file. The handle must have
2220 * %GENERIC_WRITE access.
2222 * Flushes buffers of the file and causes all unwritten data to
2225 * Return value: %TRUE on success, %FALSE otherwise.
2227 gboolean FlushFileBuffers(gpointer handle)
2229 WapiHandleType type;
2231 type = _wapi_handle_type (handle);
2233 if(io_ops[type].flushfile==NULL) {
2234 SetLastError (ERROR_INVALID_HANDLE);
2238 return(io_ops[type].flushfile (handle));
2243 * @handle: The file handle to set. The handle must have
2244 * %GENERIC_WRITE access.
2246 * Moves the end-of-file position to the current position of the file
2247 * pointer. This function is used to truncate or extend a file.
2249 * Return value: %TRUE on success, %FALSE otherwise.
2251 gboolean SetEndOfFile(gpointer handle)
2253 WapiHandleType type;
2255 type = _wapi_handle_type (handle);
2257 if (io_ops[type].setendoffile == NULL) {
2258 SetLastError (ERROR_INVALID_HANDLE);
2262 return(io_ops[type].setendoffile (handle));
2267 * @handle: The file handle to set. The handle must have
2268 * %GENERIC_READ or %GENERIC_WRITE access.
2269 * @movedistance: Low 32 bits of a signed value that specifies the
2270 * number of bytes to move the file pointer.
2271 * @highmovedistance: Pointer to the high 32 bits of a signed value
2272 * that specifies the number of bytes to move the file pointer, or
2274 * @method: The starting point for the file pointer move.
2276 * Sets the file pointer of an open file.
2278 * The distance to move the file pointer is calculated from
2279 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2280 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2281 * is the low 32 bits and @highmovedistance a pointer to the high 32
2282 * bits of a 64 bit signed value. A positive distance moves the file
2283 * pointer forward from the position specified by @method; a negative
2284 * distance moves the file pointer backward.
2286 * If the library is compiled without large file support,
2287 * @highmovedistance is ignored and its value is set to zero on a
2288 * successful return.
2290 * Return value: On success, the low 32 bits of the new file pointer.
2291 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2292 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2294 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2295 gint32 *highmovedistance, WapiSeekMethod method)
2297 WapiHandleType type;
2299 type = _wapi_handle_type (handle);
2301 if (io_ops[type].seek == NULL) {
2302 SetLastError (ERROR_INVALID_HANDLE);
2303 return(INVALID_SET_FILE_POINTER);
2306 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2312 * @handle: The file handle to test.
2314 * Finds the type of file @handle.
2316 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2317 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2318 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2319 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2321 WapiFileType GetFileType(gpointer handle)
2323 WapiHandleType type;
2325 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2326 SetLastError (ERROR_INVALID_HANDLE);
2327 return(FILE_TYPE_UNKNOWN);
2330 type = _wapi_handle_type (handle);
2332 if (io_ops[type].getfiletype == NULL) {
2333 SetLastError (ERROR_INVALID_HANDLE);
2334 return(FILE_TYPE_UNKNOWN);
2337 return(io_ops[type].getfiletype ());
2342 * @handle: The file handle to query. The handle must have
2343 * %GENERIC_READ or %GENERIC_WRITE access.
2344 * @highsize: If non-%NULL, the high 32 bits of the file size are
2347 * Retrieves the size of the file @handle.
2349 * If the library is compiled without large file support, @highsize
2350 * has its value set to zero on a successful return.
2352 * Return value: On success, the low 32 bits of the file size. If
2353 * @highsize is non-%NULL then the high 32 bits of the file size are
2354 * stored here. On failure %INVALID_FILE_SIZE is returned.
2356 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2358 WapiHandleType type;
2360 type = _wapi_handle_type (handle);
2362 if (io_ops[type].getfilesize == NULL) {
2363 SetLastError (ERROR_INVALID_HANDLE);
2364 return(INVALID_FILE_SIZE);
2367 return(io_ops[type].getfilesize (handle, highsize));
2372 * @handle: The file handle to query. The handle must have
2373 * %GENERIC_READ access.
2374 * @create_time: Points to a %WapiFileTime structure to receive the
2375 * number of ticks since the epoch that file was created. May be
2377 * @last_access: Points to a %WapiFileTime structure to receive the
2378 * number of ticks since the epoch when file was last accessed. May be
2380 * @last_write: Points to a %WapiFileTime structure to receive the
2381 * number of ticks since the epoch when file was last written to. May
2384 * Finds the number of ticks since the epoch that the file referenced
2385 * by @handle was created, last accessed and last modified. A tick is
2386 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2389 * Create time isn't recorded on POSIX file systems or reported by
2390 * stat(2), so that time is guessed by returning the oldest of the
2393 * Return value: %TRUE on success, %FALSE otherwise.
2395 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2396 WapiFileTime *last_access, WapiFileTime *last_write)
2398 WapiHandleType type;
2400 type = _wapi_handle_type (handle);
2402 if (io_ops[type].getfiletime == NULL) {
2403 SetLastError (ERROR_INVALID_HANDLE);
2407 return(io_ops[type].getfiletime (handle, create_time, last_access,
2413 * @handle: The file handle to set. The handle must have
2414 * %GENERIC_WRITE access.
2415 * @create_time: Points to a %WapiFileTime structure that contains the
2416 * number of ticks since the epoch that the file was created. May be
2418 * @last_access: Points to a %WapiFileTime structure that contains the
2419 * number of ticks since the epoch when the file was last accessed.
2421 * @last_write: Points to a %WapiFileTime structure that contains the
2422 * number of ticks since the epoch when the file was last written to.
2425 * Sets the number of ticks since the epoch that the file referenced
2426 * by @handle was created, last accessed or last modified. A tick is
2427 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2430 * Create time isn't recorded on POSIX file systems, and is ignored.
2432 * Return value: %TRUE on success, %FALSE otherwise.
2434 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2435 const WapiFileTime *last_access,
2436 const WapiFileTime *last_write)
2438 WapiHandleType type;
2440 type = _wapi_handle_type (handle);
2442 if (io_ops[type].setfiletime == NULL) {
2443 SetLastError (ERROR_INVALID_HANDLE);
2447 return(io_ops[type].setfiletime (handle, create_time, last_access,
2451 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2452 * January 1 1601 GMT
2455 #define TICKS_PER_MILLISECOND 10000L
2456 #define TICKS_PER_SECOND 10000000L
2457 #define TICKS_PER_MINUTE 600000000L
2458 #define TICKS_PER_HOUR 36000000000LL
2459 #define TICKS_PER_DAY 864000000000LL
2461 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2463 static const guint16 mon_yday[2][13]={
2464 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2465 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2469 * FileTimeToSystemTime:
2470 * @file_time: Points to a %WapiFileTime structure that contains the
2471 * number of ticks to convert.
2472 * @system_time: Points to a %WapiSystemTime structure to receive the
2475 * Converts a tick count into broken-out time values.
2477 * Return value: %TRUE on success, %FALSE otherwise.
2479 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2480 WapiSystemTime *system_time)
2482 gint64 file_ticks, totaldays, rem, y;
2485 if(system_time==NULL) {
2486 DEBUG("%s: system_time NULL", __func__);
2488 SetLastError (ERROR_INVALID_PARAMETER);
2492 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2493 file_time->dwLowDateTime;
2495 /* Really compares if file_ticks>=0x8000000000000000
2496 * (LLONG_MAX+1) but we're working with a signed value for the
2497 * year and day calculation to work later
2500 DEBUG("%s: file_time too big", __func__);
2502 SetLastError (ERROR_INVALID_PARAMETER);
2506 totaldays=(file_ticks / TICKS_PER_DAY);
2507 rem = file_ticks % TICKS_PER_DAY;
2508 DEBUG("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2510 system_time->wHour=rem/TICKS_PER_HOUR;
2511 rem %= TICKS_PER_HOUR;
2512 DEBUG("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2514 system_time->wMinute = rem / TICKS_PER_MINUTE;
2515 rem %= TICKS_PER_MINUTE;
2516 DEBUG("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2519 system_time->wSecond = rem / TICKS_PER_SECOND;
2520 rem %= TICKS_PER_SECOND;
2521 DEBUG("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2524 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2525 DEBUG("%s: Milliseconds: %d", __func__,
2526 system_time->wMilliseconds);
2528 /* January 1, 1601 was a Monday, according to Emacs calendar */
2529 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2530 DEBUG("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2532 /* This algorithm to find year and month given days from epoch
2537 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2538 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2540 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2541 /* Guess a corrected year, assuming 365 days per year */
2542 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2543 DEBUG("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2546 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2547 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2549 /* Adjust days and y to match the guessed year. */
2550 totaldays -= ((yg - y) * 365
2551 + LEAPS_THRU_END_OF (yg - 1)
2552 - LEAPS_THRU_END_OF (y - 1));
2553 DEBUG("%s: totaldays: %lld", __func__, totaldays);
2555 DEBUG("%s: y: %lld", __func__, y);
2558 system_time->wYear = y;
2559 DEBUG("%s: Year: %d", __func__, system_time->wYear);
2561 ip = mon_yday[isleap(y)];
2563 for(y=11; totaldays < ip[y]; --y) {
2567 DEBUG("%s: totaldays: %lld", __func__, totaldays);
2569 system_time->wMonth = y + 1;
2570 DEBUG("%s: Month: %d", __func__, system_time->wMonth);
2572 system_time->wDay = totaldays + 1;
2573 DEBUG("%s: Day: %d", __func__, system_time->wDay);
2578 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2580 struct _WapiHandle_find find_handle = {0};
2582 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2585 if (pattern == NULL) {
2586 DEBUG ("%s: pattern is NULL", __func__);
2588 SetLastError (ERROR_PATH_NOT_FOUND);
2589 return(INVALID_HANDLE_VALUE);
2592 utf8_pattern = mono_unicode_to_external (pattern);
2593 if (utf8_pattern == NULL) {
2594 DEBUG ("%s: unicode conversion returned NULL", __func__);
2596 SetLastError (ERROR_INVALID_NAME);
2597 return(INVALID_HANDLE_VALUE);
2600 DEBUG ("%s: looking for [%s]", __func__, utf8_pattern);
2602 /* Figure out which bit of the pattern is the directory */
2603 dir_part = _wapi_dirname (utf8_pattern);
2604 entry_part = _wapi_basename (utf8_pattern);
2607 /* Don't do this check for now, it breaks if directories
2608 * really do have metachars in their names (see bug 58116).
2609 * FIXME: Figure out a better solution to keep some checks...
2611 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2612 SetLastError (ERROR_INVALID_NAME);
2614 g_free (entry_part);
2615 g_free (utf8_pattern);
2616 return(INVALID_HANDLE_VALUE);
2620 /* The pattern can specify a directory or a set of files.
2622 * The pattern can have wildcard characters ? and *, but only
2623 * in the section after the last directory delimiter. (Return
2624 * ERROR_INVALID_NAME if there are wildcards in earlier path
2625 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2626 * means "match one character", "??" seems to mean "match one
2627 * or two characters", "???" seems to mean "match one, two or
2628 * three characters", etc. Windows will also try and match
2629 * the mangled "short name" of files, so 8 character patterns
2630 * with wildcards will show some surprising results.
2632 * All the written documentation I can find says that '?'
2633 * should only match one character, and doesn't mention '??',
2634 * '???' etc. I'm going to assume that the strict behaviour
2635 * (ie '???' means three and only three characters) is the
2636 * correct one, because that lets me use fnmatch(3) rather
2637 * than mess around with regexes.
2640 find_handle.namelist = NULL;
2641 result = _wapi_io_scandir (dir_part, entry_part,
2642 &find_handle.namelist);
2645 /* No files, which windows seems to call
2648 SetLastError (ERROR_FILE_NOT_FOUND);
2649 g_free (utf8_pattern);
2650 g_free (entry_part);
2652 return (INVALID_HANDLE_VALUE);
2656 #ifdef DEBUG_ENABLED
2657 gint errnum = errno;
2659 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2660 DEBUG ("%s: scandir error: %s", __func__,
2661 g_strerror (errnum));
2662 g_free (utf8_pattern);
2663 g_free (entry_part);
2665 return (INVALID_HANDLE_VALUE);
2668 g_free (utf8_pattern);
2669 g_free (entry_part);
2671 DEBUG ("%s: Got %d matches", __func__, result);
2673 find_handle.dir_part = dir_part;
2674 find_handle.num = result;
2675 find_handle.count = 0;
2677 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2678 if (handle == _WAPI_HANDLE_INVALID) {
2679 g_warning ("%s: error creating find handle", __func__);
2681 g_free (entry_part);
2682 g_free (utf8_pattern);
2683 SetLastError (ERROR_GEN_FAILURE);
2685 return(INVALID_HANDLE_VALUE);
2688 if (handle != INVALID_HANDLE_VALUE &&
2689 !FindNextFile (handle, find_data)) {
2691 SetLastError (ERROR_NO_MORE_FILES);
2692 handle = INVALID_HANDLE_VALUE;
2698 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2700 struct _WapiHandle_find *find_handle;
2702 struct stat buf, linkbuf;
2705 gchar *utf8_filename, *utf8_basename;
2706 gunichar2 *utf16_basename;
2710 gboolean ret = FALSE;
2712 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2713 (gpointer *)&find_handle);
2715 g_warning ("%s: error looking up find handle %p", __func__,
2717 SetLastError (ERROR_INVALID_HANDLE);
2721 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2723 thr_ret = _wapi_handle_lock_handle (handle);
2724 g_assert (thr_ret == 0);
2727 if (find_handle->count >= find_handle->num) {
2728 SetLastError (ERROR_NO_MORE_FILES);
2732 /* stat next match */
2734 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2736 result = _wapi_stat (filename, &buf);
2737 if (result == -1 && errno == ENOENT) {
2738 /* Might be a dangling symlink */
2739 result = _wapi_lstat (filename, &buf);
2743 DEBUG ("%s: stat failed: %s", __func__, filename);
2749 result = _wapi_lstat (filename, &linkbuf);
2751 DEBUG ("%s: lstat failed: %s", __func__, filename);
2757 utf8_filename = mono_utf8_from_external (filename);
2758 if (utf8_filename == NULL) {
2759 /* We couldn't turn this filename into utf8 (eg the
2760 * encoding of the name wasn't convertible), so just
2763 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2770 DEBUG ("%s: Found [%s]", __func__, utf8_filename);
2772 /* fill data block */
2774 if (buf.st_mtime < buf.st_ctime)
2775 create_time = buf.st_mtime;
2777 create_time = buf.st_ctime;
2779 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2781 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2782 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2783 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2785 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2786 find_data->nFileSizeHigh = 0;
2787 find_data->nFileSizeLow = 0;
2789 find_data->nFileSizeHigh = buf.st_size >> 32;
2790 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2793 find_data->dwReserved0 = 0;
2794 find_data->dwReserved1 = 0;
2796 utf8_basename = _wapi_basename (utf8_filename);
2797 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2799 if(utf16_basename==NULL) {
2800 g_free (utf8_basename);
2801 g_free (utf8_filename);
2806 /* utf16 is 2 * utf8 */
2809 memset (find_data->cFileName, '\0', (MAX_PATH*2));
2811 /* Truncating a utf16 string like this might leave the last
2814 memcpy (find_data->cFileName, utf16_basename,
2815 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
2817 find_data->cAlternateFileName [0] = 0; /* not used */
2819 g_free (utf8_basename);
2820 g_free (utf8_filename);
2821 g_free (utf16_basename);
2824 thr_ret = _wapi_handle_unlock_handle (handle);
2825 g_assert (thr_ret == 0);
2826 pthread_cleanup_pop (0);
2833 * @wapi_handle: the find handle to close.
2835 * Closes find handle @wapi_handle
2837 * Return value: %TRUE on success, %FALSE otherwise.
2839 gboolean FindClose (gpointer handle)
2841 struct _WapiHandle_find *find_handle;
2845 if (handle == NULL) {
2846 SetLastError (ERROR_INVALID_HANDLE);
2850 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2851 (gpointer *)&find_handle);
2853 g_warning ("%s: error looking up find handle %p", __func__,
2855 SetLastError (ERROR_INVALID_HANDLE);
2859 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2861 thr_ret = _wapi_handle_lock_handle (handle);
2862 g_assert (thr_ret == 0);
2864 g_strfreev (find_handle->namelist);
2865 g_free (find_handle->dir_part);
2867 thr_ret = _wapi_handle_unlock_handle (handle);
2868 g_assert (thr_ret == 0);
2869 pthread_cleanup_pop (0);
2871 _wapi_handle_unref (handle);
2878 * @name: a pointer to a NULL-terminated unicode string, that names
2879 * the directory to be created.
2880 * @security: ignored for now
2882 * Creates directory @name
2884 * Return value: %TRUE on success, %FALSE otherwise.
2886 gboolean CreateDirectory (const gunichar2 *name,
2887 WapiSecurityAttributes *security)
2893 DEBUG("%s: name is NULL", __func__);
2895 SetLastError (ERROR_INVALID_NAME);
2899 utf8_name = mono_unicode_to_external (name);
2900 if (utf8_name == NULL) {
2901 DEBUG ("%s: unicode conversion returned NULL", __func__);
2903 SetLastError (ERROR_INVALID_NAME);
2907 result = _wapi_mkdir (utf8_name, 0777);
2914 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2921 * @name: a pointer to a NULL-terminated unicode string, that names
2922 * the directory to be removed.
2924 * Removes directory @name
2926 * Return value: %TRUE on success, %FALSE otherwise.
2928 gboolean RemoveDirectory (const gunichar2 *name)
2934 DEBUG("%s: name is NULL", __func__);
2936 SetLastError (ERROR_INVALID_NAME);
2940 utf8_name = mono_unicode_to_external (name);
2941 if (utf8_name == NULL) {
2942 DEBUG ("%s: unicode conversion returned NULL", __func__);
2944 SetLastError (ERROR_INVALID_NAME);
2948 result = _wapi_rmdir (utf8_name);
2950 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2961 * GetFileAttributes:
2962 * @name: a pointer to a NULL-terminated unicode filename.
2964 * Gets the attributes for @name;
2966 * Return value: %INVALID_FILE_ATTRIBUTES on failure
2968 guint32 GetFileAttributes (const gunichar2 *name)
2971 struct stat buf, linkbuf;
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_PARAMETER);
2987 return (INVALID_FILE_ATTRIBUTES);
2990 result = _wapi_stat (utf8_name, &buf);
2991 if (result == -1 && errno == ENOENT) {
2992 /* Might be a dangling symlink... */
2993 result = _wapi_lstat (utf8_name, &buf);
2997 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2999 return (INVALID_FILE_ATTRIBUTES);
3002 result = _wapi_lstat (utf8_name, &linkbuf);
3004 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3006 return (INVALID_FILE_ATTRIBUTES);
3009 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3017 * GetFileAttributesEx:
3018 * @name: a pointer to a NULL-terminated unicode filename.
3019 * @level: must be GetFileExInfoStandard
3020 * @info: pointer to a WapiFileAttributesData structure
3022 * Gets attributes, size and filetimes for @name;
3024 * Return value: %TRUE on success, %FALSE on failure
3026 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3029 WapiFileAttributesData *data;
3031 struct stat buf, linkbuf;
3035 if (level != GetFileExInfoStandard) {
3036 DEBUG ("%s: info level %d not supported.", __func__,
3039 SetLastError (ERROR_INVALID_PARAMETER);
3044 DEBUG("%s: name is NULL", __func__);
3046 SetLastError (ERROR_INVALID_NAME);
3050 utf8_name = mono_unicode_to_external (name);
3051 if (utf8_name == NULL) {
3052 DEBUG ("%s: unicode conversion returned NULL", __func__);
3054 SetLastError (ERROR_INVALID_PARAMETER);
3058 result = _wapi_stat (utf8_name, &buf);
3059 if (result == -1 && errno == ENOENT) {
3060 /* Might be a dangling symlink... */
3061 result = _wapi_lstat (utf8_name, &buf);
3065 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3070 result = _wapi_lstat (utf8_name, &linkbuf);
3072 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3077 /* fill data block */
3079 data = (WapiFileAttributesData *)info;
3081 if (buf.st_mtime < buf.st_ctime)
3082 create_time = buf.st_mtime;
3084 create_time = buf.st_ctime;
3086 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3092 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3093 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3094 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3096 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3097 data->nFileSizeHigh = 0;
3098 data->nFileSizeLow = 0;
3101 data->nFileSizeHigh = buf.st_size >> 32;
3102 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3110 * @name: name of file
3111 * @attrs: attributes to set
3113 * Changes the attributes on a named file.
3115 * Return value: %TRUE on success, %FALSE on failure.
3117 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3119 /* FIXME: think of something clever to do on unix */
3125 * Currently we only handle one *internal* case, with a value that is
3126 * not standard: 0x80000000, which means `set executable bit'
3130 DEBUG("%s: name is NULL", __func__);
3132 SetLastError (ERROR_INVALID_NAME);
3136 utf8_name = mono_unicode_to_external (name);
3137 if (utf8_name == NULL) {
3138 DEBUG ("%s: unicode conversion returned NULL", __func__);
3140 SetLastError (ERROR_INVALID_NAME);
3144 result = _wapi_stat (utf8_name, &buf);
3145 if (result == -1 && errno == ENOENT) {
3146 /* Might be a dangling symlink... */
3147 result = _wapi_lstat (utf8_name, &buf);
3151 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3156 /* Contrary to the documentation, ms allows NORMAL to be
3157 * specified along with other attributes, so dont bother to
3158 * catch that case here.
3160 if (attrs & FILE_ATTRIBUTE_READONLY) {
3161 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3163 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3166 /* Ignore the other attributes for now */
3168 if (attrs & 0x80000000){
3169 mode_t exec_mask = 0;
3171 if ((buf.st_mode & S_IRUSR) != 0)
3172 exec_mask |= S_IXUSR;
3174 if ((buf.st_mode & S_IRGRP) != 0)
3175 exec_mask |= S_IXGRP;
3177 if ((buf.st_mode & S_IROTH) != 0)
3178 exec_mask |= S_IXOTH;
3180 result = chmod (utf8_name, buf.st_mode | exec_mask);
3182 /* Don't bother to reset executable (might need to change this
3192 * GetCurrentDirectory
3193 * @length: size of the buffer
3194 * @buffer: pointer to buffer that recieves path
3196 * Retrieves the current directory for the current process.
3198 * Return value: number of characters in buffer on success, zero on failure
3200 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3202 gunichar2 *utf16_path;
3206 if (getcwd ((char*)buffer, length) == NULL) {
3207 if (errno == ERANGE) { /*buffer length is not big enough */
3208 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*/
3211 utf16_path = mono_unicode_from_external (path, &bytes);
3212 g_free (utf16_path);
3216 _wapi_set_last_error_from_errno ();
3220 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3221 count = (bytes/2)+1;
3222 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3224 /* Add the terminator */
3225 memset (buffer, '\0', bytes+2);
3226 memcpy (buffer, utf16_path, bytes);
3228 g_free (utf16_path);
3234 * SetCurrentDirectory
3235 * @path: path to new directory
3237 * Changes the directory path for the current process.
3239 * Return value: %TRUE on success, %FALSE on failure.
3241 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3247 SetLastError (ERROR_INVALID_PARAMETER);
3251 utf8_path = mono_unicode_to_external (path);
3252 if (_wapi_chdir (utf8_path) != 0) {
3253 _wapi_set_last_error_from_errno ();
3263 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3264 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3266 struct _WapiHandle_file pipe_read_handle = {0};
3267 struct _WapiHandle_file pipe_write_handle = {0};
3268 gpointer read_handle;
3269 gpointer write_handle;
3273 mono_once (&io_ops_once, io_ops_init);
3275 DEBUG ("%s: Creating pipe", __func__);
3279 DEBUG ("%s: Error creating pipe: %s", __func__,
3282 _wapi_set_last_error_from_errno ();
3286 if (filedes[0] >= _wapi_fd_reserve ||
3287 filedes[1] >= _wapi_fd_reserve) {
3288 DEBUG ("%s: File descriptor is too big", __func__);
3290 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3298 /* filedes[0] is open for reading, filedes[1] for writing */
3300 pipe_read_handle.fd = filedes [0];
3301 pipe_read_handle.fileaccess = GENERIC_READ;
3302 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3304 if (read_handle == _WAPI_HANDLE_INVALID) {
3305 g_warning ("%s: error creating pipe read handle", __func__);
3308 SetLastError (ERROR_GEN_FAILURE);
3313 pipe_write_handle.fd = filedes [1];
3314 pipe_write_handle.fileaccess = GENERIC_WRITE;
3315 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3316 &pipe_write_handle);
3317 if (write_handle == _WAPI_HANDLE_INVALID) {
3318 g_warning ("%s: error creating pipe write handle", __func__);
3319 _wapi_handle_unref (read_handle);
3323 SetLastError (ERROR_GEN_FAILURE);
3328 *readpipe = read_handle;
3329 *writepipe = write_handle;
3331 DEBUG ("%s: Returning pipe: read handle %p, write handle %p",
3332 __func__, read_handle, write_handle);
3337 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3339 gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3340 gunichar2 *tmpdir16=NULL;
3345 if(tmpdir[strlen (tmpdir)]!='/') {
3347 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3350 tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3351 if(tmpdir16==NULL) {
3358 DEBUG ("%s: Size %d smaller than needed (%ld)",
3359 __func__, len, dirlen+1);
3363 /* Add the terminator */
3364 memset (buf, '\0', bytes+2);
3365 memcpy (buf, tmpdir16, bytes);
3371 if(tmpdir16!=NULL) {
3379 #ifdef HAVE_GETFSSTAT
3380 /* Darwin has getfsstat */
3381 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3383 struct statfs *stats;
3386 glong length, total = 0;
3388 n = getfsstat (NULL, 0, MNT_NOWAIT);
3391 size = n * sizeof (struct statfs);
3392 stats = (struct statfs *) g_malloc (size);
3395 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3399 for (i = 0; i < n; i++){
3400 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3401 if (total + length < len){
3402 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3403 buf [total+length] = 0;
3406 total += length + 1;
3415 /* In-place octal sequence replacement */
3417 unescape_octal (gchar *str)
3426 while (*rptr != '\0') {
3427 if (*rptr == '\\') {
3430 c = (*(rptr++) - '0') << 6;
3431 c += (*(rptr++) - '0') << 3;
3432 c += *(rptr++) - '0';
3434 } else if (wptr != rptr) {
3442 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3445 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3446 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3447 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3452 guint32 buffer_index;
3453 guint32 mountpoint_index;
3454 guint32 field_number;
3455 guint32 allocated_size;
3456 guint32 fsname_index;
3457 guint32 fstype_index;
3458 gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3459 gchar *mountpoint_allocated;
3460 gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3461 gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3462 gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3465 gboolean check_mount_source;
3466 } LinuxMountInfoParseState;
3468 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3469 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3470 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3471 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3473 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3477 LinuxMountInfoParseState state;
3478 gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3480 memset (buf, 0, len * sizeof (gunichar2));
3481 fd = open ("/proc/self/mountinfo", O_RDONLY);
3483 parser = GetLogicalDriveStrings_MountInfo;
3485 fd = open ("/proc/mounts", O_RDONLY);
3487 parser = GetLogicalDriveStrings_Mounts;
3491 ret = GetLogicalDriveStrings_Mtab (len, buf);
3495 memset (&state, 0, sizeof (LinuxMountInfoParseState));
3496 state.field_number = 1;
3497 state.delimiter = ' ';
3499 while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3500 state.buffer_index = 0;
3502 while ((*parser)(len, buf, &state)) {
3503 if (state.buffer [state.buffer_index] == '\n') {
3504 gboolean quit = add_drive_string (len, buf, &state);
3505 state.field_number = 1;
3506 state.buffer_index++;
3507 if (state.mountpoint_allocated) {
3508 g_free (state.mountpoint_allocated);
3509 state.mountpoint_allocated = NULL;
3526 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3530 if (state->field_number == 1)
3531 state->check_mount_source = TRUE;
3533 while (state->buffer_index < (guint32)state->nbytes) {
3534 if (state->buffer [state->buffer_index] == state->delimiter) {
3535 state->field_number++;
3536 switch (state->field_number) {
3538 state->mountpoint_index = 0;
3542 if (state->mountpoint_allocated)
3543 state->mountpoint_allocated [state->mountpoint_index] = 0;
3545 state->mountpoint [state->mountpoint_index] = 0;
3549 ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3551 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3553 state->buffer_index = state->nbytes;
3556 state->buffer_index++;
3558 } else if (state->buffer [state->buffer_index] == '\n')
3561 switch (state->field_number) {
3563 if (state->check_mount_source) {
3564 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3565 /* We can ignore the rest, it's a device
3567 state->check_mount_source = FALSE;
3568 state->fsname [state->fsname_index++] = '/';
3571 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3572 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3577 append_to_mountpoint (state);
3581 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3582 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3586 state->buffer_index++;
3592 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3594 while (state->buffer_index < (guint32)state->nbytes) {
3595 if (state->buffer [state->buffer_index] == state->delimiter) {
3596 state->field_number++;
3597 switch (state->field_number) {
3599 state->mountpoint_index = 0;
3603 if (state->mountpoint_allocated)
3604 state->mountpoint_allocated [state->mountpoint_index] = 0;
3606 state->mountpoint [state->mountpoint_index] = 0;
3610 state->delimiter = '-';
3614 state->delimiter = ' ';
3618 state->check_mount_source = TRUE;
3621 state->buffer_index++;
3623 } else if (state->buffer [state->buffer_index] == '\n')
3626 switch (state->field_number) {
3628 append_to_mountpoint (state);
3632 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3633 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3637 if (state->check_mount_source) {
3638 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3639 /* We can ignore the rest, it's a device
3641 state->check_mount_source = FALSE;
3642 state->fsname [state->fsname_index++] = '/';
3645 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3646 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3651 state->buffer_index++;
3658 append_to_mountpoint (LinuxMountInfoParseState *state)
3660 gchar ch = state->buffer [state->buffer_index];
3661 if (state->mountpoint_allocated) {
3662 if (state->mountpoint_index >= state->allocated_size) {
3663 guint32 newsize = (state->allocated_size << 1) + 1;
3664 gchar *newbuf = g_malloc0 (newsize * sizeof (gchar));
3666 memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3667 g_free (state->mountpoint_allocated);
3668 state->mountpoint_allocated = newbuf;
3669 state->allocated_size = newsize;
3671 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3673 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3674 state->allocated_size = (state->mountpoint_index << 1) + 1;
3675 state->mountpoint_allocated = g_malloc0 (state->allocated_size * sizeof (gchar));
3676 memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3677 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3679 state->mountpoint [state->mountpoint_index++] = ch;
3684 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3686 gboolean quit = FALSE;
3687 gboolean ignore_entry;
3689 if (state->fsname_index == 1 && state->fsname [0] == '/')
3690 ignore_entry = FALSE;
3691 else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0)
3692 ignore_entry = TRUE;
3693 else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3694 /* Ignore GNOME's gvfs */
3695 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3696 ignore_entry = TRUE;
3698 ignore_entry = FALSE;
3700 ignore_entry = TRUE;
3702 if (!ignore_entry) {
3705 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3707 unescape_octal (mountpoint);
3708 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3709 if (state->total + length + 1 > len) {
3711 state->total = len * 2;
3714 memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3715 state->total += length;
3719 state->fsname_index = 0;
3720 state->fstype_index = 0;
3726 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3728 return GetLogicalDriveStrings_Mtab (len, buf);
3732 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3735 gunichar2 *ptr, *dir;
3736 glong length, total = 0;
3740 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3745 /* Sigh, mntent and friends don't work well.
3746 * It stops on the first line that doesn't begin with a '/'.
3747 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3748 fp = fopen ("/etc/mtab", "rt");
3750 fp = fopen ("/etc/mnttab", "rt");
3756 while (fgets (buffer, 512, fp) != NULL) {
3760 splitted = g_strsplit (buffer, " ", 0);
3761 if (!*splitted || !*(splitted + 1)) {
3762 g_strfreev (splitted);
3766 unescape_octal (*(splitted + 1));
3767 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3768 g_strfreev (splitted);
3769 if (total + length + 1 > len) {
3772 return len * 2; /* guess */
3775 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3777 total += length + 1;
3782 /* Commented out, does not work with my mtab!!! - Gonz */
3783 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3787 gunichar2 *ptr, *dir;
3788 glong len, total = 0;
3791 fp = setmntent ("/etc/mtab", "rt");
3793 fp = setmntent ("/etc/mnttab", "rt");
3799 while ((mnt = getmntent (fp)) != NULL) {
3800 g_print ("GOT %s\n", mnt->mnt_dir);
3801 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3802 if (total + len + 1 > len) {
3803 return len * 2; /* guess */
3806 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3818 #if (defined(HAVE_STATVFS) || defined(HAVE_STATFS)) && !defined(PLATFORM_ANDROID)
3819 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3820 WapiULargeInteger *total_number_of_bytes,
3821 WapiULargeInteger *total_number_of_free_bytes)
3824 struct statvfs fsstat;
3825 #elif defined(HAVE_STATFS)
3826 struct statfs fsstat;
3828 gboolean isreadonly;
3829 gchar *utf8_path_name;
3831 unsigned long block_size;
3833 if (path_name == NULL) {
3834 utf8_path_name = g_strdup (g_get_current_dir());
3835 if (utf8_path_name == NULL) {
3836 SetLastError (ERROR_DIRECTORY);
3841 utf8_path_name = mono_unicode_to_external (path_name);
3842 if (utf8_path_name == NULL) {
3843 DEBUG("%s: unicode conversion returned NULL", __func__);
3845 SetLastError (ERROR_INVALID_NAME);
3852 ret = statvfs (utf8_path_name, &fsstat);
3853 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
3854 block_size = fsstat.f_frsize;
3855 #elif defined(HAVE_STATFS)
3856 ret = statfs (utf8_path_name, &fsstat);
3857 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
3858 block_size = fsstat.f_bsize;
3860 } while(ret == -1 && errno == EINTR);
3862 g_free(utf8_path_name);
3865 _wapi_set_last_error_from_errno ();
3866 DEBUG ("%s: statvfs failed: %s", __func__, strerror (errno));
3870 /* total number of free bytes for non-root */
3871 if (free_bytes_avail != NULL) {
3873 free_bytes_avail->QuadPart = 0;
3876 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
3880 /* total number of bytes available for non-root */
3881 if (total_number_of_bytes != NULL) {
3882 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
3885 /* total number of bytes available for root */
3886 if (total_number_of_free_bytes != NULL) {
3888 total_number_of_free_bytes->QuadPart = 0;
3891 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
3898 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3899 WapiULargeInteger *total_number_of_bytes,
3900 WapiULargeInteger *total_number_of_free_bytes)
3902 if (free_bytes_avail != NULL) {
3903 free_bytes_avail->QuadPart = (guint64) -1;
3906 if (total_number_of_bytes != NULL) {
3907 total_number_of_bytes->QuadPart = (guint64) -1;
3910 if (total_number_of_free_bytes != NULL) {
3911 total_number_of_free_bytes->QuadPart = (guint64) -1;
3919 * General Unix support
3924 const long fstypeid;
3926 const gchar* fstype;
3929 static _wapi_drive_type _wapi_drive_types[] = {
3931 { DRIVE_REMOTE, "afp" },
3932 { DRIVE_REMOTE, "autofs" },
3933 { DRIVE_CDROM, "cddafs" },
3934 { DRIVE_CDROM, "cd9660" },
3935 { DRIVE_RAMDISK, "devfs" },
3936 { DRIVE_FIXED, "exfat" },
3937 { DRIVE_RAMDISK, "fdesc" },
3938 { DRIVE_REMOTE, "ftp" },
3939 { DRIVE_FIXED, "hfs" },
3940 { DRIVE_FIXED, "msdos" },
3941 { DRIVE_REMOTE, "nfs" },
3942 { DRIVE_FIXED, "ntfs" },
3943 { DRIVE_REMOTE, "smbfs" },
3944 { DRIVE_FIXED, "udf" },
3945 { DRIVE_REMOTE, "webdav" },
3946 { DRIVE_UNKNOWN, NULL }
3948 { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
3949 { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
3950 { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
3951 { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
3952 { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
3953 { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
3954 { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
3955 { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
3956 { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
3957 { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
3958 { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
3959 { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
3960 { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
3961 { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
3962 { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
3963 { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
3964 { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
3965 { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
3966 { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
3967 { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
3968 { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
3969 { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
3970 { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
3971 { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
3972 { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
3973 { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
3974 { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
3975 { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
3976 { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
3977 { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
3978 { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
3979 { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
3980 { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
3981 { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
3982 { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
3983 { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
3984 { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
3985 { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
3986 { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
3987 { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
3988 { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
3989 { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
3990 { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
3991 { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
3992 { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
3993 { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
3994 { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
3995 { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
3996 { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
3997 { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
3998 { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
3999 { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4000 { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4001 { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4002 { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4003 { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4004 { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4005 { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4006 { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4007 { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4008 { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4009 { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4010 { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4011 { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4012 { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4013 { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4014 { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4015 { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4016 { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4017 { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4018 { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4019 { DRIVE_UNKNOWN, 0, NULL}
4021 { DRIVE_RAMDISK, "ramfs" },
4022 { DRIVE_RAMDISK, "tmpfs" },
4023 { DRIVE_RAMDISK, "proc" },
4024 { DRIVE_RAMDISK, "sysfs" },
4025 { DRIVE_RAMDISK, "debugfs" },
4026 { DRIVE_RAMDISK, "devpts" },
4027 { DRIVE_RAMDISK, "securityfs" },
4028 { DRIVE_CDROM, "iso9660" },
4029 { DRIVE_FIXED, "ext2" },
4030 { DRIVE_FIXED, "ext3" },
4031 { DRIVE_FIXED, "ext4" },
4032 { DRIVE_FIXED, "sysv" },
4033 { DRIVE_FIXED, "reiserfs" },
4034 { DRIVE_FIXED, "ufs" },
4035 { DRIVE_FIXED, "vfat" },
4036 { DRIVE_FIXED, "msdos" },
4037 { DRIVE_FIXED, "udf" },
4038 { DRIVE_FIXED, "hfs" },
4039 { DRIVE_FIXED, "hpfs" },
4040 { DRIVE_FIXED, "qnx4" },
4041 { DRIVE_FIXED, "ntfs" },
4042 { DRIVE_FIXED, "ntfs-3g" },
4043 { DRIVE_REMOTE, "smbfs" },
4044 { DRIVE_REMOTE, "fuse" },
4045 { DRIVE_REMOTE, "nfs" },
4046 { DRIVE_REMOTE, "nfs4" },
4047 { DRIVE_REMOTE, "cifs" },
4048 { DRIVE_REMOTE, "ncpfs" },
4049 { DRIVE_REMOTE, "coda" },
4050 { DRIVE_REMOTE, "afs" },
4051 { DRIVE_UNKNOWN, NULL }
4056 static guint32 _wapi_get_drive_type(long f_type)
4058 _wapi_drive_type *current;
4060 current = &_wapi_drive_types[0];
4061 while (current->drive_type != DRIVE_UNKNOWN) {
4062 if (current->fstypeid == f_type)
4063 return current->drive_type;
4067 return DRIVE_UNKNOWN;
4070 static guint32 _wapi_get_drive_type(const gchar* fstype)
4072 _wapi_drive_type *current;
4074 current = &_wapi_drive_types[0];
4075 while (current->drive_type != DRIVE_UNKNOWN) {
4076 if (strcmp (current->fstype, fstype) == 0)
4082 return current->drive_type;
4086 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4088 GetDriveTypeFromPath (const char *utf8_root_path_name)
4092 if (statfs (utf8_root_path_name, &buf) == -1)
4093 return DRIVE_UNKNOWN;
4095 return _wapi_get_drive_type (buf.f_fstypename);
4097 return _wapi_get_drive_type (buf.f_type);
4102 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4109 fp = fopen ("/etc/mtab", "rt");
4111 fp = fopen ("/etc/mnttab", "rt");
4113 return(DRIVE_UNKNOWN);
4116 drive_type = DRIVE_NO_ROOT_DIR;
4117 while (fgets (buffer, 512, fp) != NULL) {
4118 splitted = g_strsplit (buffer, " ", 0);
4119 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4120 g_strfreev (splitted);
4124 /* compare given root_path_name with the one from mtab,
4125 if length of utf8_root_path_name is zero it must be the root dir */
4126 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4127 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4128 drive_type = _wapi_get_drive_type (*(splitted + 2));
4129 /* it is possible this path might be mounted again with
4130 a known type...keep looking */
4131 if (drive_type != DRIVE_UNKNOWN) {
4132 g_strfreev (splitted);
4137 g_strfreev (splitted);
4145 guint32 GetDriveType(const gunichar2 *root_path_name)
4147 gchar *utf8_root_path_name;
4150 if (root_path_name == NULL) {
4151 utf8_root_path_name = g_strdup (g_get_current_dir());
4152 if (utf8_root_path_name == NULL) {
4153 return(DRIVE_NO_ROOT_DIR);
4157 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4158 if (utf8_root_path_name == NULL) {
4159 DEBUG("%s: unicode conversion returned NULL", __func__);
4160 return(DRIVE_NO_ROOT_DIR);
4163 /* strip trailing slash for compare below */
4164 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4165 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4168 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4169 g_free (utf8_root_path_name);
4171 return (drive_type);
4175 get_fstypename (gchar *utfpath)
4177 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4180 _wapi_drive_type *current;
4182 if (statfs (utfpath, &stat) == -1)
4185 return g_strdup (stat.f_fstypename);
4187 current = &_wapi_drive_types[0];
4188 while (current->drive_type != DRIVE_UNKNOWN) {
4189 if (stat.f_type == current->fstypeid)
4190 return g_strdup (current->fstype);
4200 /* Linux has struct statfs which has a different layout */
4201 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__)
4203 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4207 gboolean status = FALSE;
4210 // We only support getting the file system type
4211 if (fsbuffer == NULL)
4214 utfpath = mono_unicode_to_external (path);
4215 if ((fstypename = get_fstypename (utfpath)) != NULL){
4216 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4217 if (ret != NULL && len < fsbuffersize){
4218 memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4224 g_free (fstypename);