2 * io.c: File, console and find handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002 Ximian, Inc.
8 * Copyright (c) 2002-2006 Novell, Inc.
18 #ifdef HAVE_SYS_STATVFS_H
19 #include <sys/statvfs.h>
20 #elif defined(HAVE_SYS_STATFS_H)
21 #include <sys/statfs.h>
22 #elif defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H)
23 #include <sys/param.h>
24 #include <sys/mount.h>
26 #include <sys/types.h>
32 #include <mono/io-layer/wapi.h>
33 #include <mono/io-layer/wapi-private.h>
34 #include <mono/io-layer/handles-private.h>
35 #include <mono/io-layer/io-private.h>
36 #include <mono/io-layer/timefuncs-private.h>
37 #include <mono/io-layer/thread-private.h>
38 #include <mono/io-layer/io-portability.h>
39 #include <mono/utils/strenc.h>
43 static void file_close (gpointer handle, gpointer data);
44 static WapiFileType file_getfiletype(void);
45 static gboolean file_read(gpointer handle, gpointer buffer,
46 guint32 numbytes, guint32 *bytesread,
47 WapiOverlapped *overlapped);
48 static gboolean file_write(gpointer handle, gconstpointer buffer,
49 guint32 numbytes, guint32 *byteswritten,
50 WapiOverlapped *overlapped);
51 static gboolean file_flush(gpointer handle);
52 static guint32 file_seek(gpointer handle, gint32 movedistance,
53 gint32 *highmovedistance, WapiSeekMethod method);
54 static gboolean file_setendoffile(gpointer handle);
55 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
56 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
57 WapiFileTime *last_access,
58 WapiFileTime *last_write);
59 static gboolean file_setfiletime(gpointer handle,
60 const WapiFileTime *create_time,
61 const WapiFileTime *last_access,
62 const WapiFileTime *last_write);
64 /* File handle is only signalled for overlapped IO */
65 struct _WapiHandleOps _wapi_file_ops = {
66 file_close, /* close */
70 NULL, /* special_wait */
74 void _wapi_file_details (gpointer handle_info)
76 struct _WapiHandle_file *file = (struct _WapiHandle_file *)handle_info;
78 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
80 file->fileaccess&GENERIC_READ?'R':'.',
81 file->fileaccess&GENERIC_WRITE?'W':'.',
82 file->fileaccess&GENERIC_EXECUTE?'X':'.',
83 file->sharemode&FILE_SHARE_READ?'R':'.',
84 file->sharemode&FILE_SHARE_WRITE?'W':'.',
85 file->sharemode&FILE_SHARE_DELETE?'D':'.',
89 static void console_close (gpointer handle, gpointer data);
90 static WapiFileType console_getfiletype(void);
91 static gboolean console_read(gpointer handle, gpointer buffer,
92 guint32 numbytes, guint32 *bytesread,
93 WapiOverlapped *overlapped);
94 static gboolean console_write(gpointer handle, gconstpointer buffer,
95 guint32 numbytes, guint32 *byteswritten,
96 WapiOverlapped *overlapped);
98 /* Console is mostly the same as file, except it can block waiting for
101 struct _WapiHandleOps _wapi_console_ops = {
102 console_close, /* close */
106 NULL, /* special_wait */
110 void _wapi_console_details (gpointer handle_info)
112 _wapi_file_details (handle_info);
115 /* Find handle has no ops.
117 struct _WapiHandleOps _wapi_find_ops = {
122 NULL, /* special_wait */
126 static void pipe_close (gpointer handle, gpointer data);
127 static WapiFileType pipe_getfiletype (void);
128 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
129 guint32 *bytesread, WapiOverlapped *overlapped);
130 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
131 guint32 numbytes, guint32 *byteswritten,
132 WapiOverlapped *overlapped);
136 struct _WapiHandleOps _wapi_pipe_ops = {
137 pipe_close, /* close */
141 NULL, /* special_wait */
145 void _wapi_pipe_details (gpointer handle_info)
147 _wapi_file_details (handle_info);
150 static const struct {
151 /* File, console and pipe handles */
152 WapiFileType (*getfiletype)(void);
154 /* File, console and pipe handles */
155 gboolean (*readfile)(gpointer handle, gpointer buffer,
156 guint32 numbytes, guint32 *bytesread,
157 WapiOverlapped *overlapped);
158 gboolean (*writefile)(gpointer handle, gconstpointer buffer,
159 guint32 numbytes, guint32 *byteswritten,
160 WapiOverlapped *overlapped);
161 gboolean (*flushfile)(gpointer handle);
164 guint32 (*seek)(gpointer handle, gint32 movedistance,
165 gint32 *highmovedistance, WapiSeekMethod method);
166 gboolean (*setendoffile)(gpointer handle);
167 guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
168 gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
169 WapiFileTime *last_access,
170 WapiFileTime *last_write);
171 gboolean (*setfiletime)(gpointer handle,
172 const WapiFileTime *create_time,
173 const WapiFileTime *last_access,
174 const WapiFileTime *last_write);
175 } io_ops[WAPI_HANDLE_COUNT]={
176 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
179 file_read, file_write,
180 file_flush, file_seek,
186 {console_getfiletype,
189 NULL, NULL, NULL, NULL, NULL, NULL},
191 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
193 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
195 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
197 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
198 /* socket (will need at least read and write) */
199 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
201 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
203 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
208 NULL, NULL, NULL, NULL, NULL, NULL},
211 static mono_once_t io_ops_once=MONO_ONCE_INIT;
212 static gboolean lock_while_writing = FALSE;
214 static void io_ops_init (void)
216 /* _wapi_handle_register_capabilities (WAPI_HANDLE_FILE, */
217 /* WAPI_HANDLE_CAP_WAIT); */
218 /* _wapi_handle_register_capabilities (WAPI_HANDLE_CONSOLE, */
219 /* WAPI_HANDLE_CAP_WAIT); */
221 if (g_getenv ("MONO_STRICT_IO_EMULATION") != NULL) {
222 lock_while_writing = TRUE;
226 /* Some utility functions.
229 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
236 /* FIXME: this could definitely be better, but there seems to
237 * be no pattern to the attributes that are set
240 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
241 if (S_ISSOCK (buf->st_mode))
242 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
244 filename = _wapi_basename (pathname);
246 if (S_ISDIR (buf->st_mode)) {
247 attrs = FILE_ATTRIBUTE_DIRECTORY;
248 if (!(buf->st_mode & S_IWUSR)) {
249 attrs |= FILE_ATTRIBUTE_READONLY;
251 if (filename[0] == '.') {
252 attrs |= FILE_ATTRIBUTE_HIDDEN;
255 if (!(buf->st_mode & S_IWUSR)) {
256 attrs = FILE_ATTRIBUTE_READONLY;
258 if (filename[0] == '.') {
259 attrs |= FILE_ATTRIBUTE_HIDDEN;
261 } else if (filename[0] == '.') {
262 attrs = FILE_ATTRIBUTE_HIDDEN;
264 attrs = FILE_ATTRIBUTE_NORMAL;
269 if (S_ISLNK (lbuf->st_mode)) {
270 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
280 _wapi_set_last_error_from_errno (void)
282 SetLastError (_wapi_get_win32_file_error (errno));
285 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
288 if (errno == ENOENT) {
289 /* Check the path - if it's a missing directory then
290 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
296 dirname = _wapi_dirname (path);
298 dirname = g_strdup (dir);
301 if (_wapi_access (dirname, F_OK) == 0) {
302 SetLastError (ERROR_FILE_NOT_FOUND);
304 SetLastError (ERROR_PATH_NOT_FOUND);
309 _wapi_set_last_error_from_errno ();
315 static void file_close (gpointer handle, gpointer data)
317 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
320 g_message("%s: closing file handle %p [%s]", __func__, handle,
321 file_handle->filename);
324 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
325 _wapi_unlink (file_handle->filename);
327 g_free (file_handle->filename);
329 _wapi_handle_share_release (file_handle->share_info);
331 close (GPOINTER_TO_UINT(handle));
334 static WapiFileType file_getfiletype(void)
336 return(FILE_TYPE_DISK);
339 static gboolean file_read(gpointer handle, gpointer buffer,
340 guint32 numbytes, guint32 *bytesread,
341 WapiOverlapped *overlapped)
343 struct _WapiHandle_file *file_handle;
345 int fd = GPOINTER_TO_UINT(handle);
348 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
349 (gpointer *)&file_handle);
351 g_warning ("%s: error looking up file handle %p", __func__,
353 SetLastError (ERROR_INVALID_HANDLE);
357 if(bytesread!=NULL) {
361 if(!(file_handle->fileaccess & GENERIC_READ) &&
362 !(file_handle->fileaccess & GENERIC_ALL)) {
364 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
365 __func__, handle, file_handle->fileaccess);
368 SetLastError (ERROR_ACCESS_DENIED);
373 ret = read (fd, buffer, numbytes);
374 } while (ret == -1 && errno == EINTR &&
375 !_wapi_thread_cur_apc_pending());
381 g_message("%s: read of handle %p error: %s", __func__,
382 handle, strerror(err));
384 SetLastError (_wapi_get_win32_file_error (err));
388 if (bytesread != NULL) {
395 static gboolean file_write(gpointer handle, gconstpointer buffer,
396 guint32 numbytes, guint32 *byteswritten,
397 WapiOverlapped *overlapped G_GNUC_UNUSED)
399 struct _WapiHandle_file *file_handle;
402 off_t current_pos = 0;
403 int fd = GPOINTER_TO_UINT(handle);
405 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
406 (gpointer *)&file_handle);
408 g_warning ("%s: error looking up file handle %p", __func__,
410 SetLastError (ERROR_INVALID_HANDLE);
414 if(byteswritten!=NULL) {
418 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
419 !(file_handle->fileaccess & GENERIC_ALL)) {
421 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
424 SetLastError (ERROR_ACCESS_DENIED);
428 if (lock_while_writing) {
429 /* Need to lock the region we're about to write to,
430 * because we only do advisory locking on POSIX
433 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
434 if (current_pos == -1) {
436 g_message ("%s: handle %p lseek failed: %s", __func__,
437 handle, strerror (errno));
439 _wapi_set_last_error_from_errno ();
443 if (_wapi_lock_file_region (fd, current_pos,
444 numbytes) == FALSE) {
445 /* The error has already been set */
451 ret = write (fd, buffer, numbytes);
452 } while (ret == -1 && errno == EINTR &&
453 !_wapi_thread_cur_apc_pending());
455 if (lock_while_writing) {
456 _wapi_unlock_file_region (fd, current_pos, numbytes);
460 if (errno == EINTR) {
463 _wapi_set_last_error_from_errno ();
466 g_message("%s: write of handle %p error: %s",
467 __func__, handle, strerror(errno));
473 if (byteswritten != NULL) {
479 static gboolean file_flush(gpointer handle)
481 struct _WapiHandle_file *file_handle;
484 int fd = GPOINTER_TO_UINT(handle);
486 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
487 (gpointer *)&file_handle);
489 g_warning ("%s: error looking up file handle %p", __func__,
491 SetLastError (ERROR_INVALID_HANDLE);
495 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
496 !(file_handle->fileaccess & GENERIC_ALL)) {
498 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
501 SetLastError (ERROR_ACCESS_DENIED);
508 g_message("%s: fsync of handle %p error: %s", __func__, handle,
512 _wapi_set_last_error_from_errno ();
519 static guint32 file_seek(gpointer handle, gint32 movedistance,
520 gint32 *highmovedistance, WapiSeekMethod method)
522 struct _WapiHandle_file *file_handle;
524 off_t offset, newpos;
527 int fd = GPOINTER_TO_UINT(handle);
529 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
530 (gpointer *)&file_handle);
532 g_warning ("%s: error looking up file handle %p", __func__,
534 SetLastError (ERROR_INVALID_HANDLE);
535 return(INVALID_SET_FILE_POINTER);
538 if(!(file_handle->fileaccess & GENERIC_READ) &&
539 !(file_handle->fileaccess & GENERIC_WRITE) &&
540 !(file_handle->fileaccess & GENERIC_ALL)) {
542 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
545 SetLastError (ERROR_ACCESS_DENIED);
546 return(INVALID_SET_FILE_POINTER);
561 g_message("%s: invalid seek type %d", __func__, method);
564 SetLastError (ERROR_INVALID_PARAMETER);
565 return(INVALID_SET_FILE_POINTER);
568 #ifdef HAVE_LARGE_FILE_SUPPORT
569 if(highmovedistance==NULL) {
572 g_message("%s: setting offset to %lld (low %d)", __func__,
573 offset, movedistance);
576 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
579 g_message("%s: setting offset to %lld 0x%llx (high %d 0x%x, low %d 0x%x)", __func__, offset, offset, *highmovedistance, *highmovedistance, movedistance, movedistance);
587 #ifdef HAVE_LARGE_FILE_SUPPORT
588 g_message("%s: moving handle %p by %lld bytes from %d", __func__,
589 handle, offset, whence);
591 g_message("%s: moving handle %p fd %d by %ld bytes from %d", __func__,
592 handle, offset, whence);
596 newpos=lseek(fd, offset, whence);
599 g_message("%s: lseek on handle %p returned error %s",
600 __func__, handle, strerror(errno));
603 _wapi_set_last_error_from_errno ();
604 return(INVALID_SET_FILE_POINTER);
608 #ifdef HAVE_LARGE_FILE_SUPPORT
609 g_message("%s: lseek returns %lld", __func__, newpos);
611 g_message ("%s: lseek returns %ld", __func__, newpos);
615 #ifdef HAVE_LARGE_FILE_SUPPORT
616 ret=newpos & 0xFFFFFFFF;
617 if(highmovedistance!=NULL) {
618 *highmovedistance=newpos>>32;
622 if(highmovedistance!=NULL) {
623 /* Accurate, but potentially dodgy :-) */
629 g_message ("%s: move of handle %p returning %d/%d", __func__,
630 handle, ret, highmovedistance==NULL?0:*highmovedistance);
636 static gboolean file_setendoffile(gpointer handle)
638 struct _WapiHandle_file *file_handle;
643 int fd = GPOINTER_TO_UINT(handle);
645 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
646 (gpointer *)&file_handle);
648 g_warning ("%s: error looking up file handle %p", __func__,
650 SetLastError (ERROR_INVALID_HANDLE);
654 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
655 !(file_handle->fileaccess & GENERIC_ALL)) {
657 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
660 SetLastError (ERROR_ACCESS_DENIED);
664 /* Find the current file position, and the file length. If
665 * the file position is greater than the length, write to
666 * extend the file with a hole. If the file position is less
667 * than the length, truncate the file.
670 ret=fstat(fd, &statbuf);
673 g_message ("%s: handle %p fstat failed: %s", __func__,
674 handle, strerror(errno));
677 _wapi_set_last_error_from_errno ();
680 size=statbuf.st_size;
682 pos=lseek(fd, (off_t)0, SEEK_CUR);
685 g_message("%s: handle %p lseek failed: %s", __func__,
686 handle, strerror(errno));
689 _wapi_set_last_error_from_errno ();
693 #ifdef FTRUNCATE_DOESNT_EXTEND
694 /* I haven't bothered to write the configure.in stuff for this
695 * because I don't know if any platform needs it. I'm leaving
696 * this code just in case though
699 /* Extend the file. Use write() here, because some
700 * manuals say that ftruncate() behaviour is undefined
701 * when the file needs extending. The POSIX spec says
702 * that on XSI-conformant systems it extends, so if
703 * every system we care about conforms, then we can
707 ret = write (fd, "", 1);
708 } while (ret == -1 && errno == EINTR &&
709 !_wapi_thread_cur_apc_pending());
713 g_message("%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
716 _wapi_set_last_error_from_errno ();
720 /* And put the file position back after the write */
721 ret = lseek (fd, pos, SEEK_SET);
724 g_message ("%s: handle %p second lseek failed: %s",
725 __func__, handle, strerror(errno));
728 _wapi_set_last_error_from_errno ();
734 /* always truncate, because the extend write() adds an extra
735 * byte to the end of the file
738 ret=ftruncate(fd, pos);
740 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
743 g_message("%s: handle %p ftruncate failed: %s", __func__,
744 handle, strerror(errno));
747 _wapi_set_last_error_from_errno ();
754 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
756 struct _WapiHandle_file *file_handle;
761 int fd = GPOINTER_TO_UINT(handle);
763 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
764 (gpointer *)&file_handle);
766 g_warning ("%s: error looking up file handle %p", __func__,
768 SetLastError (ERROR_INVALID_HANDLE);
769 return(INVALID_FILE_SIZE);
772 if(!(file_handle->fileaccess & GENERIC_READ) &&
773 !(file_handle->fileaccess & GENERIC_WRITE) &&
774 !(file_handle->fileaccess & GENERIC_ALL)) {
776 g_message("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
779 SetLastError (ERROR_ACCESS_DENIED);
780 return(INVALID_FILE_SIZE);
783 /* If the file has a size with the low bits 0xFFFFFFFF the
784 * caller can't tell if this is an error, so clear the error
787 SetLastError (ERROR_SUCCESS);
789 ret = fstat(fd, &statbuf);
792 g_message ("%s: handle %p fstat failed: %s", __func__,
793 handle, strerror(errno));
796 _wapi_set_last_error_from_errno ();
797 return(INVALID_FILE_SIZE);
800 #ifdef HAVE_LARGE_FILE_SUPPORT
801 size = statbuf.st_size & 0xFFFFFFFF;
802 if (highsize != NULL) {
803 *highsize = statbuf.st_size>>32;
806 if (highsize != NULL) {
807 /* Accurate, but potentially dodgy :-) */
810 size = statbuf.st_size;
814 g_message ("%s: Returning size %d/%d", __func__, size, *highsize);
820 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
821 WapiFileTime *last_access,
822 WapiFileTime *last_write)
824 struct _WapiHandle_file *file_handle;
827 guint64 create_ticks, access_ticks, write_ticks;
829 int fd = GPOINTER_TO_UINT(handle);
831 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
832 (gpointer *)&file_handle);
834 g_warning ("%s: error looking up file handle %p", __func__,
836 SetLastError (ERROR_INVALID_HANDLE);
840 if(!(file_handle->fileaccess & GENERIC_READ) &&
841 !(file_handle->fileaccess & GENERIC_ALL)) {
843 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
844 __func__, handle, file_handle->fileaccess);
847 SetLastError (ERROR_ACCESS_DENIED);
851 ret=fstat(fd, &statbuf);
854 g_message("%s: handle %p fstat failed: %s", __func__, handle,
858 _wapi_set_last_error_from_errno ();
863 g_message("%s: atime: %ld ctime: %ld mtime: %ld", __func__,
864 statbuf.st_atime, statbuf.st_ctime,
868 /* Try and guess a meaningful create time by using the older
871 /* The magic constant comes from msdn documentation
872 * "Converting a time_t Value to a File Time"
874 if(statbuf.st_atime < statbuf.st_ctime) {
875 create_ticks=((guint64)statbuf.st_atime*10000000)
876 + 116444736000000000ULL;
878 create_ticks=((guint64)statbuf.st_ctime*10000000)
879 + 116444736000000000ULL;
882 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
883 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
886 g_message("%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
887 access_ticks, create_ticks, write_ticks);
890 if(create_time!=NULL) {
891 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
892 create_time->dwHighDateTime = create_ticks >> 32;
895 if(last_access!=NULL) {
896 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
897 last_access->dwHighDateTime = access_ticks >> 32;
900 if(last_write!=NULL) {
901 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
902 last_write->dwHighDateTime = write_ticks >> 32;
908 static gboolean file_setfiletime(gpointer handle,
909 const WapiFileTime *create_time G_GNUC_UNUSED,
910 const WapiFileTime *last_access,
911 const WapiFileTime *last_write)
913 struct _WapiHandle_file *file_handle;
915 struct utimbuf utbuf;
917 guint64 access_ticks, write_ticks;
919 int fd = GPOINTER_TO_UINT(handle);
921 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
922 (gpointer *)&file_handle);
924 g_warning ("%s: error looking up file handle %p", __func__,
926 SetLastError (ERROR_INVALID_HANDLE);
930 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
931 !(file_handle->fileaccess & GENERIC_ALL)) {
933 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
936 SetLastError (ERROR_ACCESS_DENIED);
940 if(file_handle->filename == NULL) {
942 g_message("%s: handle %p unknown filename", __func__, handle);
945 SetLastError (ERROR_INVALID_HANDLE);
949 /* Get the current times, so we can put the same times back in
950 * the event that one of the FileTime structs is NULL
952 ret=fstat (fd, &statbuf);
955 g_message("%s: handle %p fstat failed: %s", __func__, handle,
959 SetLastError (ERROR_INVALID_PARAMETER);
963 if(last_access!=NULL) {
964 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
965 last_access->dwLowDateTime;
966 /* This is (time_t)0. We can actually go to INT_MIN,
967 * but this will do for now.
969 if (access_ticks < 116444736000000000ULL) {
971 g_message ("%s: attempt to set access time too early",
974 SetLastError (ERROR_INVALID_PARAMETER);
978 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
980 utbuf.actime=statbuf.st_atime;
983 if(last_write!=NULL) {
984 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
985 last_write->dwLowDateTime;
986 /* This is (time_t)0. We can actually go to INT_MIN,
987 * but this will do for now.
989 if (write_ticks < 116444736000000000ULL) {
991 g_message ("%s: attempt to set write time too early",
994 SetLastError (ERROR_INVALID_PARAMETER);
998 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1000 utbuf.modtime=statbuf.st_mtime;
1004 g_message ("%s: setting handle %p access %ld write %ld", __func__,
1005 handle, utbuf.actime, utbuf.modtime);
1008 ret = _wapi_utime (file_handle->filename, &utbuf);
1011 g_message ("%s: handle %p [%s] utime failed: %s", __func__,
1012 handle, file_handle->filename, strerror(errno));
1015 SetLastError (ERROR_INVALID_PARAMETER);
1022 static void console_close (gpointer handle, gpointer data)
1024 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1027 g_message("%s: closing console handle %p", __func__, handle);
1030 g_free (console_handle->filename);
1032 close (GPOINTER_TO_UINT(handle));
1035 static WapiFileType console_getfiletype(void)
1037 return(FILE_TYPE_CHAR);
1040 static gboolean console_read(gpointer handle, gpointer buffer,
1041 guint32 numbytes, guint32 *bytesread,
1042 WapiOverlapped *overlapped G_GNUC_UNUSED)
1044 struct _WapiHandle_file *console_handle;
1047 int fd = GPOINTER_TO_UINT(handle);
1049 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1050 (gpointer *)&console_handle);
1052 g_warning ("%s: error looking up console handle %p", __func__,
1054 SetLastError (ERROR_INVALID_HANDLE);
1058 if(bytesread!=NULL) {
1062 if(!(console_handle->fileaccess & GENERIC_READ) &&
1063 !(console_handle->fileaccess & GENERIC_ALL)) {
1065 g_message ("%s: handle %p doesn't have GENERIC_READ access: %u",
1066 __func__, handle, console_handle->fileaccess);
1069 SetLastError (ERROR_ACCESS_DENIED);
1074 ret=read(fd, buffer, numbytes);
1075 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1079 g_message("%s: read of handle %p error: %s", __func__, handle,
1083 _wapi_set_last_error_from_errno ();
1087 if(bytesread!=NULL) {
1094 static gboolean console_write(gpointer handle, gconstpointer buffer,
1095 guint32 numbytes, guint32 *byteswritten,
1096 WapiOverlapped *overlapped G_GNUC_UNUSED)
1098 struct _WapiHandle_file *console_handle;
1101 int fd = GPOINTER_TO_UINT(handle);
1103 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1104 (gpointer *)&console_handle);
1106 g_warning ("%s: error looking up console handle %p", __func__,
1108 SetLastError (ERROR_INVALID_HANDLE);
1112 if(byteswritten!=NULL) {
1116 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1117 !(console_handle->fileaccess & GENERIC_ALL)) {
1119 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, console_handle->fileaccess);
1122 SetLastError (ERROR_ACCESS_DENIED);
1127 ret = write(fd, buffer, numbytes);
1128 } while (ret == -1 && errno == EINTR &&
1129 !_wapi_thread_cur_apc_pending());
1132 if (errno == EINTR) {
1135 _wapi_set_last_error_from_errno ();
1138 g_message ("%s: write of handle %p error: %s",
1139 __func__, handle, strerror(errno));
1145 if(byteswritten!=NULL) {
1152 static void pipe_close (gpointer handle, gpointer data G_GNUC_UNUSED)
1155 g_message("%s: closing pipe handle %p", __func__, handle);
1158 /* No filename with pipe handles */
1160 close(GPOINTER_TO_UINT(handle));
1163 static WapiFileType pipe_getfiletype(void)
1165 return(FILE_TYPE_PIPE);
1168 static gboolean pipe_read (gpointer handle, gpointer buffer,
1169 guint32 numbytes, guint32 *bytesread,
1170 WapiOverlapped *overlapped G_GNUC_UNUSED)
1172 struct _WapiHandle_file *pipe_handle;
1175 int fd = GPOINTER_TO_UINT(handle);
1177 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1178 (gpointer *)&pipe_handle);
1180 g_warning ("%s: error looking up pipe handle %p", __func__,
1182 SetLastError (ERROR_INVALID_HANDLE);
1186 if(bytesread!=NULL) {
1190 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1191 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1193 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
1194 __func__, handle, pipe_handle->fileaccess);
1197 SetLastError (ERROR_ACCESS_DENIED);
1202 g_message ("%s: reading up to %d bytes from pipe %p", __func__,
1207 ret=read(fd, buffer, numbytes);
1208 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1211 if (errno == EINTR) {
1214 _wapi_set_last_error_from_errno ();
1217 g_message("%s: read of handle %p error: %s", __func__,
1218 handle, strerror(errno));
1226 g_message ("%s: read %d bytes from pipe", __func__, ret);
1229 if(bytesread!=NULL) {
1236 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1237 guint32 numbytes, guint32 *byteswritten,
1238 WapiOverlapped *overlapped G_GNUC_UNUSED)
1240 struct _WapiHandle_file *pipe_handle;
1243 int fd = GPOINTER_TO_UINT(handle);
1245 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1246 (gpointer *)&pipe_handle);
1248 g_warning ("%s: error looking up pipe handle %p", __func__,
1250 SetLastError (ERROR_INVALID_HANDLE);
1254 if(byteswritten!=NULL) {
1258 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1259 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1261 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, pipe_handle->fileaccess);
1264 SetLastError (ERROR_ACCESS_DENIED);
1269 g_message ("%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1274 ret = write (fd, buffer, numbytes);
1275 } while (ret == -1 && errno == EINTR &&
1276 !_wapi_thread_cur_apc_pending());
1279 if (errno == EINTR) {
1282 _wapi_set_last_error_from_errno ();
1285 g_message("%s: write of handle %p error: %s", __func__,
1286 handle, strerror(errno));
1292 if(byteswritten!=NULL) {
1299 static int convert_flags(guint32 fileaccess, guint32 createmode)
1303 switch(fileaccess) {
1310 case GENERIC_READ|GENERIC_WRITE:
1315 g_message("%s: Unknown access type 0x%x", __func__,
1321 switch(createmode) {
1323 flags|=O_CREAT|O_EXCL;
1326 flags|=O_CREAT|O_TRUNC;
1333 case TRUNCATE_EXISTING:
1338 g_message("%s: Unknown create mode 0x%x", __func__,
1347 static guint32 convert_from_flags(int flags)
1349 guint32 fileaccess=0;
1352 #define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR)
1355 if((flags & O_ACCMODE) == O_RDONLY) {
1356 fileaccess=GENERIC_READ;
1357 } else if ((flags & O_ACCMODE) == O_WRONLY) {
1358 fileaccess=GENERIC_WRITE;
1359 } else if ((flags & O_ACCMODE) == O_RDWR) {
1360 fileaccess=GENERIC_READ|GENERIC_WRITE;
1363 g_message("%s: Can't figure out flags 0x%x", __func__, flags);
1367 /* Maybe sort out create mode too */
1373 static mode_t convert_perms(guint32 sharemode)
1377 if(sharemode&FILE_SHARE_READ) {
1380 if(sharemode&FILE_SHARE_WRITE) {
1388 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1390 struct _WapiFileShare **share_info)
1392 gboolean file_already_shared;
1393 guint32 file_existing_share, file_existing_access;
1395 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);
1397 if (file_already_shared) {
1398 /* The reference to this share info was incremented
1399 * when we looked it up, so be careful to put it back
1400 * if we conclude we can't use this file.
1402 if (file_existing_share == 0) {
1403 /* Quick and easy, no possibility to share */
1405 g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
1408 _wapi_handle_share_release (*share_info);
1413 if (((file_existing_share == FILE_SHARE_READ) &&
1414 (fileaccess != GENERIC_READ)) ||
1415 ((file_existing_share == FILE_SHARE_WRITE) &&
1416 (fileaccess != GENERIC_WRITE))) {
1417 /* New access mode doesn't match up */
1419 g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
1422 _wapi_handle_share_release (*share_info);
1427 if (((file_existing_access & GENERIC_READ) &&
1428 !(sharemode & FILE_SHARE_READ)) ||
1429 ((file_existing_access & GENERIC_WRITE) &&
1430 !(sharemode & FILE_SHARE_WRITE))) {
1431 /* New share mode doesn't match up */
1433 g_message ("%s: Access mode prevents open: requested share: 0x%x, file has access: 0x%x", __func__, sharemode, file_existing_access);
1436 _wapi_handle_share_release (*share_info);
1442 g_message ("%s: New file!", __func__);
1449 static gboolean share_check (struct stat *statbuf, guint32 sharemode,
1451 struct _WapiFileShare **share_info, int fd)
1453 if (share_allows_open (statbuf, sharemode, fileaccess,
1454 share_info) == TRUE) {
1458 /* Got a share violation. Double check that the file is still
1459 * open by someone, in case a process crashed while still
1460 * holding a file handle. This will also cope with someone
1461 * using Mono.Posix to close the file. This is cheaper and
1462 * less intrusive to other processes than initiating a handle
1466 _wapi_handle_check_share (*share_info, fd);
1467 if (share_allows_open (statbuf, sharemode, fileaccess,
1468 share_info) == TRUE) {
1472 /* Still violating. It's possible that a process crashed
1473 * while still holding a file handle, and that a non-mono
1474 * process has the file open. (For example, C-c mcs while
1475 * editing a source file.) As a last resort, run a handle
1476 * collection, which will remove stale share entries.
1478 _wapi_handle_collect ();
1480 return(share_allows_open (statbuf, sharemode, fileaccess, share_info));
1485 * @name: a pointer to a NULL-terminated unicode string, that names
1486 * the file or other object to create.
1487 * @fileaccess: specifies the file access mode
1488 * @sharemode: whether the file should be shared. This parameter is
1489 * currently ignored.
1490 * @security: Ignored for now.
1491 * @createmode: specifies whether to create a new file, whether to
1492 * overwrite an existing file, whether to truncate the file, etc.
1493 * @attrs: specifies file attributes and flags. On win32 attributes
1494 * are characteristics of the file, not the handle, and are ignored
1495 * when an existing file is opened. Flags give the library hints on
1496 * how to process a file to optimise performance.
1497 * @template: the handle of an open %GENERIC_READ file that specifies
1498 * attributes to apply to a newly created file, ignoring @attrs.
1499 * Normally this parameter is NULL. This parameter is ignored when an
1500 * existing file is opened.
1502 * Creates a new file handle. This only applies to normal files:
1503 * pipes are handled by CreatePipe(), and console handles are created
1504 * with GetStdHandle().
1506 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1508 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1509 guint32 sharemode, WapiSecurityAttributes *security,
1510 guint32 createmode, guint32 attrs,
1511 gpointer template G_GNUC_UNUSED)
1513 struct _WapiHandle_file file_handle = {0};
1515 int flags=convert_flags(fileaccess, createmode);
1516 /*mode_t perms=convert_perms(sharemode);*/
1517 /* we don't use sharemode, because that relates to sharing of
1518 * the file when the file is open and is already handled by
1519 * other code, perms instead are the on-disk permissions and
1520 * this is a sane default.
1526 struct stat statbuf;
1528 mono_once (&io_ops_once, io_ops_init);
1530 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1533 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1534 SetLastError (ERROR_ENCRYPTION_FAILED);
1535 return INVALID_HANDLE_VALUE;
1540 g_message ("%s: name is NULL", __func__);
1543 SetLastError (ERROR_INVALID_NAME);
1544 return(INVALID_HANDLE_VALUE);
1547 filename = mono_unicode_to_external (name);
1548 if (filename == NULL) {
1550 g_message("%s: unicode conversion returned NULL", __func__);
1553 SetLastError (ERROR_INVALID_NAME);
1554 return(INVALID_HANDLE_VALUE);
1558 g_message ("%s: Opening %s with share 0x%x and access 0x%x", __func__,
1559 filename, sharemode, fileaccess);
1562 fd = _wapi_open (filename, flags, perms);
1564 /* If we were trying to open a directory with write permissions
1565 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1566 * EISDIR. However, this is a bit bogus because calls to
1567 * manipulate the directory (e.g. SetFileTime) will still work on
1568 * the directory because they use other API calls
1569 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1570 * to open the directory again without write permission.
1572 if (fd == -1 && errno == EISDIR)
1574 /* Try again but don't try to make it writable */
1575 fd = open(filename, flags & ~(O_RDWR|O_WRONLY), perms);
1580 g_message("%s: Error opening file %s: %s", __func__, filename,
1583 _wapi_set_last_path_error_from_errno (NULL, filename);
1586 return(INVALID_HANDLE_VALUE);
1589 if (fd >= _wapi_fd_reserve) {
1591 g_message ("%s: File descriptor is too big", __func__);
1594 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1599 return(INVALID_HANDLE_VALUE);
1602 ret = fstat (fd, &statbuf);
1605 g_message ("%s: fstat error of file %s: %s", __func__,
1606 filename, strerror (errno));
1608 _wapi_set_last_error_from_errno ();
1612 return(INVALID_HANDLE_VALUE);
1615 if (share_check (&statbuf, sharemode, fileaccess,
1616 &file_handle.share_info, fd) == FALSE) {
1617 SetLastError (ERROR_SHARING_VIOLATION);
1621 return (INVALID_HANDLE_VALUE);
1623 if (file_handle.share_info == NULL) {
1624 /* No space, so no more files can be opened */
1626 g_message ("%s: No space in the share table", __func__);
1629 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1633 return(INVALID_HANDLE_VALUE);
1636 file_handle.filename = filename;
1638 if(security!=NULL) {
1639 //file_handle->security_attributes=_wapi_handle_scratch_store (
1640 //security, sizeof(WapiSecurityAttributes));
1643 file_handle.fileaccess=fileaccess;
1644 file_handle.sharemode=sharemode;
1645 file_handle.attrs=attrs;
1647 #ifdef HAVE_POSIX_FADVISE
1648 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1649 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1650 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1651 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1655 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1657 if (S_ISFIFO (statbuf.st_mode)) {
1658 handle_type = WAPI_HANDLE_PIPE;
1659 } else if (S_ISCHR (statbuf.st_mode)) {
1660 handle_type = WAPI_HANDLE_CONSOLE;
1662 handle_type = WAPI_HANDLE_FILE;
1665 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1666 if (handle == _WAPI_HANDLE_INVALID) {
1667 g_warning ("%s: error creating file handle", __func__);
1671 SetLastError (ERROR_GEN_FAILURE);
1672 return(INVALID_HANDLE_VALUE);
1676 g_message("%s: returning handle %p", __func__, handle);
1684 * @name: a pointer to a NULL-terminated unicode string, that names
1685 * the file to be deleted.
1687 * Deletes file @name.
1689 * Return value: %TRUE on success, %FALSE otherwise.
1691 gboolean DeleteFile(const gunichar2 *name)
1695 gboolean ret = FALSE;
1698 struct stat statbuf;
1699 struct _WapiFileShare *shareinfo;
1704 g_message("%s: name is NULL", __func__);
1707 SetLastError (ERROR_INVALID_NAME);
1711 filename=mono_unicode_to_external(name);
1712 if(filename==NULL) {
1714 g_message("%s: unicode conversion returned NULL", __func__);
1717 SetLastError (ERROR_INVALID_NAME);
1721 attrs = GetFileAttributes (name);
1722 if (attrs == INVALID_FILE_ATTRIBUTES) {
1724 g_message ("%s: file attributes error", __func__);
1726 /* Error set by GetFileAttributes() */
1731 if (attrs & FILE_ATTRIBUTE_READONLY) {
1733 g_message ("%s: file %s is readonly", __func__, filename);
1735 SetLastError (ERROR_ACCESS_DENIED);
1741 /* Check to make sure sharing allows us to open the file for
1742 * writing. See bug 323389.
1744 * Do the checks that don't need an open file descriptor, for
1745 * simplicity's sake. If we really have to do the full checks
1746 * then we can implement that later.
1748 if (_wapi_stat (filename, &statbuf) < 0) {
1749 _wapi_set_last_path_error_from_errno (NULL, filename);
1754 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1755 &shareinfo) == FALSE) {
1756 SetLastError (ERROR_SHARING_VIOLATION);
1760 _wapi_handle_share_release (shareinfo);
1763 retval = _wapi_unlink (filename);
1766 _wapi_set_last_path_error_from_errno (NULL, filename);
1778 * @name: a pointer to a NULL-terminated unicode string, that names
1779 * the file to be moved.
1780 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1781 * new name for the file.
1783 * Renames file @name to @dest_name.
1784 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1785 * when it is the same file as the source. In that case it silently succeeds.
1787 * Return value: %TRUE on success, %FALSE otherwise.
1789 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1791 gchar *utf8_name, *utf8_dest_name;
1792 int result, errno_copy;
1793 struct stat stat_src, stat_dest;
1794 gboolean ret = FALSE;
1795 struct _WapiFileShare *shareinfo;
1799 g_message("%s: name is NULL", __func__);
1802 SetLastError (ERROR_INVALID_NAME);
1806 utf8_name = mono_unicode_to_external (name);
1807 if (utf8_name == NULL) {
1809 g_message ("%s: unicode conversion returned NULL", __func__);
1812 SetLastError (ERROR_INVALID_NAME);
1816 if(dest_name==NULL) {
1818 g_message("%s: name is NULL", __func__);
1822 SetLastError (ERROR_INVALID_NAME);
1826 utf8_dest_name = mono_unicode_to_external (dest_name);
1827 if (utf8_dest_name == NULL) {
1829 g_message ("%s: unicode conversion returned NULL", __func__);
1833 SetLastError (ERROR_INVALID_NAME);
1838 * In C# land we check for the existence of src, but not for dest.
1839 * We check it here and return the failure if dest exists and is not
1840 * the same file as src.
1842 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1843 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1845 g_free (utf8_dest_name);
1849 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1850 if (stat_dest.st_dev != stat_src.st_dev ||
1851 stat_dest.st_ino != stat_src.st_ino) {
1853 g_free (utf8_dest_name);
1854 SetLastError (ERROR_ALREADY_EXISTS);
1859 /* Check to make sure sharing allows us to open the file for
1860 * writing. See bug 377049.
1862 * Do the checks that don't need an open file descriptor, for
1863 * simplicity's sake. If we really have to do the full checks
1864 * then we can implement that later.
1866 if (share_allows_open (&stat_src, 0, GENERIC_WRITE,
1867 &shareinfo) == FALSE) {
1868 SetLastError (ERROR_SHARING_VIOLATION);
1871 _wapi_handle_share_release (shareinfo);
1873 result = _wapi_rename (utf8_name, utf8_dest_name);
1877 switch(errno_copy) {
1879 SetLastError (ERROR_ALREADY_EXISTS);
1883 /* Ignore here, it is dealt with below */
1887 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1892 g_free (utf8_dest_name);
1894 if (result != 0 && errno_copy == EXDEV) {
1895 if (S_ISDIR (stat_src.st_mode)) {
1896 SetLastError (ERROR_NOT_SAME_DEVICE);
1899 /* Try a copy to the new location, and delete the source */
1900 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1901 /* CopyFile will set the error */
1905 return(DeleteFile (name));
1916 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1920 int buf_size = st_src->st_blksize;
1922 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1923 buf = (char *) malloc (buf_size);
1926 remain = read (src_fd, buf, buf_size);
1928 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1932 _wapi_set_last_error_from_errno ();
1942 while (remain > 0) {
1943 if ((n = write (dest_fd, wbuf, remain)) < 0) {
1944 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1948 _wapi_set_last_error_from_errno ();
1950 g_message ("%s: write failed.", __func__);
1967 * @name: a pointer to a NULL-terminated unicode string, that names
1968 * the file to be copied.
1969 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1970 * new name for the file.
1971 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1973 * Copies file @name to @dest_name
1975 * Return value: %TRUE on success, %FALSE otherwise.
1977 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1978 gboolean fail_if_exists)
1980 gchar *utf8_src, *utf8_dest;
1981 int src_fd, dest_fd;
1983 gboolean ret = TRUE;
1987 g_message("%s: name is NULL", __func__);
1990 SetLastError (ERROR_INVALID_NAME);
1994 utf8_src = mono_unicode_to_external (name);
1995 if (utf8_src == NULL) {
1997 g_message ("%s: unicode conversion of source returned NULL",
2001 SetLastError (ERROR_INVALID_PARAMETER);
2005 if(dest_name==NULL) {
2007 g_message("%s: name is NULL", __func__);
2011 SetLastError (ERROR_INVALID_NAME);
2015 utf8_dest = mono_unicode_to_external (dest_name);
2016 if (utf8_dest == NULL) {
2018 g_message ("%s: unicode conversion of dest returned NULL",
2022 SetLastError (ERROR_INVALID_PARAMETER);
2029 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2031 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2039 if (fstat (src_fd, &st) < 0) {
2040 _wapi_set_last_error_from_errno ();
2049 if (fail_if_exists) {
2050 dest_fd = open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL,
2053 dest_fd = open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2055 /* O_TRUNC might cause a fail if the file
2058 dest_fd = open (utf8_dest, O_WRONLY | O_CREAT,
2061 /* Apparently this error is set if we
2062 * overwrite the dest file
2064 SetLastError (ERROR_ALREADY_EXISTS);
2068 _wapi_set_last_error_from_errno ();
2077 if (!write_file (src_fd, dest_fd, &st, TRUE))
2089 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2095 g_message ("%s: %s is NULL", __func__, arg_name);
2097 SetLastError (ERROR_INVALID_NAME);
2101 utf8_ret = mono_unicode_to_external (arg);
2102 if (utf8_ret == NULL) {
2104 g_message ("%s: unicode conversion of %s returned NULL",
2105 __func__, arg_name);
2107 SetLastError (ERROR_INVALID_PARAMETER);
2115 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2116 const gunichar2 *backupFileName, guint32 replaceFlags,
2117 gpointer exclude, gpointer reserved)
2119 int result, errno_copy, backup_fd = -1,replaced_fd = -1;
2120 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2121 struct stat stBackup;
2122 gboolean ret = FALSE;
2124 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2126 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2127 goto replace_cleanup;
2128 if (backupFileName != NULL) {
2129 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2130 goto replace_cleanup;
2133 if (utf8_backupFileName) {
2134 // Open the backup file for read so we can restore the file if an error occurs.
2135 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2136 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2139 goto replace_cleanup;
2142 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2145 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2146 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2147 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2148 replaced_fd = open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2150 if (replaced_fd == -1) {
2151 replaced_fd = open (utf8_backupFileName, O_WRONLY | O_CREAT,
2154 if (replaced_fd == -1)
2155 goto replace_cleanup;
2157 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2160 goto replace_cleanup;
2166 g_free (utf8_replacedFileName);
2167 g_free (utf8_replacementFileName);
2168 g_free (utf8_backupFileName);
2169 if (backup_fd != -1)
2171 if (replaced_fd != -1)
2172 close (replaced_fd);
2176 static gpointer stdhandle_create (int fd, const gchar *name)
2178 struct _WapiHandle_file file_handle = {0};
2183 g_message("%s: creating standard handle type %s, fd %d", __func__,
2187 /* Check if fd is valid */
2189 flags=fcntl(fd, F_GETFL);
2190 } while (flags == -1 && errno == EINTR);
2193 /* Invalid fd. Not really much point checking for EBADF
2197 g_message("%s: fcntl error on fd %d: %s", __func__, fd,
2201 _wapi_set_last_error_from_errno ();
2202 return(INVALID_HANDLE_VALUE);
2205 file_handle.filename = g_strdup(name);
2206 /* some default security attributes might be needed */
2207 file_handle.security_attributes=0;
2208 file_handle.fileaccess=convert_from_flags(flags);
2210 /* Apparently input handles can't be written to. (I don't
2211 * know if output or error handles can't be read from.)
2214 file_handle.fileaccess &= ~GENERIC_WRITE;
2217 file_handle.sharemode=0;
2218 file_handle.attrs=0;
2220 handle = _wapi_handle_new_fd (WAPI_HANDLE_CONSOLE, fd, &file_handle);
2221 if (handle == _WAPI_HANDLE_INVALID) {
2222 g_warning ("%s: error creating file handle", __func__);
2223 SetLastError (ERROR_GEN_FAILURE);
2224 return(INVALID_HANDLE_VALUE);
2228 g_message("%s: returning handle %p", __func__, handle);
2236 * @stdhandle: specifies the file descriptor
2238 * Returns a handle for stdin, stdout, or stderr. Always returns the
2239 * same handle for the same @stdhandle.
2241 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2244 static mono_mutex_t stdhandle_mutex = MONO_MUTEX_INITIALIZER;
2246 gpointer GetStdHandle(WapiStdHandle stdhandle)
2248 struct _WapiHandle_file *file_handle;
2255 case STD_INPUT_HANDLE:
2260 case STD_OUTPUT_HANDLE:
2265 case STD_ERROR_HANDLE:
2272 g_message("%s: unknown standard handle type", __func__);
2275 SetLastError (ERROR_INVALID_PARAMETER);
2276 return(INVALID_HANDLE_VALUE);
2279 handle = GINT_TO_POINTER (fd);
2281 pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2282 (void *)&stdhandle_mutex);
2283 thr_ret = mono_mutex_lock (&stdhandle_mutex);
2284 g_assert (thr_ret == 0);
2286 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2287 (gpointer *)&file_handle);
2289 /* Need to create this console handle */
2290 handle = stdhandle_create (fd, name);
2292 if (handle == INVALID_HANDLE_VALUE) {
2293 SetLastError (ERROR_NO_MORE_FILES);
2297 /* Add a reference to this handle */
2298 _wapi_handle_ref (handle);
2302 thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2303 g_assert (thr_ret == 0);
2304 pthread_cleanup_pop (0);
2311 * @handle: The file handle to read from. The handle must have
2312 * %GENERIC_READ access.
2313 * @buffer: The buffer to store read data in
2314 * @numbytes: The maximum number of bytes to read
2315 * @bytesread: The actual number of bytes read is stored here. This
2316 * value can be zero if the handle is positioned at the end of the
2318 * @overlapped: points to a required %WapiOverlapped structure if
2319 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2322 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2323 * function reads up to @numbytes bytes from the file from the current
2324 * file position, and stores them in @buffer. If there are not enough
2325 * bytes left in the file, just the amount available will be read.
2326 * The actual number of bytes read is stored in @bytesread.
2328 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2329 * file position is ignored and the read position is taken from data
2330 * in the @overlapped structure.
2332 * Return value: %TRUE if the read succeeds (even if no bytes were
2333 * read due to an attempt to read past the end of the file), %FALSE on
2336 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2337 guint32 *bytesread, WapiOverlapped *overlapped)
2339 WapiHandleType type;
2341 type = _wapi_handle_type (handle);
2343 if(io_ops[type].readfile==NULL) {
2344 SetLastError (ERROR_INVALID_HANDLE);
2348 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2354 * @handle: The file handle to write to. The handle must have
2355 * %GENERIC_WRITE access.
2356 * @buffer: The buffer to read data from.
2357 * @numbytes: The maximum number of bytes to write.
2358 * @byteswritten: The actual number of bytes written is stored here.
2359 * If the handle is positioned at the file end, the length of the file
2360 * is extended. This parameter may be %NULL.
2361 * @overlapped: points to a required %WapiOverlapped structure if
2362 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2365 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2366 * function writes up to @numbytes bytes from @buffer to the file at
2367 * the current file position. If @handle is positioned at the end of
2368 * the file, the file is extended. The actual number of bytes written
2369 * is stored in @byteswritten.
2371 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2372 * file position is ignored and the write position is taken from data
2373 * in the @overlapped structure.
2375 * Return value: %TRUE if the write succeeds, %FALSE on error.
2377 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2378 guint32 *byteswritten, WapiOverlapped *overlapped)
2380 WapiHandleType type;
2382 type = _wapi_handle_type (handle);
2384 if(io_ops[type].writefile==NULL) {
2385 SetLastError (ERROR_INVALID_HANDLE);
2389 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2395 * @handle: Handle to open file. The handle must have
2396 * %GENERIC_WRITE access.
2398 * Flushes buffers of the file and causes all unwritten data to
2401 * Return value: %TRUE on success, %FALSE otherwise.
2403 gboolean FlushFileBuffers(gpointer handle)
2405 WapiHandleType type;
2407 type = _wapi_handle_type (handle);
2409 if(io_ops[type].flushfile==NULL) {
2410 SetLastError (ERROR_INVALID_HANDLE);
2414 return(io_ops[type].flushfile (handle));
2419 * @handle: The file handle to set. The handle must have
2420 * %GENERIC_WRITE access.
2422 * Moves the end-of-file position to the current position of the file
2423 * pointer. This function is used to truncate or extend a file.
2425 * Return value: %TRUE on success, %FALSE otherwise.
2427 gboolean SetEndOfFile(gpointer handle)
2429 WapiHandleType type;
2431 type = _wapi_handle_type (handle);
2433 if (io_ops[type].setendoffile == NULL) {
2434 SetLastError (ERROR_INVALID_HANDLE);
2438 return(io_ops[type].setendoffile (handle));
2443 * @handle: The file handle to set. The handle must have
2444 * %GENERIC_READ or %GENERIC_WRITE access.
2445 * @movedistance: Low 32 bits of a signed value that specifies the
2446 * number of bytes to move the file pointer.
2447 * @highmovedistance: Pointer to the high 32 bits of a signed value
2448 * that specifies the number of bytes to move the file pointer, or
2450 * @method: The starting point for the file pointer move.
2452 * Sets the file pointer of an open file.
2454 * The distance to move the file pointer is calculated from
2455 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2456 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2457 * is the low 32 bits and @highmovedistance a pointer to the high 32
2458 * bits of a 64 bit signed value. A positive distance moves the file
2459 * pointer forward from the position specified by @method; a negative
2460 * distance moves the file pointer backward.
2462 * If the library is compiled without large file support,
2463 * @highmovedistance is ignored and its value is set to zero on a
2464 * successful return.
2466 * Return value: On success, the low 32 bits of the new file pointer.
2467 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2468 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2470 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2471 gint32 *highmovedistance, WapiSeekMethod method)
2473 WapiHandleType type;
2475 type = _wapi_handle_type (handle);
2477 if (io_ops[type].seek == NULL) {
2478 SetLastError (ERROR_INVALID_HANDLE);
2479 return(INVALID_SET_FILE_POINTER);
2482 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2488 * @handle: The file handle to test.
2490 * Finds the type of file @handle.
2492 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2493 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2494 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2495 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2497 WapiFileType GetFileType(gpointer handle)
2499 WapiHandleType type;
2501 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2502 SetLastError (ERROR_INVALID_HANDLE);
2503 return(FILE_TYPE_UNKNOWN);
2506 type = _wapi_handle_type (handle);
2508 if (io_ops[type].getfiletype == NULL) {
2509 SetLastError (ERROR_INVALID_HANDLE);
2510 return(FILE_TYPE_UNKNOWN);
2513 return(io_ops[type].getfiletype ());
2518 * @handle: The file handle to query. The handle must have
2519 * %GENERIC_READ or %GENERIC_WRITE access.
2520 * @highsize: If non-%NULL, the high 32 bits of the file size are
2523 * Retrieves the size of the file @handle.
2525 * If the library is compiled without large file support, @highsize
2526 * has its value set to zero on a successful return.
2528 * Return value: On success, the low 32 bits of the file size. If
2529 * @highsize is non-%NULL then the high 32 bits of the file size are
2530 * stored here. On failure %INVALID_FILE_SIZE is returned.
2532 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2534 WapiHandleType type;
2536 type = _wapi_handle_type (handle);
2538 if (io_ops[type].getfilesize == NULL) {
2539 SetLastError (ERROR_INVALID_HANDLE);
2540 return(INVALID_FILE_SIZE);
2543 return(io_ops[type].getfilesize (handle, highsize));
2548 * @handle: The file handle to query. The handle must have
2549 * %GENERIC_READ access.
2550 * @create_time: Points to a %WapiFileTime structure to receive the
2551 * number of ticks since the epoch that file was created. May be
2553 * @last_access: Points to a %WapiFileTime structure to receive the
2554 * number of ticks since the epoch when file was last accessed. May be
2556 * @last_write: Points to a %WapiFileTime structure to receive the
2557 * number of ticks since the epoch when file was last written to. May
2560 * Finds the number of ticks since the epoch that the file referenced
2561 * by @handle was created, last accessed and last modified. A tick is
2562 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2565 * Create time isn't recorded on POSIX file systems or reported by
2566 * stat(2), so that time is guessed by returning the oldest of the
2569 * Return value: %TRUE on success, %FALSE otherwise.
2571 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2572 WapiFileTime *last_access, WapiFileTime *last_write)
2574 WapiHandleType type;
2576 type = _wapi_handle_type (handle);
2578 if (io_ops[type].getfiletime == NULL) {
2579 SetLastError (ERROR_INVALID_HANDLE);
2583 return(io_ops[type].getfiletime (handle, create_time, last_access,
2589 * @handle: The file handle to set. The handle must have
2590 * %GENERIC_WRITE access.
2591 * @create_time: Points to a %WapiFileTime structure that contains the
2592 * number of ticks since the epoch that the file was created. May be
2594 * @last_access: Points to a %WapiFileTime structure that contains the
2595 * number of ticks since the epoch when the file was last accessed.
2597 * @last_write: Points to a %WapiFileTime structure that contains the
2598 * number of ticks since the epoch when the file was last written to.
2601 * Sets the number of ticks since the epoch that the file referenced
2602 * by @handle was created, last accessed or last modified. A tick is
2603 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2606 * Create time isn't recorded on POSIX file systems, and is ignored.
2608 * Return value: %TRUE on success, %FALSE otherwise.
2610 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2611 const WapiFileTime *last_access,
2612 const WapiFileTime *last_write)
2614 WapiHandleType type;
2616 type = _wapi_handle_type (handle);
2618 if (io_ops[type].setfiletime == NULL) {
2619 SetLastError (ERROR_INVALID_HANDLE);
2623 return(io_ops[type].setfiletime (handle, create_time, last_access,
2627 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2628 * January 1 1601 GMT
2631 #define TICKS_PER_MILLISECOND 10000L
2632 #define TICKS_PER_SECOND 10000000L
2633 #define TICKS_PER_MINUTE 600000000L
2634 #define TICKS_PER_HOUR 36000000000LL
2635 #define TICKS_PER_DAY 864000000000LL
2637 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2639 static const guint16 mon_yday[2][13]={
2640 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2641 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2645 * FileTimeToSystemTime:
2646 * @file_time: Points to a %WapiFileTime structure that contains the
2647 * number of ticks to convert.
2648 * @system_time: Points to a %WapiSystemTime structure to receive the
2651 * Converts a tick count into broken-out time values.
2653 * Return value: %TRUE on success, %FALSE otherwise.
2655 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2656 WapiSystemTime *system_time)
2658 gint64 file_ticks, totaldays, rem, y;
2661 if(system_time==NULL) {
2663 g_message("%s: system_time NULL", __func__);
2666 SetLastError (ERROR_INVALID_PARAMETER);
2670 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2671 file_time->dwLowDateTime;
2673 /* Really compares if file_ticks>=0x8000000000000000
2674 * (LLONG_MAX+1) but we're working with a signed value for the
2675 * year and day calculation to work later
2679 g_message("%s: file_time too big", __func__);
2682 SetLastError (ERROR_INVALID_PARAMETER);
2686 totaldays=(file_ticks / TICKS_PER_DAY);
2687 rem = file_ticks % TICKS_PER_DAY;
2689 g_message("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2692 system_time->wHour=rem/TICKS_PER_HOUR;
2693 rem %= TICKS_PER_HOUR;
2695 g_message("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2698 system_time->wMinute = rem / TICKS_PER_MINUTE;
2699 rem %= TICKS_PER_MINUTE;
2701 g_message("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2705 system_time->wSecond = rem / TICKS_PER_SECOND;
2706 rem %= TICKS_PER_SECOND;
2708 g_message("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2712 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2714 g_message("%s: Milliseconds: %d", __func__,
2715 system_time->wMilliseconds);
2718 /* January 1, 1601 was a Monday, according to Emacs calendar */
2719 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2721 g_message("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2724 /* This algorithm to find year and month given days from epoch
2729 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2730 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2732 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2733 /* Guess a corrected year, assuming 365 days per year */
2734 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2736 g_message("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2739 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2740 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2743 /* Adjust days and y to match the guessed year. */
2744 totaldays -= ((yg - y) * 365
2745 + LEAPS_THRU_END_OF (yg - 1)
2746 - LEAPS_THRU_END_OF (y - 1));
2748 g_message("%s: totaldays: %lld", __func__, totaldays);
2752 g_message("%s: y: %lld", __func__, y);
2756 system_time->wYear = y;
2758 g_message("%s: Year: %d", __func__, system_time->wYear);
2761 ip = mon_yday[isleap(y)];
2763 for(y=11; totaldays < ip[y]; --y) {
2768 g_message("%s: totaldays: %lld", __func__, totaldays);
2771 system_time->wMonth = y + 1;
2773 g_message("%s: Month: %d", __func__, system_time->wMonth);
2776 system_time->wDay = totaldays + 1;
2778 g_message("%s: Day: %d", __func__, system_time->wDay);
2784 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2786 struct _WapiHandle_find find_handle = {0};
2788 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2791 if (pattern == NULL) {
2793 g_message ("%s: pattern is NULL", __func__);
2796 SetLastError (ERROR_PATH_NOT_FOUND);
2797 return(INVALID_HANDLE_VALUE);
2800 utf8_pattern = mono_unicode_to_external (pattern);
2801 if (utf8_pattern == NULL) {
2803 g_message ("%s: unicode conversion returned NULL", __func__);
2806 SetLastError (ERROR_INVALID_NAME);
2807 return(INVALID_HANDLE_VALUE);
2811 g_message ("%s: looking for [%s]", __func__, utf8_pattern);
2814 /* Figure out which bit of the pattern is the directory */
2815 dir_part = _wapi_dirname (utf8_pattern);
2816 entry_part = _wapi_basename (utf8_pattern);
2819 /* Don't do this check for now, it breaks if directories
2820 * really do have metachars in their names (see bug 58116).
2821 * FIXME: Figure out a better solution to keep some checks...
2823 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2824 SetLastError (ERROR_INVALID_NAME);
2826 g_free (entry_part);
2827 g_free (utf8_pattern);
2828 return(INVALID_HANDLE_VALUE);
2832 /* The pattern can specify a directory or a set of files.
2834 * The pattern can have wildcard characters ? and *, but only
2835 * in the section after the last directory delimiter. (Return
2836 * ERROR_INVALID_NAME if there are wildcards in earlier path
2837 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2838 * means "match one character", "??" seems to mean "match one
2839 * or two characters", "???" seems to mean "match one, two or
2840 * three characters", etc. Windows will also try and match
2841 * the mangled "short name" of files, so 8 character patterns
2842 * with wildcards will show some surprising results.
2844 * All the written documentation I can find says that '?'
2845 * should only match one character, and doesn't mention '??',
2846 * '???' etc. I'm going to assume that the strict behaviour
2847 * (ie '???' means three and only three characters) is the
2848 * correct one, because that lets me use fnmatch(3) rather
2849 * than mess around with regexes.
2852 find_handle.namelist = NULL;
2853 result = _wapi_io_scandir (dir_part, entry_part,
2854 &find_handle.namelist);
2857 /* No files, which windows seems to call
2860 SetLastError (ERROR_FILE_NOT_FOUND);
2861 g_free (utf8_pattern);
2862 g_free (entry_part);
2864 return (INVALID_HANDLE_VALUE);
2869 gint errnum = errno;
2871 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2873 g_message ("%s: scandir error: %s", __func__,
2874 g_strerror (errnum));
2876 g_free (utf8_pattern);
2877 g_free (entry_part);
2879 return (INVALID_HANDLE_VALUE);
2882 g_free (utf8_pattern);
2883 g_free (entry_part);
2886 g_message ("%s: Got %d matches", __func__, result);
2889 find_handle.dir_part = dir_part;
2890 find_handle.num = result;
2891 find_handle.count = 0;
2893 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2894 if (handle == _WAPI_HANDLE_INVALID) {
2895 g_warning ("%s: error creating find handle", __func__);
2897 g_free (entry_part);
2898 g_free (utf8_pattern);
2899 SetLastError (ERROR_GEN_FAILURE);
2901 return(INVALID_HANDLE_VALUE);
2904 if (handle != INVALID_HANDLE_VALUE &&
2905 !FindNextFile (handle, find_data)) {
2907 SetLastError (ERROR_NO_MORE_FILES);
2908 handle = INVALID_HANDLE_VALUE;
2914 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2916 struct _WapiHandle_find *find_handle;
2918 struct stat buf, linkbuf;
2921 gchar *utf8_filename, *utf8_basename;
2922 gunichar2 *utf16_basename;
2926 gboolean ret = FALSE;
2928 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2929 (gpointer *)&find_handle);
2931 g_warning ("%s: error looking up find handle %p", __func__,
2933 SetLastError (ERROR_INVALID_HANDLE);
2937 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2939 thr_ret = _wapi_handle_lock_handle (handle);
2940 g_assert (thr_ret == 0);
2943 if (find_handle->count >= find_handle->num) {
2944 SetLastError (ERROR_NO_MORE_FILES);
2948 /* stat next match */
2950 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2952 result = _wapi_stat (filename, &buf);
2953 if (result == -1 && errno == ENOENT) {
2954 /* Might be a dangling symlink */
2955 result = _wapi_lstat (filename, &buf);
2960 g_message ("%s: stat failed: %s", __func__, filename);
2967 result = _wapi_lstat (filename, &linkbuf);
2970 g_message ("%s: lstat failed: %s", __func__, filename);
2977 utf8_filename = mono_utf8_from_external (filename);
2978 if (utf8_filename == NULL) {
2979 /* We couldn't turn this filename into utf8 (eg the
2980 * encoding of the name wasn't convertible), so just
2983 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2991 g_message ("%s: Found [%s]", __func__, utf8_filename);
2994 /* fill data block */
2996 if (buf.st_mtime < buf.st_ctime)
2997 create_time = buf.st_mtime;
2999 create_time = buf.st_ctime;
3001 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
3003 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
3004 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
3005 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
3007 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3008 find_data->nFileSizeHigh = 0;
3009 find_data->nFileSizeLow = 0;
3011 find_data->nFileSizeHigh = buf.st_size >> 32;
3012 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3015 find_data->dwReserved0 = 0;
3016 find_data->dwReserved1 = 0;
3018 utf8_basename = _wapi_basename (utf8_filename);
3019 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
3021 if(utf16_basename==NULL) {
3022 g_free (utf8_basename);
3023 g_free (utf8_filename);
3028 /* utf16 is 2 * utf8 */
3031 memset (find_data->cFileName, '\0', (MAX_PATH*2));
3033 /* Truncating a utf16 string like this might leave the last
3036 memcpy (find_data->cFileName, utf16_basename,
3037 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3039 find_data->cAlternateFileName [0] = 0; /* not used */
3041 g_free (utf8_basename);
3042 g_free (utf8_filename);
3043 g_free (utf16_basename);
3046 thr_ret = _wapi_handle_unlock_handle (handle);
3047 g_assert (thr_ret == 0);
3048 pthread_cleanup_pop (0);
3055 * @wapi_handle: the find handle to close.
3057 * Closes find handle @wapi_handle
3059 * Return value: %TRUE on success, %FALSE otherwise.
3061 gboolean FindClose (gpointer handle)
3063 struct _WapiHandle_find *find_handle;
3067 if (handle == NULL) {
3068 SetLastError (ERROR_INVALID_HANDLE);
3072 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
3073 (gpointer *)&find_handle);
3075 g_warning ("%s: error looking up find handle %p", __func__,
3077 SetLastError (ERROR_INVALID_HANDLE);
3081 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
3083 thr_ret = _wapi_handle_lock_handle (handle);
3084 g_assert (thr_ret == 0);
3086 g_strfreev (find_handle->namelist);
3087 g_free (find_handle->dir_part);
3089 thr_ret = _wapi_handle_unlock_handle (handle);
3090 g_assert (thr_ret == 0);
3091 pthread_cleanup_pop (0);
3093 _wapi_handle_unref (handle);
3100 * @name: a pointer to a NULL-terminated unicode string, that names
3101 * the directory to be created.
3102 * @security: ignored for now
3104 * Creates directory @name
3106 * Return value: %TRUE on success, %FALSE otherwise.
3108 gboolean CreateDirectory (const gunichar2 *name,
3109 WapiSecurityAttributes *security)
3116 g_message("%s: name is NULL", __func__);
3119 SetLastError (ERROR_INVALID_NAME);
3123 utf8_name = mono_unicode_to_external (name);
3124 if (utf8_name == NULL) {
3126 g_message ("%s: unicode conversion returned NULL", __func__);
3129 SetLastError (ERROR_INVALID_NAME);
3133 result = _wapi_mkdir (utf8_name, 0777);
3140 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3147 * @name: a pointer to a NULL-terminated unicode string, that names
3148 * the directory to be removed.
3150 * Removes directory @name
3152 * Return value: %TRUE on success, %FALSE otherwise.
3154 gboolean RemoveDirectory (const gunichar2 *name)
3161 g_message("%s: name is NULL", __func__);
3164 SetLastError (ERROR_INVALID_NAME);
3168 utf8_name = mono_unicode_to_external (name);
3169 if (utf8_name == NULL) {
3171 g_message ("%s: unicode conversion returned NULL", __func__);
3174 SetLastError (ERROR_INVALID_NAME);
3178 result = _wapi_rmdir (utf8_name);
3180 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3191 * GetFileAttributes:
3192 * @name: a pointer to a NULL-terminated unicode filename.
3194 * Gets the attributes for @name;
3196 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3198 guint32 GetFileAttributes (const gunichar2 *name)
3201 struct stat buf, linkbuf;
3207 g_message("%s: name is NULL", __func__);
3210 SetLastError (ERROR_INVALID_NAME);
3214 utf8_name = mono_unicode_to_external (name);
3215 if (utf8_name == NULL) {
3217 g_message ("%s: unicode conversion returned NULL", __func__);
3220 SetLastError (ERROR_INVALID_PARAMETER);
3221 return (INVALID_FILE_ATTRIBUTES);
3224 result = _wapi_stat (utf8_name, &buf);
3225 if (result == -1 && errno == ENOENT) {
3226 /* Might be a dangling symlink... */
3227 result = _wapi_lstat (utf8_name, &buf);
3231 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3233 return (INVALID_FILE_ATTRIBUTES);
3236 result = _wapi_lstat (utf8_name, &linkbuf);
3238 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3240 return (INVALID_FILE_ATTRIBUTES);
3243 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3251 * GetFileAttributesEx:
3252 * @name: a pointer to a NULL-terminated unicode filename.
3253 * @level: must be GetFileExInfoStandard
3254 * @info: pointer to a WapiFileAttributesData structure
3256 * Gets attributes, size and filetimes for @name;
3258 * Return value: %TRUE on success, %FALSE on failure
3260 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3263 WapiFileAttributesData *data;
3265 struct stat buf, linkbuf;
3269 if (level != GetFileExInfoStandard) {
3271 g_message ("%s: info level %d not supported.", __func__,
3275 SetLastError (ERROR_INVALID_PARAMETER);
3281 g_message("%s: name is NULL", __func__);
3284 SetLastError (ERROR_INVALID_NAME);
3288 utf8_name = mono_unicode_to_external (name);
3289 if (utf8_name == NULL) {
3291 g_message ("%s: unicode conversion returned NULL", __func__);
3294 SetLastError (ERROR_INVALID_PARAMETER);
3298 result = _wapi_stat (utf8_name, &buf);
3299 if (result == -1 && errno == ENOENT) {
3300 /* Might be a dangling symlink... */
3301 result = _wapi_lstat (utf8_name, &buf);
3305 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3310 result = _wapi_lstat (utf8_name, &linkbuf);
3312 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3317 /* fill data block */
3319 data = (WapiFileAttributesData *)info;
3321 if (buf.st_mtime < buf.st_ctime)
3322 create_time = buf.st_mtime;
3324 create_time = buf.st_ctime;
3326 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3332 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3333 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3334 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3336 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3337 data->nFileSizeHigh = 0;
3338 data->nFileSizeLow = 0;
3341 data->nFileSizeHigh = buf.st_size >> 32;
3342 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3350 * @name: name of file
3351 * @attrs: attributes to set
3353 * Changes the attributes on a named file.
3355 * Return value: %TRUE on success, %FALSE on failure.
3357 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3359 /* FIXME: think of something clever to do on unix */
3365 * Currently we only handle one *internal* case, with a value that is
3366 * not standard: 0x80000000, which means `set executable bit'
3371 g_message("%s: name is NULL", __func__);
3374 SetLastError (ERROR_INVALID_NAME);
3378 utf8_name = mono_unicode_to_external (name);
3379 if (utf8_name == NULL) {
3381 g_message ("%s: unicode conversion returned NULL", __func__);
3384 SetLastError (ERROR_INVALID_NAME);
3388 result = _wapi_stat (utf8_name, &buf);
3390 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3395 /* Contrary to the documentation, ms allows NORMAL to be
3396 * specified along with other attributes, so dont bother to
3397 * catch that case here.
3399 if (attrs & FILE_ATTRIBUTE_READONLY) {
3400 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3402 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3405 /* Ignore the other attributes for now */
3407 if (attrs & 0x80000000){
3408 mode_t exec_mask = 0;
3410 if ((buf.st_mode & S_IRUSR) != 0)
3411 exec_mask |= S_IXUSR;
3413 if ((buf.st_mode & S_IRGRP) != 0)
3414 exec_mask |= S_IXGRP;
3416 if ((buf.st_mode & S_IROTH) != 0)
3417 exec_mask |= S_IXOTH;
3419 result = chmod (utf8_name, buf.st_mode | exec_mask);
3421 /* Don't bother to reset executable (might need to change this
3431 * GetCurrentDirectory
3432 * @length: size of the buffer
3433 * @buffer: pointer to buffer that recieves path
3435 * Retrieves the current directory for the current process.
3437 * Return value: number of characters in buffer on success, zero on failure
3439 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3441 gunichar2 *utf16_path;
3445 if (getcwd ((char*)buffer, length) == NULL) {
3446 if (errno == ERANGE) { /*buffer length is not big enough */
3447 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*/
3450 utf16_path = mono_unicode_from_external (path, &bytes);
3451 g_free (utf16_path);
3455 _wapi_set_last_error_from_errno ();
3459 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3460 count = (bytes/2)+1;
3461 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3463 /* Add the terminator */
3464 memset (buffer, '\0', bytes+2);
3465 memcpy (buffer, utf16_path, bytes);
3467 g_free (utf16_path);
3473 * SetCurrentDirectory
3474 * @path: path to new directory
3476 * Changes the directory path for the current process.
3478 * Return value: %TRUE on success, %FALSE on failure.
3480 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3486 SetLastError (ERROR_INVALID_PARAMETER);
3490 utf8_path = mono_unicode_to_external (path);
3491 if (_wapi_chdir (utf8_path) != 0) {
3492 _wapi_set_last_error_from_errno ();
3502 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3503 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3505 struct _WapiHandle_file pipe_read_handle = {0};
3506 struct _WapiHandle_file pipe_write_handle = {0};
3507 gpointer read_handle;
3508 gpointer write_handle;
3512 mono_once (&io_ops_once, io_ops_init);
3515 g_message ("%s: Creating pipe", __func__);
3521 g_message ("%s: Error creating pipe: %s", __func__,
3525 _wapi_set_last_error_from_errno ();
3529 if (filedes[0] >= _wapi_fd_reserve ||
3530 filedes[1] >= _wapi_fd_reserve) {
3532 g_message ("%s: File descriptor is too big", __func__);
3535 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3543 /* filedes[0] is open for reading, filedes[1] for writing */
3545 pipe_read_handle.fileaccess = GENERIC_READ;
3546 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3548 if (read_handle == _WAPI_HANDLE_INVALID) {
3549 g_warning ("%s: error creating pipe read handle", __func__);
3552 SetLastError (ERROR_GEN_FAILURE);
3557 pipe_write_handle.fileaccess = GENERIC_WRITE;
3558 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3559 &pipe_write_handle);
3560 if (write_handle == _WAPI_HANDLE_INVALID) {
3561 g_warning ("%s: error creating pipe write handle", __func__);
3562 _wapi_handle_unref (read_handle);
3566 SetLastError (ERROR_GEN_FAILURE);
3571 *readpipe = read_handle;
3572 *writepipe = write_handle;
3575 g_message ("%s: Returning pipe: read handle %p, write handle %p",
3576 __func__, read_handle, write_handle);
3582 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3584 gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3585 gunichar2 *tmpdir16=NULL;
3590 if(tmpdir[strlen (tmpdir)]!='/') {
3592 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3595 tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3596 if(tmpdir16==NULL) {
3604 g_message ("%s: Size %d smaller than needed (%ld)",
3605 __func__, len, dirlen+1);
3610 /* Add the terminator */
3611 memset (buf, '\0', bytes+2);
3612 memcpy (buf, tmpdir16, bytes);
3618 if(tmpdir16!=NULL) {
3627 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3630 gunichar2 *ptr, *dir;
3631 glong length, total = 0;
3635 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3640 /* Sigh, mntent and friends don't work well.
3641 * It stops on the first line that doesn't begin with a '/'.
3642 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3643 fp = fopen ("/etc/mtab", "rt");
3645 fp = fopen ("/etc/mnttab", "rt");
3651 while (fgets (buffer, 512, fp) != NULL) {
3655 splitted = g_strsplit (buffer, " ", 0);
3656 if (!*splitted || !*(splitted + 1)) {
3657 g_strfreev (splitted);
3661 dir = g_utf8_to_utf16 (*(splitted + 1), -1, &length, NULL, NULL);
3662 g_strfreev (splitted);
3663 if (total + length + 1 > len) {
3665 return len * 2; /* guess */
3668 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3670 total += length + 1;
3675 /* Commented out, does not work with my mtab!!! - Gonz */
3676 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3680 gunichar2 *ptr, *dir;
3681 glong len, total = 0;
3684 fp = setmntent ("/etc/mtab", "rt");
3686 fp = setmntent ("/etc/mnttab", "rt");
3692 while ((mnt = getmntent (fp)) != NULL) {
3693 g_print ("GOT %s\n", mnt->mnt_dir);
3694 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3695 if (total + len + 1 > len) {
3696 return len * 2; /* guess */
3699 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3710 #if (defined(HAVE_STATVFS) || defined(HAVE_STATFS)) && !defined(PLATFORM_ANDROID)
3711 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3712 WapiULargeInteger *total_number_of_bytes,
3713 WapiULargeInteger *total_number_of_free_bytes)
3716 struct statvfs fsstat;
3717 #elif defined(HAVE_STATFS)
3718 struct statfs fsstat;
3720 gboolean isreadonly;
3721 gchar *utf8_path_name;
3724 if (path_name == NULL) {
3725 utf8_path_name = g_strdup (g_get_current_dir());
3726 if (utf8_path_name == NULL) {
3727 SetLastError (ERROR_DIRECTORY);
3732 utf8_path_name = mono_unicode_to_external (path_name);
3733 if (utf8_path_name == NULL) {
3735 g_message("%s: unicode conversion returned NULL", __func__);
3738 SetLastError (ERROR_INVALID_NAME);
3745 ret = statvfs (utf8_path_name, &fsstat);
3746 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
3747 #elif defined(HAVE_STATFS)
3748 ret = statfs (utf8_path_name, &fsstat);
3749 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
3751 } while(ret == -1 && errno == EINTR);
3753 g_free(utf8_path_name);
3756 _wapi_set_last_error_from_errno ();
3758 g_message ("%s: statvfs failed: %s", __func__, strerror (errno));
3763 /* total number of free bytes for non-root */
3764 if (free_bytes_avail != NULL) {
3766 free_bytes_avail->QuadPart = 0;
3769 free_bytes_avail->QuadPart = fsstat.f_bsize * fsstat.f_bavail;
3773 /* total number of bytes available for non-root */
3774 if (total_number_of_bytes != NULL) {
3775 total_number_of_bytes->QuadPart = fsstat.f_bsize * fsstat.f_blocks;
3778 /* total number of bytes available for root */
3779 if (total_number_of_free_bytes != NULL) {
3781 total_number_of_free_bytes->QuadPart = 0;
3784 total_number_of_free_bytes->QuadPart = fsstat.f_bsize * fsstat.f_bfree;
3791 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3792 WapiULargeInteger *total_number_of_bytes,
3793 WapiULargeInteger *total_number_of_free_bytes)
3795 if (free_bytes_avail != NULL) {
3796 free_bytes_avail->QuadPart = (guint64) -1;
3799 if (total_number_of_bytes != NULL) {
3800 total_number_of_bytes->QuadPart = (guint64) -1;
3803 if (total_number_of_free_bytes != NULL) {
3804 total_number_of_free_bytes->QuadPart = (guint64) -1;
3813 const gchar* fstype;
3816 static _wapi_drive_type _wapi_drive_types[] = {
3817 { DRIVE_RAMDISK, "ramfs" },
3818 { DRIVE_RAMDISK, "tmpfs" },
3819 { DRIVE_RAMDISK, "proc" },
3820 { DRIVE_RAMDISK, "sysfs" },
3821 { DRIVE_RAMDISK, "debugfs" },
3822 { DRIVE_RAMDISK, "devpts" },
3823 { DRIVE_RAMDISK, "securityfs" },
3824 { DRIVE_CDROM, "iso9660" },
3825 { DRIVE_FIXED, "ext2" },
3826 { DRIVE_FIXED, "ext3" },
3827 { DRIVE_FIXED, "ext4" },
3828 { DRIVE_FIXED, "sysv" },
3829 { DRIVE_FIXED, "reiserfs" },
3830 { DRIVE_FIXED, "ufs" },
3831 { DRIVE_FIXED, "vfat" },
3832 { DRIVE_FIXED, "msdos" },
3833 { DRIVE_FIXED, "udf" },
3834 { DRIVE_FIXED, "hfs" },
3835 { DRIVE_FIXED, "hpfs" },
3836 { DRIVE_FIXED, "qnx4" },
3837 { DRIVE_FIXED, "ntfs" },
3838 { DRIVE_FIXED, "ntfs-3g" },
3839 { DRIVE_REMOTE, "smbfs" },
3840 { DRIVE_REMOTE, "fuse" },
3841 { DRIVE_REMOTE, "nfs" },
3842 { DRIVE_REMOTE, "nfs4" },
3843 { DRIVE_REMOTE, "cifs" },
3844 { DRIVE_REMOTE, "ncpfs" },
3845 { DRIVE_REMOTE, "coda" },
3846 { DRIVE_REMOTE, "afs" },
3847 { DRIVE_UNKNOWN, NULL }
3850 static guint32 _wapi_get_drive_type(const gchar* fstype)
3852 _wapi_drive_type *current;
3854 current = &_wapi_drive_types[0];
3855 while (current->drive_type != DRIVE_UNKNOWN) {
3856 if (strcmp (current->fstype, fstype) == 0)
3862 return current->drive_type;
3865 guint32 GetDriveType(const gunichar2 *root_path_name)
3870 gchar *utf8_root_path_name;
3873 if (root_path_name == NULL) {
3874 utf8_root_path_name = g_strdup (g_get_current_dir());
3875 if (utf8_root_path_name == NULL) {
3876 return(DRIVE_NO_ROOT_DIR);
3880 utf8_root_path_name = mono_unicode_to_external (root_path_name);
3881 if (utf8_root_path_name == NULL) {
3883 g_message("%s: unicode conversion returned NULL", __func__);
3885 return(DRIVE_NO_ROOT_DIR);
3888 /* strip trailing slash for compare below */
3889 if (g_str_has_suffix(utf8_root_path_name, "/")) {
3890 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
3894 fp = fopen ("/etc/mtab", "rt");
3896 fp = fopen ("/etc/mnttab", "rt");
3898 g_free (utf8_root_path_name);
3899 return(DRIVE_UNKNOWN);
3903 drive_type = DRIVE_NO_ROOT_DIR;
3904 while (fgets (buffer, 512, fp) != NULL) {
3905 splitted = g_strsplit (buffer, " ", 0);
3906 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
3907 g_strfreev (splitted);
3911 /* compare given root_path_name with the one from mtab,
3912 if length of utf8_root_path_name is zero it must be the root dir */
3913 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
3914 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
3915 drive_type = _wapi_get_drive_type (*(splitted + 2));
3916 g_strfreev (splitted);
3920 g_strfreev (splitted);
3924 g_free (utf8_root_path_name);
3926 return (drive_type);