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 gboolean ret = TRUE;
1863 DEBUG("%s: name is NULL", __func__);
1865 SetLastError (ERROR_INVALID_NAME);
1869 utf8_src = mono_unicode_to_external (name);
1870 if (utf8_src == NULL) {
1871 DEBUG ("%s: unicode conversion of source returned NULL",
1874 SetLastError (ERROR_INVALID_PARAMETER);
1878 if(dest_name==NULL) {
1879 DEBUG("%s: dest is NULL", __func__);
1882 SetLastError (ERROR_INVALID_NAME);
1886 utf8_dest = mono_unicode_to_external (dest_name);
1887 if (utf8_dest == NULL) {
1888 DEBUG ("%s: unicode conversion of dest returned NULL",
1891 SetLastError (ERROR_INVALID_PARAMETER);
1898 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
1900 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
1908 if (fstat (src_fd, &st) < 0) {
1909 _wapi_set_last_error_from_errno ();
1918 /* Before trying to open/create the dest, we need to report a 'file busy'
1919 * error if src and dest are actually the same file. We do the check here to take
1920 * advantage of the IOMAP capability */
1921 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
1922 st.st_ino == dest_st.st_ino) {
1928 SetLastError (ERROR_SHARING_VIOLATION);
1932 if (fail_if_exists) {
1933 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
1935 /* FIXME: it kinda sucks that this code path potentially scans
1936 * the directory twice due to the weird SetLastError()
1938 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
1940 /* The file does not exist, try creating it */
1941 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
1943 /* Apparently this error is set if we
1944 * overwrite the dest file
1946 SetLastError (ERROR_ALREADY_EXISTS);
1950 _wapi_set_last_error_from_errno ();
1959 if (!write_file (src_fd, dest_fd, &st, TRUE))
1971 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
1976 DEBUG ("%s: %s is NULL", __func__, arg_name);
1977 SetLastError (ERROR_INVALID_NAME);
1981 utf8_ret = mono_unicode_to_external (arg);
1982 if (utf8_ret == NULL) {
1983 DEBUG ("%s: unicode conversion of %s returned NULL",
1984 __func__, arg_name);
1985 SetLastError (ERROR_INVALID_PARAMETER);
1993 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
1994 const gunichar2 *backupFileName, guint32 replaceFlags,
1995 gpointer exclude, gpointer reserved)
1997 int result, errno_copy, backup_fd = -1,replaced_fd = -1;
1998 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
1999 struct stat stBackup;
2000 gboolean ret = FALSE;
2002 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2004 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2005 goto replace_cleanup;
2006 if (backupFileName != NULL) {
2007 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2008 goto replace_cleanup;
2011 if (utf8_backupFileName) {
2012 // Open the backup file for read so we can restore the file if an error occurs.
2013 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2014 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2017 goto replace_cleanup;
2020 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2023 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2024 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2025 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2026 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2029 if (replaced_fd == -1)
2030 goto replace_cleanup;
2032 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2035 goto replace_cleanup;
2041 g_free (utf8_replacedFileName);
2042 g_free (utf8_replacementFileName);
2043 g_free (utf8_backupFileName);
2044 if (backup_fd != -1)
2046 if (replaced_fd != -1)
2047 close (replaced_fd);
2053 * @stdhandle: specifies the file descriptor
2055 * Returns a handle for stdin, stdout, or stderr. Always returns the
2056 * same handle for the same @stdhandle.
2058 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2061 static mono_mutex_t stdhandle_mutex = MONO_MUTEX_INITIALIZER;
2063 gpointer GetStdHandle(WapiStdHandle stdhandle)
2065 struct _WapiHandle_file *file_handle;
2072 case STD_INPUT_HANDLE:
2077 case STD_OUTPUT_HANDLE:
2082 case STD_ERROR_HANDLE:
2088 DEBUG("%s: unknown standard handle type", __func__);
2090 SetLastError (ERROR_INVALID_PARAMETER);
2091 return(INVALID_HANDLE_VALUE);
2094 handle = GINT_TO_POINTER (fd);
2096 pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2097 (void *)&stdhandle_mutex);
2098 thr_ret = mono_mutex_lock (&stdhandle_mutex);
2099 g_assert (thr_ret == 0);
2101 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2102 (gpointer *)&file_handle);
2104 /* Need to create this console handle */
2105 handle = _wapi_stdhandle_create (fd, name);
2107 if (handle == INVALID_HANDLE_VALUE) {
2108 SetLastError (ERROR_NO_MORE_FILES);
2112 /* Add a reference to this handle */
2113 _wapi_handle_ref (handle);
2117 thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2118 g_assert (thr_ret == 0);
2119 pthread_cleanup_pop (0);
2126 * @handle: The file handle to read from. The handle must have
2127 * %GENERIC_READ access.
2128 * @buffer: The buffer to store read data in
2129 * @numbytes: The maximum number of bytes to read
2130 * @bytesread: The actual number of bytes read is stored here. This
2131 * value can be zero if the handle is positioned at the end of the
2133 * @overlapped: points to a required %WapiOverlapped structure if
2134 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2137 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2138 * function reads up to @numbytes bytes from the file from the current
2139 * file position, and stores them in @buffer. If there are not enough
2140 * bytes left in the file, just the amount available will be read.
2141 * The actual number of bytes read is stored in @bytesread.
2143 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2144 * file position is ignored and the read position is taken from data
2145 * in the @overlapped structure.
2147 * Return value: %TRUE if the read succeeds (even if no bytes were
2148 * read due to an attempt to read past the end of the file), %FALSE on
2151 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2152 guint32 *bytesread, WapiOverlapped *overlapped)
2154 WapiHandleType type;
2156 type = _wapi_handle_type (handle);
2158 if(io_ops[type].readfile==NULL) {
2159 SetLastError (ERROR_INVALID_HANDLE);
2163 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2169 * @handle: The file handle to write to. The handle must have
2170 * %GENERIC_WRITE access.
2171 * @buffer: The buffer to read data from.
2172 * @numbytes: The maximum number of bytes to write.
2173 * @byteswritten: The actual number of bytes written is stored here.
2174 * If the handle is positioned at the file end, the length of the file
2175 * is extended. This parameter may be %NULL.
2176 * @overlapped: points to a required %WapiOverlapped structure if
2177 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2180 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2181 * function writes up to @numbytes bytes from @buffer to the file at
2182 * the current file position. If @handle is positioned at the end of
2183 * the file, the file is extended. The actual number of bytes written
2184 * is stored in @byteswritten.
2186 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2187 * file position is ignored and the write position is taken from data
2188 * in the @overlapped structure.
2190 * Return value: %TRUE if the write succeeds, %FALSE on error.
2192 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2193 guint32 *byteswritten, WapiOverlapped *overlapped)
2195 WapiHandleType type;
2197 type = _wapi_handle_type (handle);
2199 if(io_ops[type].writefile==NULL) {
2200 SetLastError (ERROR_INVALID_HANDLE);
2204 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2210 * @handle: Handle to open file. The handle must have
2211 * %GENERIC_WRITE access.
2213 * Flushes buffers of the file and causes all unwritten data to
2216 * Return value: %TRUE on success, %FALSE otherwise.
2218 gboolean FlushFileBuffers(gpointer handle)
2220 WapiHandleType type;
2222 type = _wapi_handle_type (handle);
2224 if(io_ops[type].flushfile==NULL) {
2225 SetLastError (ERROR_INVALID_HANDLE);
2229 return(io_ops[type].flushfile (handle));
2234 * @handle: The file handle to set. The handle must have
2235 * %GENERIC_WRITE access.
2237 * Moves the end-of-file position to the current position of the file
2238 * pointer. This function is used to truncate or extend a file.
2240 * Return value: %TRUE on success, %FALSE otherwise.
2242 gboolean SetEndOfFile(gpointer handle)
2244 WapiHandleType type;
2246 type = _wapi_handle_type (handle);
2248 if (io_ops[type].setendoffile == NULL) {
2249 SetLastError (ERROR_INVALID_HANDLE);
2253 return(io_ops[type].setendoffile (handle));
2258 * @handle: The file handle to set. The handle must have
2259 * %GENERIC_READ or %GENERIC_WRITE access.
2260 * @movedistance: Low 32 bits of a signed value that specifies the
2261 * number of bytes to move the file pointer.
2262 * @highmovedistance: Pointer to the high 32 bits of a signed value
2263 * that specifies the number of bytes to move the file pointer, or
2265 * @method: The starting point for the file pointer move.
2267 * Sets the file pointer of an open file.
2269 * The distance to move the file pointer is calculated from
2270 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2271 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2272 * is the low 32 bits and @highmovedistance a pointer to the high 32
2273 * bits of a 64 bit signed value. A positive distance moves the file
2274 * pointer forward from the position specified by @method; a negative
2275 * distance moves the file pointer backward.
2277 * If the library is compiled without large file support,
2278 * @highmovedistance is ignored and its value is set to zero on a
2279 * successful return.
2281 * Return value: On success, the low 32 bits of the new file pointer.
2282 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2283 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2285 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2286 gint32 *highmovedistance, WapiSeekMethod method)
2288 WapiHandleType type;
2290 type = _wapi_handle_type (handle);
2292 if (io_ops[type].seek == NULL) {
2293 SetLastError (ERROR_INVALID_HANDLE);
2294 return(INVALID_SET_FILE_POINTER);
2297 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2303 * @handle: The file handle to test.
2305 * Finds the type of file @handle.
2307 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2308 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2309 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2310 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2312 WapiFileType GetFileType(gpointer handle)
2314 WapiHandleType type;
2316 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2317 SetLastError (ERROR_INVALID_HANDLE);
2318 return(FILE_TYPE_UNKNOWN);
2321 type = _wapi_handle_type (handle);
2323 if (io_ops[type].getfiletype == NULL) {
2324 SetLastError (ERROR_INVALID_HANDLE);
2325 return(FILE_TYPE_UNKNOWN);
2328 return(io_ops[type].getfiletype ());
2333 * @handle: The file handle to query. The handle must have
2334 * %GENERIC_READ or %GENERIC_WRITE access.
2335 * @highsize: If non-%NULL, the high 32 bits of the file size are
2338 * Retrieves the size of the file @handle.
2340 * If the library is compiled without large file support, @highsize
2341 * has its value set to zero on a successful return.
2343 * Return value: On success, the low 32 bits of the file size. If
2344 * @highsize is non-%NULL then the high 32 bits of the file size are
2345 * stored here. On failure %INVALID_FILE_SIZE is returned.
2347 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2349 WapiHandleType type;
2351 type = _wapi_handle_type (handle);
2353 if (io_ops[type].getfilesize == NULL) {
2354 SetLastError (ERROR_INVALID_HANDLE);
2355 return(INVALID_FILE_SIZE);
2358 return(io_ops[type].getfilesize (handle, highsize));
2363 * @handle: The file handle to query. The handle must have
2364 * %GENERIC_READ access.
2365 * @create_time: Points to a %WapiFileTime structure to receive the
2366 * number of ticks since the epoch that file was created. May be
2368 * @last_access: Points to a %WapiFileTime structure to receive the
2369 * number of ticks since the epoch when file was last accessed. May be
2371 * @last_write: Points to a %WapiFileTime structure to receive the
2372 * number of ticks since the epoch when file was last written to. May
2375 * Finds the number of ticks since the epoch that the file referenced
2376 * by @handle was created, last accessed and last modified. A tick is
2377 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2380 * Create time isn't recorded on POSIX file systems or reported by
2381 * stat(2), so that time is guessed by returning the oldest of the
2384 * Return value: %TRUE on success, %FALSE otherwise.
2386 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2387 WapiFileTime *last_access, WapiFileTime *last_write)
2389 WapiHandleType type;
2391 type = _wapi_handle_type (handle);
2393 if (io_ops[type].getfiletime == NULL) {
2394 SetLastError (ERROR_INVALID_HANDLE);
2398 return(io_ops[type].getfiletime (handle, create_time, last_access,
2404 * @handle: The file handle to set. The handle must have
2405 * %GENERIC_WRITE access.
2406 * @create_time: Points to a %WapiFileTime structure that contains the
2407 * number of ticks since the epoch that the file was created. May be
2409 * @last_access: Points to a %WapiFileTime structure that contains the
2410 * number of ticks since the epoch when the file was last accessed.
2412 * @last_write: Points to a %WapiFileTime structure that contains the
2413 * number of ticks since the epoch when the file was last written to.
2416 * Sets the number of ticks since the epoch that the file referenced
2417 * by @handle was created, last accessed or last modified. A tick is
2418 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2421 * Create time isn't recorded on POSIX file systems, and is ignored.
2423 * Return value: %TRUE on success, %FALSE otherwise.
2425 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2426 const WapiFileTime *last_access,
2427 const WapiFileTime *last_write)
2429 WapiHandleType type;
2431 type = _wapi_handle_type (handle);
2433 if (io_ops[type].setfiletime == NULL) {
2434 SetLastError (ERROR_INVALID_HANDLE);
2438 return(io_ops[type].setfiletime (handle, create_time, last_access,
2442 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2443 * January 1 1601 GMT
2446 #define TICKS_PER_MILLISECOND 10000L
2447 #define TICKS_PER_SECOND 10000000L
2448 #define TICKS_PER_MINUTE 600000000L
2449 #define TICKS_PER_HOUR 36000000000LL
2450 #define TICKS_PER_DAY 864000000000LL
2452 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2454 static const guint16 mon_yday[2][13]={
2455 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2456 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2460 * FileTimeToSystemTime:
2461 * @file_time: Points to a %WapiFileTime structure that contains the
2462 * number of ticks to convert.
2463 * @system_time: Points to a %WapiSystemTime structure to receive the
2466 * Converts a tick count into broken-out time values.
2468 * Return value: %TRUE on success, %FALSE otherwise.
2470 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2471 WapiSystemTime *system_time)
2473 gint64 file_ticks, totaldays, rem, y;
2476 if(system_time==NULL) {
2477 DEBUG("%s: system_time NULL", __func__);
2479 SetLastError (ERROR_INVALID_PARAMETER);
2483 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2484 file_time->dwLowDateTime;
2486 /* Really compares if file_ticks>=0x8000000000000000
2487 * (LLONG_MAX+1) but we're working with a signed value for the
2488 * year and day calculation to work later
2491 DEBUG("%s: file_time too big", __func__);
2493 SetLastError (ERROR_INVALID_PARAMETER);
2497 totaldays=(file_ticks / TICKS_PER_DAY);
2498 rem = file_ticks % TICKS_PER_DAY;
2499 DEBUG("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2501 system_time->wHour=rem/TICKS_PER_HOUR;
2502 rem %= TICKS_PER_HOUR;
2503 DEBUG("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2505 system_time->wMinute = rem / TICKS_PER_MINUTE;
2506 rem %= TICKS_PER_MINUTE;
2507 DEBUG("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2510 system_time->wSecond = rem / TICKS_PER_SECOND;
2511 rem %= TICKS_PER_SECOND;
2512 DEBUG("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2515 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2516 DEBUG("%s: Milliseconds: %d", __func__,
2517 system_time->wMilliseconds);
2519 /* January 1, 1601 was a Monday, according to Emacs calendar */
2520 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2521 DEBUG("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2523 /* This algorithm to find year and month given days from epoch
2528 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2529 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2531 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2532 /* Guess a corrected year, assuming 365 days per year */
2533 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2534 DEBUG("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2537 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2538 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2540 /* Adjust days and y to match the guessed year. */
2541 totaldays -= ((yg - y) * 365
2542 + LEAPS_THRU_END_OF (yg - 1)
2543 - LEAPS_THRU_END_OF (y - 1));
2544 DEBUG("%s: totaldays: %lld", __func__, totaldays);
2546 DEBUG("%s: y: %lld", __func__, y);
2549 system_time->wYear = y;
2550 DEBUG("%s: Year: %d", __func__, system_time->wYear);
2552 ip = mon_yday[isleap(y)];
2554 for(y=11; totaldays < ip[y]; --y) {
2558 DEBUG("%s: totaldays: %lld", __func__, totaldays);
2560 system_time->wMonth = y + 1;
2561 DEBUG("%s: Month: %d", __func__, system_time->wMonth);
2563 system_time->wDay = totaldays + 1;
2564 DEBUG("%s: Day: %d", __func__, system_time->wDay);
2569 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2571 struct _WapiHandle_find find_handle = {0};
2573 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2576 if (pattern == NULL) {
2577 DEBUG ("%s: pattern is NULL", __func__);
2579 SetLastError (ERROR_PATH_NOT_FOUND);
2580 return(INVALID_HANDLE_VALUE);
2583 utf8_pattern = mono_unicode_to_external (pattern);
2584 if (utf8_pattern == NULL) {
2585 DEBUG ("%s: unicode conversion returned NULL", __func__);
2587 SetLastError (ERROR_INVALID_NAME);
2588 return(INVALID_HANDLE_VALUE);
2591 DEBUG ("%s: looking for [%s]", __func__, utf8_pattern);
2593 /* Figure out which bit of the pattern is the directory */
2594 dir_part = _wapi_dirname (utf8_pattern);
2595 entry_part = _wapi_basename (utf8_pattern);
2598 /* Don't do this check for now, it breaks if directories
2599 * really do have metachars in their names (see bug 58116).
2600 * FIXME: Figure out a better solution to keep some checks...
2602 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2603 SetLastError (ERROR_INVALID_NAME);
2605 g_free (entry_part);
2606 g_free (utf8_pattern);
2607 return(INVALID_HANDLE_VALUE);
2611 /* The pattern can specify a directory or a set of files.
2613 * The pattern can have wildcard characters ? and *, but only
2614 * in the section after the last directory delimiter. (Return
2615 * ERROR_INVALID_NAME if there are wildcards in earlier path
2616 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2617 * means "match one character", "??" seems to mean "match one
2618 * or two characters", "???" seems to mean "match one, two or
2619 * three characters", etc. Windows will also try and match
2620 * the mangled "short name" of files, so 8 character patterns
2621 * with wildcards will show some surprising results.
2623 * All the written documentation I can find says that '?'
2624 * should only match one character, and doesn't mention '??',
2625 * '???' etc. I'm going to assume that the strict behaviour
2626 * (ie '???' means three and only three characters) is the
2627 * correct one, because that lets me use fnmatch(3) rather
2628 * than mess around with regexes.
2631 find_handle.namelist = NULL;
2632 result = _wapi_io_scandir (dir_part, entry_part,
2633 &find_handle.namelist);
2636 /* No files, which windows seems to call
2639 SetLastError (ERROR_FILE_NOT_FOUND);
2640 g_free (utf8_pattern);
2641 g_free (entry_part);
2643 return (INVALID_HANDLE_VALUE);
2647 #ifdef DEBUG_ENABLED
2648 gint errnum = errno;
2650 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2651 DEBUG ("%s: scandir error: %s", __func__,
2652 g_strerror (errnum));
2653 g_free (utf8_pattern);
2654 g_free (entry_part);
2656 return (INVALID_HANDLE_VALUE);
2659 g_free (utf8_pattern);
2660 g_free (entry_part);
2662 DEBUG ("%s: Got %d matches", __func__, result);
2664 find_handle.dir_part = dir_part;
2665 find_handle.num = result;
2666 find_handle.count = 0;
2668 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2669 if (handle == _WAPI_HANDLE_INVALID) {
2670 g_warning ("%s: error creating find handle", __func__);
2672 g_free (entry_part);
2673 g_free (utf8_pattern);
2674 SetLastError (ERROR_GEN_FAILURE);
2676 return(INVALID_HANDLE_VALUE);
2679 if (handle != INVALID_HANDLE_VALUE &&
2680 !FindNextFile (handle, find_data)) {
2682 SetLastError (ERROR_NO_MORE_FILES);
2683 handle = INVALID_HANDLE_VALUE;
2689 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2691 struct _WapiHandle_find *find_handle;
2693 struct stat buf, linkbuf;
2696 gchar *utf8_filename, *utf8_basename;
2697 gunichar2 *utf16_basename;
2701 gboolean ret = FALSE;
2703 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2704 (gpointer *)&find_handle);
2706 g_warning ("%s: error looking up find handle %p", __func__,
2708 SetLastError (ERROR_INVALID_HANDLE);
2712 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2714 thr_ret = _wapi_handle_lock_handle (handle);
2715 g_assert (thr_ret == 0);
2718 if (find_handle->count >= find_handle->num) {
2719 SetLastError (ERROR_NO_MORE_FILES);
2723 /* stat next match */
2725 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2727 result = _wapi_stat (filename, &buf);
2728 if (result == -1 && errno == ENOENT) {
2729 /* Might be a dangling symlink */
2730 result = _wapi_lstat (filename, &buf);
2734 DEBUG ("%s: stat failed: %s", __func__, filename);
2740 result = _wapi_lstat (filename, &linkbuf);
2742 DEBUG ("%s: lstat failed: %s", __func__, filename);
2748 utf8_filename = mono_utf8_from_external (filename);
2749 if (utf8_filename == NULL) {
2750 /* We couldn't turn this filename into utf8 (eg the
2751 * encoding of the name wasn't convertible), so just
2754 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2761 DEBUG ("%s: Found [%s]", __func__, utf8_filename);
2763 /* fill data block */
2765 if (buf.st_mtime < buf.st_ctime)
2766 create_time = buf.st_mtime;
2768 create_time = buf.st_ctime;
2770 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2772 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2773 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2774 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2776 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2777 find_data->nFileSizeHigh = 0;
2778 find_data->nFileSizeLow = 0;
2780 find_data->nFileSizeHigh = buf.st_size >> 32;
2781 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2784 find_data->dwReserved0 = 0;
2785 find_data->dwReserved1 = 0;
2787 utf8_basename = _wapi_basename (utf8_filename);
2788 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2790 if(utf16_basename==NULL) {
2791 g_free (utf8_basename);
2792 g_free (utf8_filename);
2797 /* utf16 is 2 * utf8 */
2800 memset (find_data->cFileName, '\0', (MAX_PATH*2));
2802 /* Truncating a utf16 string like this might leave the last
2805 memcpy (find_data->cFileName, utf16_basename,
2806 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
2808 find_data->cAlternateFileName [0] = 0; /* not used */
2810 g_free (utf8_basename);
2811 g_free (utf8_filename);
2812 g_free (utf16_basename);
2815 thr_ret = _wapi_handle_unlock_handle (handle);
2816 g_assert (thr_ret == 0);
2817 pthread_cleanup_pop (0);
2824 * @wapi_handle: the find handle to close.
2826 * Closes find handle @wapi_handle
2828 * Return value: %TRUE on success, %FALSE otherwise.
2830 gboolean FindClose (gpointer handle)
2832 struct _WapiHandle_find *find_handle;
2836 if (handle == NULL) {
2837 SetLastError (ERROR_INVALID_HANDLE);
2841 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2842 (gpointer *)&find_handle);
2844 g_warning ("%s: error looking up find handle %p", __func__,
2846 SetLastError (ERROR_INVALID_HANDLE);
2850 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2852 thr_ret = _wapi_handle_lock_handle (handle);
2853 g_assert (thr_ret == 0);
2855 g_strfreev (find_handle->namelist);
2856 g_free (find_handle->dir_part);
2858 thr_ret = _wapi_handle_unlock_handle (handle);
2859 g_assert (thr_ret == 0);
2860 pthread_cleanup_pop (0);
2862 _wapi_handle_unref (handle);
2869 * @name: a pointer to a NULL-terminated unicode string, that names
2870 * the directory to be created.
2871 * @security: ignored for now
2873 * Creates directory @name
2875 * Return value: %TRUE on success, %FALSE otherwise.
2877 gboolean CreateDirectory (const gunichar2 *name,
2878 WapiSecurityAttributes *security)
2884 DEBUG("%s: name is NULL", __func__);
2886 SetLastError (ERROR_INVALID_NAME);
2890 utf8_name = mono_unicode_to_external (name);
2891 if (utf8_name == NULL) {
2892 DEBUG ("%s: unicode conversion returned NULL", __func__);
2894 SetLastError (ERROR_INVALID_NAME);
2898 result = _wapi_mkdir (utf8_name, 0777);
2905 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2912 * @name: a pointer to a NULL-terminated unicode string, that names
2913 * the directory to be removed.
2915 * Removes directory @name
2917 * Return value: %TRUE on success, %FALSE otherwise.
2919 gboolean RemoveDirectory (const gunichar2 *name)
2925 DEBUG("%s: name is NULL", __func__);
2927 SetLastError (ERROR_INVALID_NAME);
2931 utf8_name = mono_unicode_to_external (name);
2932 if (utf8_name == NULL) {
2933 DEBUG ("%s: unicode conversion returned NULL", __func__);
2935 SetLastError (ERROR_INVALID_NAME);
2939 result = _wapi_rmdir (utf8_name);
2941 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2952 * GetFileAttributes:
2953 * @name: a pointer to a NULL-terminated unicode filename.
2955 * Gets the attributes for @name;
2957 * Return value: %INVALID_FILE_ATTRIBUTES on failure
2959 guint32 GetFileAttributes (const gunichar2 *name)
2962 struct stat buf, linkbuf;
2967 DEBUG("%s: name is NULL", __func__);
2969 SetLastError (ERROR_INVALID_NAME);
2973 utf8_name = mono_unicode_to_external (name);
2974 if (utf8_name == NULL) {
2975 DEBUG ("%s: unicode conversion returned NULL", __func__);
2977 SetLastError (ERROR_INVALID_PARAMETER);
2978 return (INVALID_FILE_ATTRIBUTES);
2981 result = _wapi_stat (utf8_name, &buf);
2982 if (result == -1 && errno == ENOENT) {
2983 /* Might be a dangling symlink... */
2984 result = _wapi_lstat (utf8_name, &buf);
2988 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2990 return (INVALID_FILE_ATTRIBUTES);
2993 result = _wapi_lstat (utf8_name, &linkbuf);
2995 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2997 return (INVALID_FILE_ATTRIBUTES);
3000 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3008 * GetFileAttributesEx:
3009 * @name: a pointer to a NULL-terminated unicode filename.
3010 * @level: must be GetFileExInfoStandard
3011 * @info: pointer to a WapiFileAttributesData structure
3013 * Gets attributes, size and filetimes for @name;
3015 * Return value: %TRUE on success, %FALSE on failure
3017 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3020 WapiFileAttributesData *data;
3022 struct stat buf, linkbuf;
3026 if (level != GetFileExInfoStandard) {
3027 DEBUG ("%s: info level %d not supported.", __func__,
3030 SetLastError (ERROR_INVALID_PARAMETER);
3035 DEBUG("%s: name is NULL", __func__);
3037 SetLastError (ERROR_INVALID_NAME);
3041 utf8_name = mono_unicode_to_external (name);
3042 if (utf8_name == NULL) {
3043 DEBUG ("%s: unicode conversion returned NULL", __func__);
3045 SetLastError (ERROR_INVALID_PARAMETER);
3049 result = _wapi_stat (utf8_name, &buf);
3050 if (result == -1 && errno == ENOENT) {
3051 /* Might be a dangling symlink... */
3052 result = _wapi_lstat (utf8_name, &buf);
3056 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3061 result = _wapi_lstat (utf8_name, &linkbuf);
3063 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3068 /* fill data block */
3070 data = (WapiFileAttributesData *)info;
3072 if (buf.st_mtime < buf.st_ctime)
3073 create_time = buf.st_mtime;
3075 create_time = buf.st_ctime;
3077 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3083 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3084 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3085 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3087 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3088 data->nFileSizeHigh = 0;
3089 data->nFileSizeLow = 0;
3092 data->nFileSizeHigh = buf.st_size >> 32;
3093 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3101 * @name: name of file
3102 * @attrs: attributes to set
3104 * Changes the attributes on a named file.
3106 * Return value: %TRUE on success, %FALSE on failure.
3108 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3110 /* FIXME: think of something clever to do on unix */
3116 * Currently we only handle one *internal* case, with a value that is
3117 * not standard: 0x80000000, which means `set executable bit'
3121 DEBUG("%s: name is NULL", __func__);
3123 SetLastError (ERROR_INVALID_NAME);
3127 utf8_name = mono_unicode_to_external (name);
3128 if (utf8_name == NULL) {
3129 DEBUG ("%s: unicode conversion returned NULL", __func__);
3131 SetLastError (ERROR_INVALID_NAME);
3135 result = _wapi_stat (utf8_name, &buf);
3136 if (result == -1 && errno == ENOENT) {
3137 /* Might be a dangling symlink... */
3138 result = _wapi_lstat (utf8_name, &buf);
3142 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3147 /* Contrary to the documentation, ms allows NORMAL to be
3148 * specified along with other attributes, so dont bother to
3149 * catch that case here.
3151 if (attrs & FILE_ATTRIBUTE_READONLY) {
3152 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3154 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3157 /* Ignore the other attributes for now */
3159 if (attrs & 0x80000000){
3160 mode_t exec_mask = 0;
3162 if ((buf.st_mode & S_IRUSR) != 0)
3163 exec_mask |= S_IXUSR;
3165 if ((buf.st_mode & S_IRGRP) != 0)
3166 exec_mask |= S_IXGRP;
3168 if ((buf.st_mode & S_IROTH) != 0)
3169 exec_mask |= S_IXOTH;
3171 result = chmod (utf8_name, buf.st_mode | exec_mask);
3173 /* Don't bother to reset executable (might need to change this
3183 * GetCurrentDirectory
3184 * @length: size of the buffer
3185 * @buffer: pointer to buffer that recieves path
3187 * Retrieves the current directory for the current process.
3189 * Return value: number of characters in buffer on success, zero on failure
3191 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3193 gunichar2 *utf16_path;
3197 if (getcwd ((char*)buffer, length) == NULL) {
3198 if (errno == ERANGE) { /*buffer length is not big enough */
3199 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*/
3202 utf16_path = mono_unicode_from_external (path, &bytes);
3203 g_free (utf16_path);
3207 _wapi_set_last_error_from_errno ();
3211 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3212 count = (bytes/2)+1;
3213 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3215 /* Add the terminator */
3216 memset (buffer, '\0', bytes+2);
3217 memcpy (buffer, utf16_path, bytes);
3219 g_free (utf16_path);
3225 * SetCurrentDirectory
3226 * @path: path to new directory
3228 * Changes the directory path for the current process.
3230 * Return value: %TRUE on success, %FALSE on failure.
3232 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3238 SetLastError (ERROR_INVALID_PARAMETER);
3242 utf8_path = mono_unicode_to_external (path);
3243 if (_wapi_chdir (utf8_path) != 0) {
3244 _wapi_set_last_error_from_errno ();
3254 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3255 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3257 struct _WapiHandle_file pipe_read_handle = {0};
3258 struct _WapiHandle_file pipe_write_handle = {0};
3259 gpointer read_handle;
3260 gpointer write_handle;
3264 mono_once (&io_ops_once, io_ops_init);
3266 DEBUG ("%s: Creating pipe", __func__);
3270 DEBUG ("%s: Error creating pipe: %s", __func__,
3273 _wapi_set_last_error_from_errno ();
3277 if (filedes[0] >= _wapi_fd_reserve ||
3278 filedes[1] >= _wapi_fd_reserve) {
3279 DEBUG ("%s: File descriptor is too big", __func__);
3281 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3289 /* filedes[0] is open for reading, filedes[1] for writing */
3291 pipe_read_handle.fd = filedes [0];
3292 pipe_read_handle.fileaccess = GENERIC_READ;
3293 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3295 if (read_handle == _WAPI_HANDLE_INVALID) {
3296 g_warning ("%s: error creating pipe read handle", __func__);
3299 SetLastError (ERROR_GEN_FAILURE);
3304 pipe_write_handle.fd = filedes [1];
3305 pipe_write_handle.fileaccess = GENERIC_WRITE;
3306 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3307 &pipe_write_handle);
3308 if (write_handle == _WAPI_HANDLE_INVALID) {
3309 g_warning ("%s: error creating pipe write handle", __func__);
3310 _wapi_handle_unref (read_handle);
3314 SetLastError (ERROR_GEN_FAILURE);
3319 *readpipe = read_handle;
3320 *writepipe = write_handle;
3322 DEBUG ("%s: Returning pipe: read handle %p, write handle %p",
3323 __func__, read_handle, write_handle);
3328 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3330 gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3331 gunichar2 *tmpdir16=NULL;
3336 if(tmpdir[strlen (tmpdir)]!='/') {
3338 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3341 tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3342 if(tmpdir16==NULL) {
3349 DEBUG ("%s: Size %d smaller than needed (%ld)",
3350 __func__, len, dirlen+1);
3354 /* Add the terminator */
3355 memset (buf, '\0', bytes+2);
3356 memcpy (buf, tmpdir16, bytes);
3362 if(tmpdir16!=NULL) {
3370 #ifdef HAVE_GETFSSTAT
3371 /* Darwin has getfsstat */
3372 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3374 struct statfs *stats;
3377 glong length, total = 0;
3379 n = getfsstat (NULL, 0, MNT_NOWAIT);
3382 size = n * sizeof (struct statfs);
3383 stats = (struct statfs *) g_malloc (size);
3386 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3390 for (i = 0; i < n; i++){
3391 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3392 if (total + length < len){
3393 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3394 buf [total+length] = 0;
3397 total += length + 1;
3406 /* In-place octal sequence replacement */
3408 unescape_octal (gchar *str)
3417 while (*rptr != '\0') {
3418 if (*rptr == '\\') {
3421 c = (*(rptr++) - '0') << 6;
3422 c += (*(rptr++) - '0') << 3;
3423 c += *(rptr++) - '0';
3425 } else if (wptr != rptr) {
3433 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3436 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3437 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3438 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3443 guint32 buffer_index;
3444 guint32 mountpoint_index;
3445 guint32 field_number;
3446 guint32 allocated_size;
3447 guint32 fsname_index;
3448 guint32 fstype_index;
3449 gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3450 gchar *mountpoint_allocated;
3451 gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3452 gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3453 gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3456 gboolean check_mount_source;
3457 } LinuxMountInfoParseState;
3459 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3460 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3461 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3462 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3464 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3468 LinuxMountInfoParseState state;
3469 gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3471 memset (buf, 0, len * sizeof (gunichar2));
3472 fd = open ("/proc/self/mountinfo", O_RDONLY);
3474 parser = GetLogicalDriveStrings_MountInfo;
3476 fd = open ("/proc/mounts", O_RDONLY);
3478 parser = GetLogicalDriveStrings_Mounts;
3482 ret = GetLogicalDriveStrings_Mtab (len, buf);
3486 memset (&state, 0, sizeof (LinuxMountInfoParseState));
3487 state.field_number = 1;
3488 state.delimiter = ' ';
3490 while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3491 state.buffer_index = 0;
3493 while ((*parser)(len, buf, &state)) {
3494 if (state.buffer [state.buffer_index] == '\n') {
3495 gboolean quit = add_drive_string (len, buf, &state);
3496 state.field_number = 1;
3497 state.buffer_index++;
3498 if (state.mountpoint_allocated) {
3499 g_free (state.mountpoint_allocated);
3500 state.mountpoint_allocated = NULL;
3517 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3521 if (state->field_number == 1)
3522 state->check_mount_source = TRUE;
3524 while (state->buffer_index < (guint32)state->nbytes) {
3525 if (state->buffer [state->buffer_index] == state->delimiter) {
3526 state->field_number++;
3527 switch (state->field_number) {
3529 state->mountpoint_index = 0;
3533 if (state->mountpoint_allocated)
3534 state->mountpoint_allocated [state->mountpoint_index] = 0;
3536 state->mountpoint [state->mountpoint_index] = 0;
3540 ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3542 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3544 state->buffer_index = state->nbytes;
3547 state->buffer_index++;
3549 } else if (state->buffer [state->buffer_index] == '\n')
3552 switch (state->field_number) {
3554 if (state->check_mount_source) {
3555 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3556 /* We can ignore the rest, it's a device
3558 state->check_mount_source = FALSE;
3559 state->fsname [state->fsname_index++] = '/';
3562 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3563 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3568 append_to_mountpoint (state);
3572 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3573 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3577 state->buffer_index++;
3583 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3585 while (state->buffer_index < (guint32)state->nbytes) {
3586 if (state->buffer [state->buffer_index] == state->delimiter) {
3587 state->field_number++;
3588 switch (state->field_number) {
3590 state->mountpoint_index = 0;
3594 if (state->mountpoint_allocated)
3595 state->mountpoint_allocated [state->mountpoint_index] = 0;
3597 state->mountpoint [state->mountpoint_index] = 0;
3601 state->delimiter = '-';
3605 state->delimiter = ' ';
3609 state->check_mount_source = TRUE;
3612 state->buffer_index++;
3614 } else if (state->buffer [state->buffer_index] == '\n')
3617 switch (state->field_number) {
3619 append_to_mountpoint (state);
3623 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3624 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3628 if (state->check_mount_source) {
3629 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3630 /* We can ignore the rest, it's a device
3632 state->check_mount_source = FALSE;
3633 state->fsname [state->fsname_index++] = '/';
3636 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3637 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3642 state->buffer_index++;
3649 append_to_mountpoint (LinuxMountInfoParseState *state)
3651 gchar ch = state->buffer [state->buffer_index];
3652 if (state->mountpoint_allocated) {
3653 if (state->mountpoint_index >= state->allocated_size) {
3654 guint32 newsize = (state->allocated_size << 1) + 1;
3655 gchar *newbuf = g_malloc0 (newsize * sizeof (gchar));
3657 memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3658 g_free (state->mountpoint_allocated);
3659 state->mountpoint_allocated = newbuf;
3660 state->allocated_size = newsize;
3662 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3664 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3665 state->allocated_size = (state->mountpoint_index << 1) + 1;
3666 state->mountpoint_allocated = g_malloc0 (state->allocated_size * sizeof (gchar));
3667 memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3668 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3670 state->mountpoint [state->mountpoint_index++] = ch;
3675 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3677 gboolean quit = FALSE;
3678 gboolean ignore_entry;
3680 if (state->fsname_index == 1 && state->fsname [0] == '/')
3681 ignore_entry = FALSE;
3682 else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0)
3683 ignore_entry = TRUE;
3684 else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3685 /* Ignore GNOME's gvfs */
3686 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3687 ignore_entry = TRUE;
3689 ignore_entry = FALSE;
3691 ignore_entry = TRUE;
3693 if (!ignore_entry) {
3696 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3698 unescape_octal (mountpoint);
3699 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3700 if (state->total + length + 1 > len) {
3702 state->total = len * 2;
3705 memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3706 state->total += length;
3710 state->fsname_index = 0;
3711 state->fstype_index = 0;
3717 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3719 return GetLogicalDriveStrings_Mtab (len, buf);
3723 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3726 gunichar2 *ptr, *dir;
3727 glong length, total = 0;
3731 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3736 /* Sigh, mntent and friends don't work well.
3737 * It stops on the first line that doesn't begin with a '/'.
3738 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3739 fp = fopen ("/etc/mtab", "rt");
3741 fp = fopen ("/etc/mnttab", "rt");
3747 while (fgets (buffer, 512, fp) != NULL) {
3751 splitted = g_strsplit (buffer, " ", 0);
3752 if (!*splitted || !*(splitted + 1)) {
3753 g_strfreev (splitted);
3757 unescape_octal (*(splitted + 1));
3758 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3759 g_strfreev (splitted);
3760 if (total + length + 1 > len) {
3763 return len * 2; /* guess */
3766 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3768 total += length + 1;
3773 /* Commented out, does not work with my mtab!!! - Gonz */
3774 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3778 gunichar2 *ptr, *dir;
3779 glong len, total = 0;
3782 fp = setmntent ("/etc/mtab", "rt");
3784 fp = setmntent ("/etc/mnttab", "rt");
3790 while ((mnt = getmntent (fp)) != NULL) {
3791 g_print ("GOT %s\n", mnt->mnt_dir);
3792 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3793 if (total + len + 1 > len) {
3794 return len * 2; /* guess */
3797 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3809 #if (defined(HAVE_STATVFS) || defined(HAVE_STATFS)) && !defined(PLATFORM_ANDROID)
3810 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3811 WapiULargeInteger *total_number_of_bytes,
3812 WapiULargeInteger *total_number_of_free_bytes)
3815 struct statvfs fsstat;
3816 #elif defined(HAVE_STATFS)
3817 struct statfs fsstat;
3819 gboolean isreadonly;
3820 gchar *utf8_path_name;
3822 unsigned long block_size;
3824 if (path_name == NULL) {
3825 utf8_path_name = g_strdup (g_get_current_dir());
3826 if (utf8_path_name == NULL) {
3827 SetLastError (ERROR_DIRECTORY);
3832 utf8_path_name = mono_unicode_to_external (path_name);
3833 if (utf8_path_name == NULL) {
3834 DEBUG("%s: unicode conversion returned NULL", __func__);
3836 SetLastError (ERROR_INVALID_NAME);
3843 ret = statvfs (utf8_path_name, &fsstat);
3844 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
3845 block_size = fsstat.f_frsize;
3846 #elif defined(HAVE_STATFS)
3847 ret = statfs (utf8_path_name, &fsstat);
3848 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
3849 block_size = fsstat.f_bsize;
3851 } while(ret == -1 && errno == EINTR);
3853 g_free(utf8_path_name);
3856 _wapi_set_last_error_from_errno ();
3857 DEBUG ("%s: statvfs failed: %s", __func__, strerror (errno));
3861 /* total number of free bytes for non-root */
3862 if (free_bytes_avail != NULL) {
3864 free_bytes_avail->QuadPart = 0;
3867 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
3871 /* total number of bytes available for non-root */
3872 if (total_number_of_bytes != NULL) {
3873 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
3876 /* total number of bytes available for root */
3877 if (total_number_of_free_bytes != NULL) {
3879 total_number_of_free_bytes->QuadPart = 0;
3882 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
3889 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3890 WapiULargeInteger *total_number_of_bytes,
3891 WapiULargeInteger *total_number_of_free_bytes)
3893 if (free_bytes_avail != NULL) {
3894 free_bytes_avail->QuadPart = (guint64) -1;
3897 if (total_number_of_bytes != NULL) {
3898 total_number_of_bytes->QuadPart = (guint64) -1;
3901 if (total_number_of_free_bytes != NULL) {
3902 total_number_of_free_bytes->QuadPart = (guint64) -1;
3910 * General Unix support
3915 const long fstypeid;
3917 const gchar* fstype;
3920 static _wapi_drive_type _wapi_drive_types[] = {
3922 { DRIVE_REMOTE, "afp" },
3923 { DRIVE_REMOTE, "autofs" },
3924 { DRIVE_CDROM, "cddafs" },
3925 { DRIVE_CDROM, "cd9660" },
3926 { DRIVE_RAMDISK, "devfs" },
3927 { DRIVE_FIXED, "exfat" },
3928 { DRIVE_RAMDISK, "fdesc" },
3929 { DRIVE_REMOTE, "ftp" },
3930 { DRIVE_FIXED, "hfs" },
3931 { DRIVE_FIXED, "msdos" },
3932 { DRIVE_REMOTE, "nfs" },
3933 { DRIVE_FIXED, "ntfs" },
3934 { DRIVE_REMOTE, "smbfs" },
3935 { DRIVE_FIXED, "udf" },
3936 { DRIVE_REMOTE, "webdav" },
3937 { DRIVE_UNKNOWN, NULL }
3939 { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
3940 { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
3941 { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
3942 { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
3943 { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
3944 { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
3945 { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
3946 { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
3947 { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
3948 { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
3949 { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
3950 { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
3951 { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
3952 { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
3953 { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
3954 { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
3955 { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
3956 { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
3957 { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
3958 { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
3959 { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
3960 { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
3961 { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
3962 { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
3963 { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
3964 { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
3965 { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
3966 { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
3967 { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
3968 { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
3969 { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
3970 { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
3971 { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
3972 { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
3973 { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
3974 { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
3975 { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
3976 { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
3977 { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
3978 { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
3979 { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
3980 { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
3981 { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
3982 { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
3983 { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
3984 { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
3985 { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
3986 { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
3987 { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
3988 { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
3989 { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
3990 { DRIVE_FIXED, UFS_MAGIC, "ufs"},
3991 { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
3992 { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
3993 { DRIVE_FIXED, UFS_CIGAM, "ufs"},
3994 { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
3995 { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
3996 { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
3997 { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
3998 { DRIVE_FIXED, V9FS_MAGIC, "9p"},
3999 { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4000 { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4001 { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4002 { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4003 { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4004 { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4005 { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4006 { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4007 { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4008 { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4009 { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4010 { DRIVE_UNKNOWN, 0, NULL}
4012 { DRIVE_RAMDISK, "ramfs" },
4013 { DRIVE_RAMDISK, "tmpfs" },
4014 { DRIVE_RAMDISK, "proc" },
4015 { DRIVE_RAMDISK, "sysfs" },
4016 { DRIVE_RAMDISK, "debugfs" },
4017 { DRIVE_RAMDISK, "devpts" },
4018 { DRIVE_RAMDISK, "securityfs" },
4019 { DRIVE_CDROM, "iso9660" },
4020 { DRIVE_FIXED, "ext2" },
4021 { DRIVE_FIXED, "ext3" },
4022 { DRIVE_FIXED, "ext4" },
4023 { DRIVE_FIXED, "sysv" },
4024 { DRIVE_FIXED, "reiserfs" },
4025 { DRIVE_FIXED, "ufs" },
4026 { DRIVE_FIXED, "vfat" },
4027 { DRIVE_FIXED, "msdos" },
4028 { DRIVE_FIXED, "udf" },
4029 { DRIVE_FIXED, "hfs" },
4030 { DRIVE_FIXED, "hpfs" },
4031 { DRIVE_FIXED, "qnx4" },
4032 { DRIVE_FIXED, "ntfs" },
4033 { DRIVE_FIXED, "ntfs-3g" },
4034 { DRIVE_REMOTE, "smbfs" },
4035 { DRIVE_REMOTE, "fuse" },
4036 { DRIVE_REMOTE, "nfs" },
4037 { DRIVE_REMOTE, "nfs4" },
4038 { DRIVE_REMOTE, "cifs" },
4039 { DRIVE_REMOTE, "ncpfs" },
4040 { DRIVE_REMOTE, "coda" },
4041 { DRIVE_REMOTE, "afs" },
4042 { DRIVE_UNKNOWN, NULL }
4047 static guint32 _wapi_get_drive_type(long f_type)
4049 _wapi_drive_type *current;
4051 current = &_wapi_drive_types[0];
4052 while (current->drive_type != DRIVE_UNKNOWN) {
4053 if (current->fstypeid == f_type)
4054 return current->drive_type;
4058 return DRIVE_UNKNOWN;
4061 static guint32 _wapi_get_drive_type(const gchar* fstype)
4063 _wapi_drive_type *current;
4065 current = &_wapi_drive_types[0];
4066 while (current->drive_type != DRIVE_UNKNOWN) {
4067 if (strcmp (current->fstype, fstype) == 0)
4073 return current->drive_type;
4077 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4079 GetDriveTypeFromPath (const char *utf8_root_path_name)
4083 if (statfs (utf8_root_path_name, &buf) == -1)
4084 return DRIVE_UNKNOWN;
4086 return _wapi_get_drive_type (buf.f_fstypename);
4088 return _wapi_get_drive_type (buf.f_type);
4093 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4100 fp = fopen ("/etc/mtab", "rt");
4102 fp = fopen ("/etc/mnttab", "rt");
4104 return(DRIVE_UNKNOWN);
4107 drive_type = DRIVE_NO_ROOT_DIR;
4108 while (fgets (buffer, 512, fp) != NULL) {
4109 splitted = g_strsplit (buffer, " ", 0);
4110 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4111 g_strfreev (splitted);
4115 /* compare given root_path_name with the one from mtab,
4116 if length of utf8_root_path_name is zero it must be the root dir */
4117 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4118 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4119 drive_type = _wapi_get_drive_type (*(splitted + 2));
4120 g_strfreev (splitted);
4124 g_strfreev (splitted);
4132 guint32 GetDriveType(const gunichar2 *root_path_name)
4134 gchar *utf8_root_path_name;
4137 if (root_path_name == NULL) {
4138 utf8_root_path_name = g_strdup (g_get_current_dir());
4139 if (utf8_root_path_name == NULL) {
4140 return(DRIVE_NO_ROOT_DIR);
4144 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4145 if (utf8_root_path_name == NULL) {
4146 DEBUG("%s: unicode conversion returned NULL", __func__);
4147 return(DRIVE_NO_ROOT_DIR);
4150 /* strip trailing slash for compare below */
4151 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4152 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4155 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4156 g_free (utf8_root_path_name);
4158 return (drive_type);
4162 get_fstypename (gchar *utfpath)
4164 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4167 _wapi_drive_type *current;
4169 if (statfs (utfpath, &stat) == -1)
4172 return stat.f_fstypename;
4174 current = &_wapi_drive_types[0];
4175 while (current->drive_type != DRIVE_UNKNOWN) {
4176 if (stat.f_type == current->fstypeid)
4177 return current->fstype;
4187 /* Linux has struct statfs which has a different layout */
4188 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__)
4190 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4193 const gchar *fstypename;
4194 gboolean status = FALSE;
4197 // We only support getting the file system type
4198 if (fsbuffer == NULL)
4201 utfpath = mono_unicode_to_external (path);
4202 if ((fstypename = get_fstypename (utfpath)) != NULL){
4203 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4204 if (ret != NULL && len < fsbuffersize){
4205 memcpy (fsbuffer, ret, len * sizeof (gunichar2));