2 * io.c: File, console and find handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002 Ximian, Inc.
8 * Copyright (c) 2002-2006 Novell, Inc.
18 #ifdef HAVE_SYS_STATVFS_H
19 #include <sys/statvfs.h>
20 #elif defined(HAVE_SYS_STATFS_H)
21 #include <sys/statfs.h>
23 #if defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H)
24 #include <sys/param.h>
25 #include <sys/mount.h>
27 #include <sys/types.h>
33 #include <sys/ioctl.h>
37 #include <mono/io-layer/wapi.h>
38 #include <mono/io-layer/wapi-private.h>
39 #include <mono/io-layer/handles-private.h>
40 #include <mono/io-layer/io-private.h>
41 #include <mono/io-layer/timefuncs-private.h>
42 #include <mono/io-layer/thread-private.h>
43 #include <mono/io-layer/io-portability.h>
44 #include <mono/utils/strenc.h>
48 static void file_close (gpointer handle, gpointer data);
49 static WapiFileType file_getfiletype(void);
50 static gboolean file_read(gpointer handle, gpointer buffer,
51 guint32 numbytes, guint32 *bytesread,
52 WapiOverlapped *overlapped);
53 static gboolean file_write(gpointer handle, gconstpointer buffer,
54 guint32 numbytes, guint32 *byteswritten,
55 WapiOverlapped *overlapped);
56 static gboolean file_flush(gpointer handle);
57 static guint32 file_seek(gpointer handle, gint32 movedistance,
58 gint32 *highmovedistance, WapiSeekMethod method);
59 static gboolean file_setendoffile(gpointer handle);
60 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
61 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
62 WapiFileTime *last_access,
63 WapiFileTime *last_write);
64 static gboolean file_setfiletime(gpointer handle,
65 const WapiFileTime *create_time,
66 const WapiFileTime *last_access,
67 const WapiFileTime *last_write);
68 static guint32 GetDriveTypeFromPath (const gchar *utf8_root_path_name);
70 /* File handle is only signalled for overlapped IO */
71 struct _WapiHandleOps _wapi_file_ops = {
72 file_close, /* close */
76 NULL, /* special_wait */
80 void _wapi_file_details (gpointer handle_info)
82 struct _WapiHandle_file *file = (struct _WapiHandle_file *)handle_info;
84 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
86 file->fileaccess&GENERIC_READ?'R':'.',
87 file->fileaccess&GENERIC_WRITE?'W':'.',
88 file->fileaccess&GENERIC_EXECUTE?'X':'.',
89 file->sharemode&FILE_SHARE_READ?'R':'.',
90 file->sharemode&FILE_SHARE_WRITE?'W':'.',
91 file->sharemode&FILE_SHARE_DELETE?'D':'.',
95 static void console_close (gpointer handle, gpointer data);
96 static WapiFileType console_getfiletype(void);
97 static gboolean console_read(gpointer handle, gpointer buffer,
98 guint32 numbytes, guint32 *bytesread,
99 WapiOverlapped *overlapped);
100 static gboolean console_write(gpointer handle, gconstpointer buffer,
101 guint32 numbytes, guint32 *byteswritten,
102 WapiOverlapped *overlapped);
104 /* Console is mostly the same as file, except it can block waiting for
107 struct _WapiHandleOps _wapi_console_ops = {
108 console_close, /* close */
112 NULL, /* special_wait */
116 void _wapi_console_details (gpointer handle_info)
118 _wapi_file_details (handle_info);
121 /* Find handle has no ops.
123 struct _WapiHandleOps _wapi_find_ops = {
128 NULL, /* special_wait */
132 static void pipe_close (gpointer handle, gpointer data);
133 static WapiFileType pipe_getfiletype (void);
134 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
135 guint32 *bytesread, WapiOverlapped *overlapped);
136 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
137 guint32 numbytes, guint32 *byteswritten,
138 WapiOverlapped *overlapped);
142 struct _WapiHandleOps _wapi_pipe_ops = {
143 pipe_close, /* close */
147 NULL, /* special_wait */
151 void _wapi_pipe_details (gpointer handle_info)
153 _wapi_file_details (handle_info);
156 static const struct {
157 /* File, console and pipe handles */
158 WapiFileType (*getfiletype)(void);
160 /* File, console and pipe handles */
161 gboolean (*readfile)(gpointer handle, gpointer buffer,
162 guint32 numbytes, guint32 *bytesread,
163 WapiOverlapped *overlapped);
164 gboolean (*writefile)(gpointer handle, gconstpointer buffer,
165 guint32 numbytes, guint32 *byteswritten,
166 WapiOverlapped *overlapped);
167 gboolean (*flushfile)(gpointer handle);
170 guint32 (*seek)(gpointer handle, gint32 movedistance,
171 gint32 *highmovedistance, WapiSeekMethod method);
172 gboolean (*setendoffile)(gpointer handle);
173 guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
174 gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
175 WapiFileTime *last_access,
176 WapiFileTime *last_write);
177 gboolean (*setfiletime)(gpointer handle,
178 const WapiFileTime *create_time,
179 const WapiFileTime *last_access,
180 const WapiFileTime *last_write);
181 } io_ops[WAPI_HANDLE_COUNT]={
182 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
185 file_read, file_write,
186 file_flush, file_seek,
192 {console_getfiletype,
195 NULL, NULL, NULL, NULL, NULL, NULL},
197 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
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},
204 /* socket (will need at least read and write) */
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},
214 NULL, NULL, NULL, NULL, NULL, NULL},
217 static mono_once_t io_ops_once=MONO_ONCE_INIT;
218 static gboolean lock_while_writing = FALSE;
220 static void io_ops_init (void)
222 /* _wapi_handle_register_capabilities (WAPI_HANDLE_FILE, */
223 /* WAPI_HANDLE_CAP_WAIT); */
224 /* _wapi_handle_register_capabilities (WAPI_HANDLE_CONSOLE, */
225 /* WAPI_HANDLE_CAP_WAIT); */
227 if (g_getenv ("MONO_STRICT_IO_EMULATION") != NULL) {
228 lock_while_writing = TRUE;
232 /* Some utility functions.
235 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
242 /* FIXME: this could definitely be better, but there seems to
243 * be no pattern to the attributes that are set
246 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
247 if (S_ISSOCK (buf->st_mode))
248 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
250 filename = _wapi_basename (pathname);
252 if (S_ISDIR (buf->st_mode)) {
253 attrs = FILE_ATTRIBUTE_DIRECTORY;
254 if (!(buf->st_mode & S_IWUSR)) {
255 attrs |= FILE_ATTRIBUTE_READONLY;
257 if (filename[0] == '.') {
258 attrs |= FILE_ATTRIBUTE_HIDDEN;
261 if (!(buf->st_mode & S_IWUSR)) {
262 attrs = FILE_ATTRIBUTE_READONLY;
264 if (filename[0] == '.') {
265 attrs |= FILE_ATTRIBUTE_HIDDEN;
267 } else if (filename[0] == '.') {
268 attrs = FILE_ATTRIBUTE_HIDDEN;
270 attrs = FILE_ATTRIBUTE_NORMAL;
275 if (S_ISLNK (lbuf->st_mode)) {
276 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
286 _wapi_set_last_error_from_errno (void)
288 SetLastError (_wapi_get_win32_file_error (errno));
291 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
294 if (errno == ENOENT) {
295 /* Check the path - if it's a missing directory then
296 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
302 dirname = _wapi_dirname (path);
304 dirname = g_strdup (dir);
307 if (_wapi_access (dirname, F_OK) == 0) {
308 SetLastError (ERROR_FILE_NOT_FOUND);
310 SetLastError (ERROR_PATH_NOT_FOUND);
315 _wapi_set_last_error_from_errno ();
321 static void file_close (gpointer handle, gpointer data)
323 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
326 g_message("%s: closing file handle %p [%s]", __func__, handle,
327 file_handle->filename);
330 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
331 _wapi_unlink (file_handle->filename);
333 g_free (file_handle->filename);
335 if (file_handle->share_info)
336 _wapi_handle_share_release (file_handle->share_info);
338 close (GPOINTER_TO_UINT(handle));
341 static WapiFileType file_getfiletype(void)
343 return(FILE_TYPE_DISK);
346 static gboolean file_read(gpointer handle, gpointer buffer,
347 guint32 numbytes, guint32 *bytesread,
348 WapiOverlapped *overlapped)
350 struct _WapiHandle_file *file_handle;
352 int fd = GPOINTER_TO_UINT(handle);
355 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
356 (gpointer *)&file_handle);
358 g_warning ("%s: error looking up file handle %p", __func__,
360 SetLastError (ERROR_INVALID_HANDLE);
364 if(bytesread!=NULL) {
368 if(!(file_handle->fileaccess & GENERIC_READ) &&
369 !(file_handle->fileaccess & GENERIC_ALL)) {
371 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
372 __func__, handle, file_handle->fileaccess);
375 SetLastError (ERROR_ACCESS_DENIED);
380 ret = read (fd, buffer, numbytes);
381 } while (ret == -1 && errno == EINTR &&
382 !_wapi_thread_cur_apc_pending());
388 g_message("%s: read of handle %p error: %s", __func__,
389 handle, strerror(err));
391 SetLastError (_wapi_get_win32_file_error (err));
395 if (bytesread != NULL) {
402 static gboolean file_write(gpointer handle, gconstpointer buffer,
403 guint32 numbytes, guint32 *byteswritten,
404 WapiOverlapped *overlapped G_GNUC_UNUSED)
406 struct _WapiHandle_file *file_handle;
409 off_t current_pos = 0;
410 int fd = GPOINTER_TO_UINT(handle);
412 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
413 (gpointer *)&file_handle);
415 g_warning ("%s: error looking up file handle %p", __func__,
417 SetLastError (ERROR_INVALID_HANDLE);
421 if(byteswritten!=NULL) {
425 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
426 !(file_handle->fileaccess & GENERIC_ALL)) {
428 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
431 SetLastError (ERROR_ACCESS_DENIED);
435 if (lock_while_writing) {
436 /* Need to lock the region we're about to write to,
437 * because we only do advisory locking on POSIX
440 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
441 if (current_pos == -1) {
443 g_message ("%s: handle %p lseek failed: %s", __func__,
444 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 ();
473 g_message("%s: write of handle %p error: %s",
474 __func__, handle, strerror(errno));
480 if (byteswritten != NULL) {
486 static gboolean file_flush(gpointer handle)
488 struct _WapiHandle_file *file_handle;
491 int fd = GPOINTER_TO_UINT(handle);
493 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
494 (gpointer *)&file_handle);
496 g_warning ("%s: error looking up file handle %p", __func__,
498 SetLastError (ERROR_INVALID_HANDLE);
502 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
503 !(file_handle->fileaccess & GENERIC_ALL)) {
505 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
508 SetLastError (ERROR_ACCESS_DENIED);
515 g_message("%s: fsync of handle %p error: %s", __func__, handle,
519 _wapi_set_last_error_from_errno ();
526 static guint32 file_seek(gpointer handle, gint32 movedistance,
527 gint32 *highmovedistance, WapiSeekMethod method)
529 struct _WapiHandle_file *file_handle;
531 off_t offset, newpos;
534 int fd = GPOINTER_TO_UINT(handle);
536 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
537 (gpointer *)&file_handle);
539 g_warning ("%s: error looking up file handle %p", __func__,
541 SetLastError (ERROR_INVALID_HANDLE);
542 return(INVALID_SET_FILE_POINTER);
545 if(!(file_handle->fileaccess & GENERIC_READ) &&
546 !(file_handle->fileaccess & GENERIC_WRITE) &&
547 !(file_handle->fileaccess & GENERIC_ALL)) {
549 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
552 SetLastError (ERROR_ACCESS_DENIED);
553 return(INVALID_SET_FILE_POINTER);
568 g_message("%s: invalid seek type %d", __func__, method);
571 SetLastError (ERROR_INVALID_PARAMETER);
572 return(INVALID_SET_FILE_POINTER);
575 #ifdef HAVE_LARGE_FILE_SUPPORT
576 if(highmovedistance==NULL) {
579 g_message("%s: setting offset to %lld (low %d)", __func__,
580 offset, movedistance);
583 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
586 g_message("%s: setting offset to %lld 0x%llx (high %d 0x%x, low %d 0x%x)", __func__, offset, offset, *highmovedistance, *highmovedistance, movedistance, movedistance);
594 #ifdef HAVE_LARGE_FILE_SUPPORT
595 g_message("%s: moving handle %p by %lld bytes from %d", __func__,
596 handle, offset, whence);
598 g_message("%s: moving handle %p fd %d by %ld bytes from %d", __func__,
599 handle, offset, whence);
603 newpos=lseek(fd, offset, whence);
606 g_message("%s: lseek on handle %p returned error %s",
607 __func__, handle, strerror(errno));
610 _wapi_set_last_error_from_errno ();
611 return(INVALID_SET_FILE_POINTER);
615 #ifdef HAVE_LARGE_FILE_SUPPORT
616 g_message("%s: lseek returns %lld", __func__, newpos);
618 g_message ("%s: lseek returns %ld", __func__, newpos);
622 #ifdef HAVE_LARGE_FILE_SUPPORT
623 ret=newpos & 0xFFFFFFFF;
624 if(highmovedistance!=NULL) {
625 *highmovedistance=newpos>>32;
629 if(highmovedistance!=NULL) {
630 /* Accurate, but potentially dodgy :-) */
636 g_message ("%s: move of handle %p returning %d/%d", __func__,
637 handle, ret, highmovedistance==NULL?0:*highmovedistance);
643 static gboolean file_setendoffile(gpointer handle)
645 struct _WapiHandle_file *file_handle;
650 int fd = GPOINTER_TO_UINT(handle);
652 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
653 (gpointer *)&file_handle);
655 g_warning ("%s: error looking up file handle %p", __func__,
657 SetLastError (ERROR_INVALID_HANDLE);
661 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
662 !(file_handle->fileaccess & GENERIC_ALL)) {
664 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
667 SetLastError (ERROR_ACCESS_DENIED);
671 /* Find the current file position, and the file length. If
672 * the file position is greater than the length, write to
673 * extend the file with a hole. If the file position is less
674 * than the length, truncate the file.
677 ret=fstat(fd, &statbuf);
680 g_message ("%s: handle %p fstat failed: %s", __func__,
681 handle, strerror(errno));
684 _wapi_set_last_error_from_errno ();
687 size=statbuf.st_size;
689 pos=lseek(fd, (off_t)0, SEEK_CUR);
692 g_message("%s: handle %p lseek failed: %s", __func__,
693 handle, strerror(errno));
696 _wapi_set_last_error_from_errno ();
700 #ifdef FTRUNCATE_DOESNT_EXTEND
701 /* I haven't bothered to write the configure.in stuff for this
702 * because I don't know if any platform needs it. I'm leaving
703 * this code just in case though
706 /* Extend the file. Use write() here, because some
707 * manuals say that ftruncate() behaviour is undefined
708 * when the file needs extending. The POSIX spec says
709 * that on XSI-conformant systems it extends, so if
710 * every system we care about conforms, then we can
714 ret = write (fd, "", 1);
715 } while (ret == -1 && errno == EINTR &&
716 !_wapi_thread_cur_apc_pending());
720 g_message("%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
723 _wapi_set_last_error_from_errno ();
727 /* And put the file position back after the write */
728 ret = lseek (fd, pos, SEEK_SET);
731 g_message ("%s: handle %p second lseek failed: %s",
732 __func__, handle, strerror(errno));
735 _wapi_set_last_error_from_errno ();
741 /* always truncate, because the extend write() adds an extra
742 * byte to the end of the file
745 ret=ftruncate(fd, pos);
747 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
750 g_message("%s: handle %p ftruncate failed: %s", __func__,
751 handle, strerror(errno));
754 _wapi_set_last_error_from_errno ();
761 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
763 struct _WapiHandle_file *file_handle;
768 int fd = GPOINTER_TO_UINT(handle);
770 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
771 (gpointer *)&file_handle);
773 g_warning ("%s: error looking up file handle %p", __func__,
775 SetLastError (ERROR_INVALID_HANDLE);
776 return(INVALID_FILE_SIZE);
779 if(!(file_handle->fileaccess & GENERIC_READ) &&
780 !(file_handle->fileaccess & GENERIC_WRITE) &&
781 !(file_handle->fileaccess & GENERIC_ALL)) {
783 g_message("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
786 SetLastError (ERROR_ACCESS_DENIED);
787 return(INVALID_FILE_SIZE);
790 /* If the file has a size with the low bits 0xFFFFFFFF the
791 * caller can't tell if this is an error, so clear the error
794 SetLastError (ERROR_SUCCESS);
796 ret = fstat(fd, &statbuf);
799 g_message ("%s: handle %p fstat failed: %s", __func__,
800 handle, strerror(errno));
803 _wapi_set_last_error_from_errno ();
804 return(INVALID_FILE_SIZE);
807 /* fstat indicates block devices as zero-length, so go a different path */
809 if (S_ISBLK(statbuf.st_mode)) {
811 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
813 g_message ("%s: handle %p ioctl BLKGETSIZE64 failed: %s",
814 __func__, handle, strerror(errno));
817 _wapi_set_last_error_from_errno ();
818 return(INVALID_FILE_SIZE);
821 size = bigsize & 0xFFFFFFFF;
822 if (highsize != NULL) {
823 *highsize = bigsize>>32;
827 g_message ("%s: Returning block device size %d/%d",
828 __func__, size, *highsize);
835 #ifdef HAVE_LARGE_FILE_SUPPORT
836 size = statbuf.st_size & 0xFFFFFFFF;
837 if (highsize != NULL) {
838 *highsize = statbuf.st_size>>32;
841 if (highsize != NULL) {
842 /* Accurate, but potentially dodgy :-) */
845 size = statbuf.st_size;
849 g_message ("%s: Returning size %d/%d", __func__, size, *highsize);
855 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
856 WapiFileTime *last_access,
857 WapiFileTime *last_write)
859 struct _WapiHandle_file *file_handle;
862 guint64 create_ticks, access_ticks, write_ticks;
864 int fd = GPOINTER_TO_UINT(handle);
866 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
867 (gpointer *)&file_handle);
869 g_warning ("%s: error looking up file handle %p", __func__,
871 SetLastError (ERROR_INVALID_HANDLE);
875 if(!(file_handle->fileaccess & GENERIC_READ) &&
876 !(file_handle->fileaccess & GENERIC_ALL)) {
878 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
879 __func__, handle, file_handle->fileaccess);
882 SetLastError (ERROR_ACCESS_DENIED);
886 ret=fstat(fd, &statbuf);
889 g_message("%s: handle %p fstat failed: %s", __func__, handle,
893 _wapi_set_last_error_from_errno ();
898 g_message("%s: atime: %ld ctime: %ld mtime: %ld", __func__,
899 statbuf.st_atime, statbuf.st_ctime,
903 /* Try and guess a meaningful create time by using the older
906 /* The magic constant comes from msdn documentation
907 * "Converting a time_t Value to a File Time"
909 if(statbuf.st_atime < statbuf.st_ctime) {
910 create_ticks=((guint64)statbuf.st_atime*10000000)
911 + 116444736000000000ULL;
913 create_ticks=((guint64)statbuf.st_ctime*10000000)
914 + 116444736000000000ULL;
917 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
918 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
921 g_message("%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
922 access_ticks, create_ticks, write_ticks);
925 if(create_time!=NULL) {
926 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
927 create_time->dwHighDateTime = create_ticks >> 32;
930 if(last_access!=NULL) {
931 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
932 last_access->dwHighDateTime = access_ticks >> 32;
935 if(last_write!=NULL) {
936 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
937 last_write->dwHighDateTime = write_ticks >> 32;
943 static gboolean file_setfiletime(gpointer handle,
944 const WapiFileTime *create_time G_GNUC_UNUSED,
945 const WapiFileTime *last_access,
946 const WapiFileTime *last_write)
948 struct _WapiHandle_file *file_handle;
950 struct utimbuf utbuf;
952 guint64 access_ticks, write_ticks;
954 int fd = GPOINTER_TO_UINT(handle);
956 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
957 (gpointer *)&file_handle);
959 g_warning ("%s: error looking up file handle %p", __func__,
961 SetLastError (ERROR_INVALID_HANDLE);
965 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
966 !(file_handle->fileaccess & GENERIC_ALL)) {
968 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
971 SetLastError (ERROR_ACCESS_DENIED);
975 if(file_handle->filename == NULL) {
977 g_message("%s: handle %p unknown filename", __func__, handle);
980 SetLastError (ERROR_INVALID_HANDLE);
984 /* Get the current times, so we can put the same times back in
985 * the event that one of the FileTime structs is NULL
987 ret=fstat (fd, &statbuf);
990 g_message("%s: handle %p fstat failed: %s", __func__, handle,
994 SetLastError (ERROR_INVALID_PARAMETER);
998 if(last_access!=NULL) {
999 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
1000 last_access->dwLowDateTime;
1001 /* This is (time_t)0. We can actually go to INT_MIN,
1002 * but this will do for now.
1004 if (access_ticks < 116444736000000000ULL) {
1006 g_message ("%s: attempt to set access time too early",
1009 SetLastError (ERROR_INVALID_PARAMETER);
1013 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
1015 utbuf.actime=statbuf.st_atime;
1018 if(last_write!=NULL) {
1019 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
1020 last_write->dwLowDateTime;
1021 /* This is (time_t)0. We can actually go to INT_MIN,
1022 * but this will do for now.
1024 if (write_ticks < 116444736000000000ULL) {
1026 g_message ("%s: attempt to set write time too early",
1029 SetLastError (ERROR_INVALID_PARAMETER);
1033 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1035 utbuf.modtime=statbuf.st_mtime;
1039 g_message ("%s: setting handle %p access %ld write %ld", __func__,
1040 handle, utbuf.actime, utbuf.modtime);
1043 ret = _wapi_utime (file_handle->filename, &utbuf);
1046 g_message ("%s: handle %p [%s] utime failed: %s", __func__,
1047 handle, file_handle->filename, strerror(errno));
1050 SetLastError (ERROR_INVALID_PARAMETER);
1057 static void console_close (gpointer handle, gpointer data)
1059 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1062 g_message("%s: closing console handle %p", __func__, handle);
1065 g_free (console_handle->filename);
1067 close (GPOINTER_TO_UINT(handle));
1070 static WapiFileType console_getfiletype(void)
1072 return(FILE_TYPE_CHAR);
1075 static gboolean console_read(gpointer handle, gpointer buffer,
1076 guint32 numbytes, guint32 *bytesread,
1077 WapiOverlapped *overlapped G_GNUC_UNUSED)
1079 struct _WapiHandle_file *console_handle;
1082 int fd = GPOINTER_TO_UINT(handle);
1084 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1085 (gpointer *)&console_handle);
1087 g_warning ("%s: error looking up console handle %p", __func__,
1089 SetLastError (ERROR_INVALID_HANDLE);
1093 if(bytesread!=NULL) {
1097 if(!(console_handle->fileaccess & GENERIC_READ) &&
1098 !(console_handle->fileaccess & GENERIC_ALL)) {
1100 g_message ("%s: handle %p doesn't have GENERIC_READ access: %u",
1101 __func__, handle, console_handle->fileaccess);
1104 SetLastError (ERROR_ACCESS_DENIED);
1109 ret=read(fd, buffer, numbytes);
1110 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1114 g_message("%s: read of handle %p error: %s", __func__, handle,
1118 _wapi_set_last_error_from_errno ();
1122 if(bytesread!=NULL) {
1129 static gboolean console_write(gpointer handle, gconstpointer buffer,
1130 guint32 numbytes, guint32 *byteswritten,
1131 WapiOverlapped *overlapped G_GNUC_UNUSED)
1133 struct _WapiHandle_file *console_handle;
1136 int fd = GPOINTER_TO_UINT(handle);
1138 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1139 (gpointer *)&console_handle);
1141 g_warning ("%s: error looking up console handle %p", __func__,
1143 SetLastError (ERROR_INVALID_HANDLE);
1147 if(byteswritten!=NULL) {
1151 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1152 !(console_handle->fileaccess & GENERIC_ALL)) {
1154 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, console_handle->fileaccess);
1157 SetLastError (ERROR_ACCESS_DENIED);
1162 ret = write(fd, buffer, numbytes);
1163 } while (ret == -1 && errno == EINTR &&
1164 !_wapi_thread_cur_apc_pending());
1167 if (errno == EINTR) {
1170 _wapi_set_last_error_from_errno ();
1173 g_message ("%s: write of handle %p error: %s",
1174 __func__, handle, strerror(errno));
1180 if(byteswritten!=NULL) {
1187 static void pipe_close (gpointer handle, gpointer data G_GNUC_UNUSED)
1190 g_message("%s: closing pipe handle %p", __func__, handle);
1193 /* No filename with pipe handles */
1195 close(GPOINTER_TO_UINT(handle));
1198 static WapiFileType pipe_getfiletype(void)
1200 return(FILE_TYPE_PIPE);
1203 static gboolean pipe_read (gpointer handle, gpointer buffer,
1204 guint32 numbytes, guint32 *bytesread,
1205 WapiOverlapped *overlapped G_GNUC_UNUSED)
1207 struct _WapiHandle_file *pipe_handle;
1210 int fd = GPOINTER_TO_UINT(handle);
1212 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1213 (gpointer *)&pipe_handle);
1215 g_warning ("%s: error looking up pipe handle %p", __func__,
1217 SetLastError (ERROR_INVALID_HANDLE);
1221 if(bytesread!=NULL) {
1225 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1226 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1228 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
1229 __func__, handle, pipe_handle->fileaccess);
1232 SetLastError (ERROR_ACCESS_DENIED);
1237 g_message ("%s: reading up to %d bytes from pipe %p", __func__,
1242 ret=read(fd, buffer, numbytes);
1243 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1246 if (errno == EINTR) {
1249 _wapi_set_last_error_from_errno ();
1252 g_message("%s: read of handle %p error: %s", __func__,
1253 handle, strerror(errno));
1261 g_message ("%s: read %d bytes from pipe", __func__, ret);
1264 if(bytesread!=NULL) {
1271 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1272 guint32 numbytes, guint32 *byteswritten,
1273 WapiOverlapped *overlapped G_GNUC_UNUSED)
1275 struct _WapiHandle_file *pipe_handle;
1278 int fd = GPOINTER_TO_UINT(handle);
1280 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1281 (gpointer *)&pipe_handle);
1283 g_warning ("%s: error looking up pipe handle %p", __func__,
1285 SetLastError (ERROR_INVALID_HANDLE);
1289 if(byteswritten!=NULL) {
1293 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1294 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1296 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, pipe_handle->fileaccess);
1299 SetLastError (ERROR_ACCESS_DENIED);
1304 g_message ("%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1309 ret = write (fd, buffer, numbytes);
1310 } while (ret == -1 && errno == EINTR &&
1311 !_wapi_thread_cur_apc_pending());
1314 if (errno == EINTR) {
1317 _wapi_set_last_error_from_errno ();
1320 g_message("%s: write of handle %p error: %s", __func__,
1321 handle, strerror(errno));
1327 if(byteswritten!=NULL) {
1334 static int convert_flags(guint32 fileaccess, guint32 createmode)
1338 switch(fileaccess) {
1345 case GENERIC_READ|GENERIC_WRITE:
1350 g_message("%s: Unknown access type 0x%x", __func__,
1356 switch(createmode) {
1358 flags|=O_CREAT|O_EXCL;
1361 flags|=O_CREAT|O_TRUNC;
1368 case TRUNCATE_EXISTING:
1373 g_message("%s: Unknown create mode 0x%x", __func__,
1383 static mode_t convert_perms(guint32 sharemode)
1387 if(sharemode&FILE_SHARE_READ) {
1390 if(sharemode&FILE_SHARE_WRITE) {
1398 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1400 struct _WapiFileShare **share_info)
1402 gboolean file_already_shared;
1403 guint32 file_existing_share, file_existing_access;
1405 file_already_shared = _wapi_handle_get_or_set_share (statbuf->st_dev, statbuf->st_ino, sharemode, fileaccess, &file_existing_share, &file_existing_access, share_info);
1407 if (file_already_shared) {
1408 /* The reference to this share info was incremented
1409 * when we looked it up, so be careful to put it back
1410 * if we conclude we can't use this file.
1412 if (file_existing_share == 0) {
1413 /* Quick and easy, no possibility to share */
1415 g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
1418 _wapi_handle_share_release (*share_info);
1423 if (((file_existing_share == FILE_SHARE_READ) &&
1424 (fileaccess != GENERIC_READ)) ||
1425 ((file_existing_share == FILE_SHARE_WRITE) &&
1426 (fileaccess != GENERIC_WRITE))) {
1427 /* New access mode doesn't match up */
1429 g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
1432 _wapi_handle_share_release (*share_info);
1437 if (((file_existing_access & GENERIC_READ) &&
1438 !(sharemode & FILE_SHARE_READ)) ||
1439 ((file_existing_access & GENERIC_WRITE) &&
1440 !(sharemode & FILE_SHARE_WRITE))) {
1441 /* New share mode doesn't match up */
1443 g_message ("%s: Access mode prevents open: requested share: 0x%x, file has access: 0x%x", __func__, sharemode, file_existing_access);
1446 _wapi_handle_share_release (*share_info);
1452 g_message ("%s: New file!", __func__);
1459 static gboolean share_check (struct stat *statbuf, guint32 sharemode,
1461 struct _WapiFileShare **share_info, int fd)
1463 if (share_allows_open (statbuf, sharemode, fileaccess,
1464 share_info) == TRUE) {
1468 /* Got a share violation. Double check that the file is still
1469 * open by someone, in case a process crashed while still
1470 * holding a file handle. This will also cope with someone
1471 * using Mono.Posix to close the file. This is cheaper and
1472 * less intrusive to other processes than initiating a handle
1476 _wapi_handle_check_share (*share_info, fd);
1477 if (share_allows_open (statbuf, sharemode, fileaccess,
1478 share_info) == TRUE) {
1482 /* Still violating. It's possible that a process crashed
1483 * while still holding a file handle, and that a non-mono
1484 * process has the file open. (For example, C-c mcs while
1485 * editing a source file.) As a last resort, run a handle
1486 * collection, which will remove stale share entries.
1488 _wapi_handle_collect ();
1490 return(share_allows_open (statbuf, sharemode, fileaccess, share_info));
1495 * @name: a pointer to a NULL-terminated unicode string, that names
1496 * the file or other object to create.
1497 * @fileaccess: specifies the file access mode
1498 * @sharemode: whether the file should be shared. This parameter is
1499 * currently ignored.
1500 * @security: Ignored for now.
1501 * @createmode: specifies whether to create a new file, whether to
1502 * overwrite an existing file, whether to truncate the file, etc.
1503 * @attrs: specifies file attributes and flags. On win32 attributes
1504 * are characteristics of the file, not the handle, and are ignored
1505 * when an existing file is opened. Flags give the library hints on
1506 * how to process a file to optimise performance.
1507 * @template: the handle of an open %GENERIC_READ file that specifies
1508 * attributes to apply to a newly created file, ignoring @attrs.
1509 * Normally this parameter is NULL. This parameter is ignored when an
1510 * existing file is opened.
1512 * Creates a new file handle. This only applies to normal files:
1513 * pipes are handled by CreatePipe(), and console handles are created
1514 * with GetStdHandle().
1516 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1518 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1519 guint32 sharemode, WapiSecurityAttributes *security,
1520 guint32 createmode, guint32 attrs,
1521 gpointer template G_GNUC_UNUSED)
1523 struct _WapiHandle_file file_handle = {0};
1525 int flags=convert_flags(fileaccess, createmode);
1526 /*mode_t perms=convert_perms(sharemode);*/
1527 /* we don't use sharemode, because that relates to sharing of
1528 * the file when the file is open and is already handled by
1529 * other code, perms instead are the on-disk permissions and
1530 * this is a sane default.
1536 struct stat statbuf;
1538 mono_once (&io_ops_once, io_ops_init);
1540 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1543 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1544 SetLastError (ERROR_ENCRYPTION_FAILED);
1545 return INVALID_HANDLE_VALUE;
1550 g_message ("%s: name is NULL", __func__);
1553 SetLastError (ERROR_INVALID_NAME);
1554 return(INVALID_HANDLE_VALUE);
1557 filename = mono_unicode_to_external (name);
1558 if (filename == NULL) {
1560 g_message("%s: unicode conversion returned NULL", __func__);
1563 SetLastError (ERROR_INVALID_NAME);
1564 return(INVALID_HANDLE_VALUE);
1568 g_message ("%s: Opening %s with share 0x%x and access 0x%x", __func__,
1569 filename, sharemode, fileaccess);
1572 fd = _wapi_open (filename, flags, perms);
1574 /* If we were trying to open a directory with write permissions
1575 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1576 * EISDIR. However, this is a bit bogus because calls to
1577 * manipulate the directory (e.g. SetFileTime) will still work on
1578 * the directory because they use other API calls
1579 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1580 * to open the directory again without write permission.
1582 if (fd == -1 && errno == EISDIR)
1584 /* Try again but don't try to make it writable */
1585 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1590 g_message("%s: Error opening file %s: %s", __func__, filename,
1593 _wapi_set_last_path_error_from_errno (NULL, filename);
1596 return(INVALID_HANDLE_VALUE);
1599 if (fd >= _wapi_fd_reserve) {
1601 g_message ("%s: File descriptor is too big", __func__);
1604 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1609 return(INVALID_HANDLE_VALUE);
1612 ret = fstat (fd, &statbuf);
1615 g_message ("%s: fstat error of file %s: %s", __func__,
1616 filename, strerror (errno));
1618 _wapi_set_last_error_from_errno ();
1622 return(INVALID_HANDLE_VALUE);
1625 if (share_check (&statbuf, sharemode, fileaccess,
1626 &file_handle.share_info, fd) == FALSE) {
1627 SetLastError (ERROR_SHARING_VIOLATION);
1631 return (INVALID_HANDLE_VALUE);
1633 if (file_handle.share_info == NULL) {
1634 /* No space, so no more files can be opened */
1636 g_message ("%s: No space in the share table", __func__);
1639 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1643 return(INVALID_HANDLE_VALUE);
1646 file_handle.filename = filename;
1648 if(security!=NULL) {
1649 //file_handle->security_attributes=_wapi_handle_scratch_store (
1650 //security, sizeof(WapiSecurityAttributes));
1653 file_handle.fileaccess=fileaccess;
1654 file_handle.sharemode=sharemode;
1655 file_handle.attrs=attrs;
1657 #ifdef HAVE_POSIX_FADVISE
1658 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1659 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1660 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1661 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1665 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1667 if (S_ISFIFO (statbuf.st_mode)) {
1668 handle_type = WAPI_HANDLE_PIPE;
1669 } else if (S_ISCHR (statbuf.st_mode)) {
1670 handle_type = WAPI_HANDLE_CONSOLE;
1672 handle_type = WAPI_HANDLE_FILE;
1675 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1676 if (handle == _WAPI_HANDLE_INVALID) {
1677 g_warning ("%s: error creating file handle", __func__);
1681 SetLastError (ERROR_GEN_FAILURE);
1682 return(INVALID_HANDLE_VALUE);
1686 g_message("%s: returning handle %p", __func__, handle);
1694 * @name: a pointer to a NULL-terminated unicode string, that names
1695 * the file to be deleted.
1697 * Deletes file @name.
1699 * Return value: %TRUE on success, %FALSE otherwise.
1701 gboolean DeleteFile(const gunichar2 *name)
1705 gboolean ret = FALSE;
1708 struct stat statbuf;
1709 struct _WapiFileShare *shareinfo;
1714 g_message("%s: name is NULL", __func__);
1717 SetLastError (ERROR_INVALID_NAME);
1721 filename=mono_unicode_to_external(name);
1722 if(filename==NULL) {
1724 g_message("%s: unicode conversion returned NULL", __func__);
1727 SetLastError (ERROR_INVALID_NAME);
1731 attrs = GetFileAttributes (name);
1732 if (attrs == INVALID_FILE_ATTRIBUTES) {
1734 g_message ("%s: file attributes error", __func__);
1736 /* Error set by GetFileAttributes() */
1741 if (attrs & FILE_ATTRIBUTE_READONLY) {
1743 g_message ("%s: file %s is readonly", __func__, filename);
1745 SetLastError (ERROR_ACCESS_DENIED);
1751 /* Check to make sure sharing allows us to open the file for
1752 * writing. See bug 323389.
1754 * Do the checks that don't need an open file descriptor, for
1755 * simplicity's sake. If we really have to do the full checks
1756 * then we can implement that later.
1758 if (_wapi_stat (filename, &statbuf) < 0) {
1759 _wapi_set_last_path_error_from_errno (NULL, filename);
1764 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1765 &shareinfo) == FALSE) {
1766 SetLastError (ERROR_SHARING_VIOLATION);
1771 _wapi_handle_share_release (shareinfo);
1774 retval = _wapi_unlink (filename);
1777 _wapi_set_last_path_error_from_errno (NULL, filename);
1789 * @name: a pointer to a NULL-terminated unicode string, that names
1790 * the file to be moved.
1791 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1792 * new name for the file.
1794 * Renames file @name to @dest_name.
1795 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1796 * when it is the same file as the source. In that case it silently succeeds.
1798 * Return value: %TRUE on success, %FALSE otherwise.
1800 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1802 gchar *utf8_name, *utf8_dest_name;
1803 int result, errno_copy;
1804 struct stat stat_src, stat_dest;
1805 gboolean ret = FALSE;
1806 struct _WapiFileShare *shareinfo;
1810 g_message("%s: name is NULL", __func__);
1813 SetLastError (ERROR_INVALID_NAME);
1817 utf8_name = mono_unicode_to_external (name);
1818 if (utf8_name == NULL) {
1820 g_message ("%s: unicode conversion returned NULL", __func__);
1823 SetLastError (ERROR_INVALID_NAME);
1827 if(dest_name==NULL) {
1829 g_message("%s: name is NULL", __func__);
1833 SetLastError (ERROR_INVALID_NAME);
1837 utf8_dest_name = mono_unicode_to_external (dest_name);
1838 if (utf8_dest_name == NULL) {
1840 g_message ("%s: unicode conversion returned NULL", __func__);
1844 SetLastError (ERROR_INVALID_NAME);
1849 * In C# land we check for the existence of src, but not for dest.
1850 * We check it here and return the failure if dest exists and is not
1851 * the same file as src.
1853 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1854 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1855 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1857 g_free (utf8_dest_name);
1862 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1863 if (stat_dest.st_dev != stat_src.st_dev ||
1864 stat_dest.st_ino != stat_src.st_ino) {
1866 g_free (utf8_dest_name);
1867 SetLastError (ERROR_ALREADY_EXISTS);
1872 /* Check to make sure sharing allows us to open the file for
1873 * writing. See bug 377049.
1875 * Do the checks that don't need an open file descriptor, for
1876 * simplicity's sake. If we really have to do the full checks
1877 * then we can implement that later.
1879 if (share_allows_open (&stat_src, 0, GENERIC_WRITE,
1880 &shareinfo) == FALSE) {
1881 SetLastError (ERROR_SHARING_VIOLATION);
1885 _wapi_handle_share_release (shareinfo);
1887 result = _wapi_rename (utf8_name, utf8_dest_name);
1891 switch(errno_copy) {
1893 SetLastError (ERROR_ALREADY_EXISTS);
1897 /* Ignore here, it is dealt with below */
1901 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1906 g_free (utf8_dest_name);
1908 if (result != 0 && errno_copy == EXDEV) {
1909 if (S_ISDIR (stat_src.st_mode)) {
1910 SetLastError (ERROR_NOT_SAME_DEVICE);
1913 /* Try a copy to the new location, and delete the source */
1914 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1915 /* CopyFile will set the error */
1919 return(DeleteFile (name));
1930 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1934 int buf_size = st_src->st_blksize;
1936 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1937 buf = (char *) malloc (buf_size);
1940 remain = read (src_fd, buf, buf_size);
1942 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1946 _wapi_set_last_error_from_errno ();
1956 while (remain > 0) {
1957 if ((n = write (dest_fd, wbuf, remain)) < 0) {
1958 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1962 _wapi_set_last_error_from_errno ();
1964 g_message ("%s: write failed.", __func__);
1981 * @name: a pointer to a NULL-terminated unicode string, that names
1982 * the file to be copied.
1983 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1984 * new name for the file.
1985 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1987 * Copies file @name to @dest_name
1989 * Return value: %TRUE on success, %FALSE otherwise.
1991 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1992 gboolean fail_if_exists)
1994 gchar *utf8_src, *utf8_dest;
1995 int src_fd, dest_fd;
1996 struct stat st, dest_st;
1997 gboolean ret = TRUE;
2001 g_message("%s: name is NULL", __func__);
2004 SetLastError (ERROR_INVALID_NAME);
2008 utf8_src = mono_unicode_to_external (name);
2009 if (utf8_src == NULL) {
2011 g_message ("%s: unicode conversion of source returned NULL",
2015 SetLastError (ERROR_INVALID_PARAMETER);
2019 if(dest_name==NULL) {
2021 g_message("%s: dest is NULL", __func__);
2025 SetLastError (ERROR_INVALID_NAME);
2029 utf8_dest = mono_unicode_to_external (dest_name);
2030 if (utf8_dest == NULL) {
2032 g_message ("%s: unicode conversion of dest returned NULL",
2036 SetLastError (ERROR_INVALID_PARAMETER);
2043 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2045 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2053 if (fstat (src_fd, &st) < 0) {
2054 _wapi_set_last_error_from_errno ();
2063 /* Before trying to open/create the dest, we need to report a 'file busy'
2064 * error if src and dest are actually the same file. We do the check here to take
2065 * advantage of the IOMAP capability */
2066 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
2067 st.st_ino == dest_st.st_ino) {
2073 SetLastError (ERROR_SHARING_VIOLATION);
2077 if (fail_if_exists) {
2078 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2080 /* FIXME: it kinda sucks that this code path potentially scans
2081 * the directory twice due to the weird SetLastError()
2083 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2085 /* The file does not exist, try creating it */
2086 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2088 /* Apparently this error is set if we
2089 * overwrite the dest file
2091 SetLastError (ERROR_ALREADY_EXISTS);
2095 _wapi_set_last_error_from_errno ();
2104 if (!write_file (src_fd, dest_fd, &st, TRUE))
2116 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2122 g_message ("%s: %s is NULL", __func__, arg_name);
2124 SetLastError (ERROR_INVALID_NAME);
2128 utf8_ret = mono_unicode_to_external (arg);
2129 if (utf8_ret == NULL) {
2131 g_message ("%s: unicode conversion of %s returned NULL",
2132 __func__, arg_name);
2134 SetLastError (ERROR_INVALID_PARAMETER);
2142 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2143 const gunichar2 *backupFileName, guint32 replaceFlags,
2144 gpointer exclude, gpointer reserved)
2146 int result, errno_copy, backup_fd = -1,replaced_fd = -1;
2147 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2148 struct stat stBackup;
2149 gboolean ret = FALSE;
2151 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2153 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2154 goto replace_cleanup;
2155 if (backupFileName != NULL) {
2156 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2157 goto replace_cleanup;
2160 if (utf8_backupFileName) {
2161 // Open the backup file for read so we can restore the file if an error occurs.
2162 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2163 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2166 goto replace_cleanup;
2169 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2172 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2173 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2174 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2175 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2178 if (replaced_fd == -1)
2179 goto replace_cleanup;
2181 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2184 goto replace_cleanup;
2190 g_free (utf8_replacedFileName);
2191 g_free (utf8_replacementFileName);
2192 g_free (utf8_backupFileName);
2193 if (backup_fd != -1)
2195 if (replaced_fd != -1)
2196 close (replaced_fd);
2202 * @stdhandle: specifies the file descriptor
2204 * Returns a handle for stdin, stdout, or stderr. Always returns the
2205 * same handle for the same @stdhandle.
2207 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2210 static mono_mutex_t stdhandle_mutex = MONO_MUTEX_INITIALIZER;
2212 gpointer GetStdHandle(WapiStdHandle stdhandle)
2214 struct _WapiHandle_file *file_handle;
2221 case STD_INPUT_HANDLE:
2226 case STD_OUTPUT_HANDLE:
2231 case STD_ERROR_HANDLE:
2238 g_message("%s: unknown standard handle type", __func__);
2241 SetLastError (ERROR_INVALID_PARAMETER);
2242 return(INVALID_HANDLE_VALUE);
2245 handle = GINT_TO_POINTER (fd);
2247 pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2248 (void *)&stdhandle_mutex);
2249 thr_ret = mono_mutex_lock (&stdhandle_mutex);
2250 g_assert (thr_ret == 0);
2252 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2253 (gpointer *)&file_handle);
2255 /* Need to create this console handle */
2256 handle = _wapi_stdhandle_create (fd, name);
2258 if (handle == INVALID_HANDLE_VALUE) {
2259 SetLastError (ERROR_NO_MORE_FILES);
2263 /* Add a reference to this handle */
2264 _wapi_handle_ref (handle);
2268 thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2269 g_assert (thr_ret == 0);
2270 pthread_cleanup_pop (0);
2277 * @handle: The file handle to read from. The handle must have
2278 * %GENERIC_READ access.
2279 * @buffer: The buffer to store read data in
2280 * @numbytes: The maximum number of bytes to read
2281 * @bytesread: The actual number of bytes read is stored here. This
2282 * value can be zero if the handle is positioned at the end of the
2284 * @overlapped: points to a required %WapiOverlapped structure if
2285 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2288 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2289 * function reads up to @numbytes bytes from the file from the current
2290 * file position, and stores them in @buffer. If there are not enough
2291 * bytes left in the file, just the amount available will be read.
2292 * The actual number of bytes read is stored in @bytesread.
2294 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2295 * file position is ignored and the read position is taken from data
2296 * in the @overlapped structure.
2298 * Return value: %TRUE if the read succeeds (even if no bytes were
2299 * read due to an attempt to read past the end of the file), %FALSE on
2302 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2303 guint32 *bytesread, WapiOverlapped *overlapped)
2305 WapiHandleType type;
2307 type = _wapi_handle_type (handle);
2309 if(io_ops[type].readfile==NULL) {
2310 SetLastError (ERROR_INVALID_HANDLE);
2314 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2320 * @handle: The file handle to write to. The handle must have
2321 * %GENERIC_WRITE access.
2322 * @buffer: The buffer to read data from.
2323 * @numbytes: The maximum number of bytes to write.
2324 * @byteswritten: The actual number of bytes written is stored here.
2325 * If the handle is positioned at the file end, the length of the file
2326 * is extended. This parameter may be %NULL.
2327 * @overlapped: points to a required %WapiOverlapped structure if
2328 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2331 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2332 * function writes up to @numbytes bytes from @buffer to the file at
2333 * the current file position. If @handle is positioned at the end of
2334 * the file, the file is extended. The actual number of bytes written
2335 * is stored in @byteswritten.
2337 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2338 * file position is ignored and the write position is taken from data
2339 * in the @overlapped structure.
2341 * Return value: %TRUE if the write succeeds, %FALSE on error.
2343 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2344 guint32 *byteswritten, WapiOverlapped *overlapped)
2346 WapiHandleType type;
2348 type = _wapi_handle_type (handle);
2350 if(io_ops[type].writefile==NULL) {
2351 SetLastError (ERROR_INVALID_HANDLE);
2355 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2361 * @handle: Handle to open file. The handle must have
2362 * %GENERIC_WRITE access.
2364 * Flushes buffers of the file and causes all unwritten data to
2367 * Return value: %TRUE on success, %FALSE otherwise.
2369 gboolean FlushFileBuffers(gpointer handle)
2371 WapiHandleType type;
2373 type = _wapi_handle_type (handle);
2375 if(io_ops[type].flushfile==NULL) {
2376 SetLastError (ERROR_INVALID_HANDLE);
2380 return(io_ops[type].flushfile (handle));
2385 * @handle: The file handle to set. The handle must have
2386 * %GENERIC_WRITE access.
2388 * Moves the end-of-file position to the current position of the file
2389 * pointer. This function is used to truncate or extend a file.
2391 * Return value: %TRUE on success, %FALSE otherwise.
2393 gboolean SetEndOfFile(gpointer handle)
2395 WapiHandleType type;
2397 type = _wapi_handle_type (handle);
2399 if (io_ops[type].setendoffile == NULL) {
2400 SetLastError (ERROR_INVALID_HANDLE);
2404 return(io_ops[type].setendoffile (handle));
2409 * @handle: The file handle to set. The handle must have
2410 * %GENERIC_READ or %GENERIC_WRITE access.
2411 * @movedistance: Low 32 bits of a signed value that specifies the
2412 * number of bytes to move the file pointer.
2413 * @highmovedistance: Pointer to the high 32 bits of a signed value
2414 * that specifies the number of bytes to move the file pointer, or
2416 * @method: The starting point for the file pointer move.
2418 * Sets the file pointer of an open file.
2420 * The distance to move the file pointer is calculated from
2421 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2422 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2423 * is the low 32 bits and @highmovedistance a pointer to the high 32
2424 * bits of a 64 bit signed value. A positive distance moves the file
2425 * pointer forward from the position specified by @method; a negative
2426 * distance moves the file pointer backward.
2428 * If the library is compiled without large file support,
2429 * @highmovedistance is ignored and its value is set to zero on a
2430 * successful return.
2432 * Return value: On success, the low 32 bits of the new file pointer.
2433 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2434 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2436 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2437 gint32 *highmovedistance, WapiSeekMethod method)
2439 WapiHandleType type;
2441 type = _wapi_handle_type (handle);
2443 if (io_ops[type].seek == NULL) {
2444 SetLastError (ERROR_INVALID_HANDLE);
2445 return(INVALID_SET_FILE_POINTER);
2448 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2454 * @handle: The file handle to test.
2456 * Finds the type of file @handle.
2458 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2459 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2460 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2461 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2463 WapiFileType GetFileType(gpointer handle)
2465 WapiHandleType type;
2467 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2468 SetLastError (ERROR_INVALID_HANDLE);
2469 return(FILE_TYPE_UNKNOWN);
2472 type = _wapi_handle_type (handle);
2474 if (io_ops[type].getfiletype == NULL) {
2475 SetLastError (ERROR_INVALID_HANDLE);
2476 return(FILE_TYPE_UNKNOWN);
2479 return(io_ops[type].getfiletype ());
2484 * @handle: The file handle to query. The handle must have
2485 * %GENERIC_READ or %GENERIC_WRITE access.
2486 * @highsize: If non-%NULL, the high 32 bits of the file size are
2489 * Retrieves the size of the file @handle.
2491 * If the library is compiled without large file support, @highsize
2492 * has its value set to zero on a successful return.
2494 * Return value: On success, the low 32 bits of the file size. If
2495 * @highsize is non-%NULL then the high 32 bits of the file size are
2496 * stored here. On failure %INVALID_FILE_SIZE is returned.
2498 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2500 WapiHandleType type;
2502 type = _wapi_handle_type (handle);
2504 if (io_ops[type].getfilesize == NULL) {
2505 SetLastError (ERROR_INVALID_HANDLE);
2506 return(INVALID_FILE_SIZE);
2509 return(io_ops[type].getfilesize (handle, highsize));
2514 * @handle: The file handle to query. The handle must have
2515 * %GENERIC_READ access.
2516 * @create_time: Points to a %WapiFileTime structure to receive the
2517 * number of ticks since the epoch that file was created. May be
2519 * @last_access: Points to a %WapiFileTime structure to receive the
2520 * number of ticks since the epoch when file was last accessed. May be
2522 * @last_write: Points to a %WapiFileTime structure to receive the
2523 * number of ticks since the epoch when file was last written to. May
2526 * Finds the number of ticks since the epoch that the file referenced
2527 * by @handle was created, last accessed and last modified. A tick is
2528 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2531 * Create time isn't recorded on POSIX file systems or reported by
2532 * stat(2), so that time is guessed by returning the oldest of the
2535 * Return value: %TRUE on success, %FALSE otherwise.
2537 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2538 WapiFileTime *last_access, WapiFileTime *last_write)
2540 WapiHandleType type;
2542 type = _wapi_handle_type (handle);
2544 if (io_ops[type].getfiletime == NULL) {
2545 SetLastError (ERROR_INVALID_HANDLE);
2549 return(io_ops[type].getfiletime (handle, create_time, last_access,
2555 * @handle: The file handle to set. The handle must have
2556 * %GENERIC_WRITE access.
2557 * @create_time: Points to a %WapiFileTime structure that contains the
2558 * number of ticks since the epoch that the file was created. May be
2560 * @last_access: Points to a %WapiFileTime structure that contains the
2561 * number of ticks since the epoch when the file was last accessed.
2563 * @last_write: Points to a %WapiFileTime structure that contains the
2564 * number of ticks since the epoch when the file was last written to.
2567 * Sets the number of ticks since the epoch that the file referenced
2568 * by @handle was created, last accessed or last modified. A tick is
2569 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2572 * Create time isn't recorded on POSIX file systems, and is ignored.
2574 * Return value: %TRUE on success, %FALSE otherwise.
2576 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2577 const WapiFileTime *last_access,
2578 const WapiFileTime *last_write)
2580 WapiHandleType type;
2582 type = _wapi_handle_type (handle);
2584 if (io_ops[type].setfiletime == NULL) {
2585 SetLastError (ERROR_INVALID_HANDLE);
2589 return(io_ops[type].setfiletime (handle, create_time, last_access,
2593 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2594 * January 1 1601 GMT
2597 #define TICKS_PER_MILLISECOND 10000L
2598 #define TICKS_PER_SECOND 10000000L
2599 #define TICKS_PER_MINUTE 600000000L
2600 #define TICKS_PER_HOUR 36000000000LL
2601 #define TICKS_PER_DAY 864000000000LL
2603 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2605 static const guint16 mon_yday[2][13]={
2606 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2607 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2611 * FileTimeToSystemTime:
2612 * @file_time: Points to a %WapiFileTime structure that contains the
2613 * number of ticks to convert.
2614 * @system_time: Points to a %WapiSystemTime structure to receive the
2617 * Converts a tick count into broken-out time values.
2619 * Return value: %TRUE on success, %FALSE otherwise.
2621 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2622 WapiSystemTime *system_time)
2624 gint64 file_ticks, totaldays, rem, y;
2627 if(system_time==NULL) {
2629 g_message("%s: system_time NULL", __func__);
2632 SetLastError (ERROR_INVALID_PARAMETER);
2636 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2637 file_time->dwLowDateTime;
2639 /* Really compares if file_ticks>=0x8000000000000000
2640 * (LLONG_MAX+1) but we're working with a signed value for the
2641 * year and day calculation to work later
2645 g_message("%s: file_time too big", __func__);
2648 SetLastError (ERROR_INVALID_PARAMETER);
2652 totaldays=(file_ticks / TICKS_PER_DAY);
2653 rem = file_ticks % TICKS_PER_DAY;
2655 g_message("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2658 system_time->wHour=rem/TICKS_PER_HOUR;
2659 rem %= TICKS_PER_HOUR;
2661 g_message("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2664 system_time->wMinute = rem / TICKS_PER_MINUTE;
2665 rem %= TICKS_PER_MINUTE;
2667 g_message("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2671 system_time->wSecond = rem / TICKS_PER_SECOND;
2672 rem %= TICKS_PER_SECOND;
2674 g_message("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2678 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2680 g_message("%s: Milliseconds: %d", __func__,
2681 system_time->wMilliseconds);
2684 /* January 1, 1601 was a Monday, according to Emacs calendar */
2685 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2687 g_message("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2690 /* This algorithm to find year and month given days from epoch
2695 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2696 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2698 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2699 /* Guess a corrected year, assuming 365 days per year */
2700 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2702 g_message("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2705 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2706 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2709 /* Adjust days and y to match the guessed year. */
2710 totaldays -= ((yg - y) * 365
2711 + LEAPS_THRU_END_OF (yg - 1)
2712 - LEAPS_THRU_END_OF (y - 1));
2714 g_message("%s: totaldays: %lld", __func__, totaldays);
2718 g_message("%s: y: %lld", __func__, y);
2722 system_time->wYear = y;
2724 g_message("%s: Year: %d", __func__, system_time->wYear);
2727 ip = mon_yday[isleap(y)];
2729 for(y=11; totaldays < ip[y]; --y) {
2734 g_message("%s: totaldays: %lld", __func__, totaldays);
2737 system_time->wMonth = y + 1;
2739 g_message("%s: Month: %d", __func__, system_time->wMonth);
2742 system_time->wDay = totaldays + 1;
2744 g_message("%s: Day: %d", __func__, system_time->wDay);
2750 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2752 struct _WapiHandle_find find_handle = {0};
2754 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2757 if (pattern == NULL) {
2759 g_message ("%s: pattern is NULL", __func__);
2762 SetLastError (ERROR_PATH_NOT_FOUND);
2763 return(INVALID_HANDLE_VALUE);
2766 utf8_pattern = mono_unicode_to_external (pattern);
2767 if (utf8_pattern == NULL) {
2769 g_message ("%s: unicode conversion returned NULL", __func__);
2772 SetLastError (ERROR_INVALID_NAME);
2773 return(INVALID_HANDLE_VALUE);
2777 g_message ("%s: looking for [%s]", __func__, utf8_pattern);
2780 /* Figure out which bit of the pattern is the directory */
2781 dir_part = _wapi_dirname (utf8_pattern);
2782 entry_part = _wapi_basename (utf8_pattern);
2785 /* Don't do this check for now, it breaks if directories
2786 * really do have metachars in their names (see bug 58116).
2787 * FIXME: Figure out a better solution to keep some checks...
2789 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2790 SetLastError (ERROR_INVALID_NAME);
2792 g_free (entry_part);
2793 g_free (utf8_pattern);
2794 return(INVALID_HANDLE_VALUE);
2798 /* The pattern can specify a directory or a set of files.
2800 * The pattern can have wildcard characters ? and *, but only
2801 * in the section after the last directory delimiter. (Return
2802 * ERROR_INVALID_NAME if there are wildcards in earlier path
2803 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2804 * means "match one character", "??" seems to mean "match one
2805 * or two characters", "???" seems to mean "match one, two or
2806 * three characters", etc. Windows will also try and match
2807 * the mangled "short name" of files, so 8 character patterns
2808 * with wildcards will show some surprising results.
2810 * All the written documentation I can find says that '?'
2811 * should only match one character, and doesn't mention '??',
2812 * '???' etc. I'm going to assume that the strict behaviour
2813 * (ie '???' means three and only three characters) is the
2814 * correct one, because that lets me use fnmatch(3) rather
2815 * than mess around with regexes.
2818 find_handle.namelist = NULL;
2819 result = _wapi_io_scandir (dir_part, entry_part,
2820 &find_handle.namelist);
2823 /* No files, which windows seems to call
2826 SetLastError (ERROR_FILE_NOT_FOUND);
2827 g_free (utf8_pattern);
2828 g_free (entry_part);
2830 return (INVALID_HANDLE_VALUE);
2835 gint errnum = errno;
2837 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2839 g_message ("%s: scandir error: %s", __func__,
2840 g_strerror (errnum));
2842 g_free (utf8_pattern);
2843 g_free (entry_part);
2845 return (INVALID_HANDLE_VALUE);
2848 g_free (utf8_pattern);
2849 g_free (entry_part);
2852 g_message ("%s: Got %d matches", __func__, result);
2855 find_handle.dir_part = dir_part;
2856 find_handle.num = result;
2857 find_handle.count = 0;
2859 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2860 if (handle == _WAPI_HANDLE_INVALID) {
2861 g_warning ("%s: error creating find handle", __func__);
2863 g_free (entry_part);
2864 g_free (utf8_pattern);
2865 SetLastError (ERROR_GEN_FAILURE);
2867 return(INVALID_HANDLE_VALUE);
2870 if (handle != INVALID_HANDLE_VALUE &&
2871 !FindNextFile (handle, find_data)) {
2873 SetLastError (ERROR_NO_MORE_FILES);
2874 handle = INVALID_HANDLE_VALUE;
2880 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2882 struct _WapiHandle_find *find_handle;
2884 struct stat buf, linkbuf;
2887 gchar *utf8_filename, *utf8_basename;
2888 gunichar2 *utf16_basename;
2892 gboolean ret = FALSE;
2894 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2895 (gpointer *)&find_handle);
2897 g_warning ("%s: error looking up find handle %p", __func__,
2899 SetLastError (ERROR_INVALID_HANDLE);
2903 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2905 thr_ret = _wapi_handle_lock_handle (handle);
2906 g_assert (thr_ret == 0);
2909 if (find_handle->count >= find_handle->num) {
2910 SetLastError (ERROR_NO_MORE_FILES);
2914 /* stat next match */
2916 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2918 result = _wapi_stat (filename, &buf);
2919 if (result == -1 && errno == ENOENT) {
2920 /* Might be a dangling symlink */
2921 result = _wapi_lstat (filename, &buf);
2926 g_message ("%s: stat failed: %s", __func__, filename);
2933 result = _wapi_lstat (filename, &linkbuf);
2936 g_message ("%s: lstat failed: %s", __func__, filename);
2943 utf8_filename = mono_utf8_from_external (filename);
2944 if (utf8_filename == NULL) {
2945 /* We couldn't turn this filename into utf8 (eg the
2946 * encoding of the name wasn't convertible), so just
2949 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2957 g_message ("%s: Found [%s]", __func__, utf8_filename);
2960 /* fill data block */
2962 if (buf.st_mtime < buf.st_ctime)
2963 create_time = buf.st_mtime;
2965 create_time = buf.st_ctime;
2967 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2969 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2970 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2971 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2973 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2974 find_data->nFileSizeHigh = 0;
2975 find_data->nFileSizeLow = 0;
2977 find_data->nFileSizeHigh = buf.st_size >> 32;
2978 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2981 find_data->dwReserved0 = 0;
2982 find_data->dwReserved1 = 0;
2984 utf8_basename = _wapi_basename (utf8_filename);
2985 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2987 if(utf16_basename==NULL) {
2988 g_free (utf8_basename);
2989 g_free (utf8_filename);
2994 /* utf16 is 2 * utf8 */
2997 memset (find_data->cFileName, '\0', (MAX_PATH*2));
2999 /* Truncating a utf16 string like this might leave the last
3002 memcpy (find_data->cFileName, utf16_basename,
3003 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3005 find_data->cAlternateFileName [0] = 0; /* not used */
3007 g_free (utf8_basename);
3008 g_free (utf8_filename);
3009 g_free (utf16_basename);
3012 thr_ret = _wapi_handle_unlock_handle (handle);
3013 g_assert (thr_ret == 0);
3014 pthread_cleanup_pop (0);
3021 * @wapi_handle: the find handle to close.
3023 * Closes find handle @wapi_handle
3025 * Return value: %TRUE on success, %FALSE otherwise.
3027 gboolean FindClose (gpointer handle)
3029 struct _WapiHandle_find *find_handle;
3033 if (handle == NULL) {
3034 SetLastError (ERROR_INVALID_HANDLE);
3038 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
3039 (gpointer *)&find_handle);
3041 g_warning ("%s: error looking up find handle %p", __func__,
3043 SetLastError (ERROR_INVALID_HANDLE);
3047 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
3049 thr_ret = _wapi_handle_lock_handle (handle);
3050 g_assert (thr_ret == 0);
3052 g_strfreev (find_handle->namelist);
3053 g_free (find_handle->dir_part);
3055 thr_ret = _wapi_handle_unlock_handle (handle);
3056 g_assert (thr_ret == 0);
3057 pthread_cleanup_pop (0);
3059 _wapi_handle_unref (handle);
3066 * @name: a pointer to a NULL-terminated unicode string, that names
3067 * the directory to be created.
3068 * @security: ignored for now
3070 * Creates directory @name
3072 * Return value: %TRUE on success, %FALSE otherwise.
3074 gboolean CreateDirectory (const gunichar2 *name,
3075 WapiSecurityAttributes *security)
3082 g_message("%s: name is NULL", __func__);
3085 SetLastError (ERROR_INVALID_NAME);
3089 utf8_name = mono_unicode_to_external (name);
3090 if (utf8_name == NULL) {
3092 g_message ("%s: unicode conversion returned NULL", __func__);
3095 SetLastError (ERROR_INVALID_NAME);
3099 result = _wapi_mkdir (utf8_name, 0777);
3106 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3113 * @name: a pointer to a NULL-terminated unicode string, that names
3114 * the directory to be removed.
3116 * Removes directory @name
3118 * Return value: %TRUE on success, %FALSE otherwise.
3120 gboolean RemoveDirectory (const gunichar2 *name)
3127 g_message("%s: name is NULL", __func__);
3130 SetLastError (ERROR_INVALID_NAME);
3134 utf8_name = mono_unicode_to_external (name);
3135 if (utf8_name == NULL) {
3137 g_message ("%s: unicode conversion returned NULL", __func__);
3140 SetLastError (ERROR_INVALID_NAME);
3144 result = _wapi_rmdir (utf8_name);
3146 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3157 * GetFileAttributes:
3158 * @name: a pointer to a NULL-terminated unicode filename.
3160 * Gets the attributes for @name;
3162 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3164 guint32 GetFileAttributes (const gunichar2 *name)
3167 struct stat buf, linkbuf;
3173 g_message("%s: name is NULL", __func__);
3176 SetLastError (ERROR_INVALID_NAME);
3180 utf8_name = mono_unicode_to_external (name);
3181 if (utf8_name == NULL) {
3183 g_message ("%s: unicode conversion returned NULL", __func__);
3186 SetLastError (ERROR_INVALID_PARAMETER);
3187 return (INVALID_FILE_ATTRIBUTES);
3190 result = _wapi_stat (utf8_name, &buf);
3191 if (result == -1 && errno == ENOENT) {
3192 /* Might be a dangling symlink... */
3193 result = _wapi_lstat (utf8_name, &buf);
3197 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3199 return (INVALID_FILE_ATTRIBUTES);
3202 result = _wapi_lstat (utf8_name, &linkbuf);
3204 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3206 return (INVALID_FILE_ATTRIBUTES);
3209 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3217 * GetFileAttributesEx:
3218 * @name: a pointer to a NULL-terminated unicode filename.
3219 * @level: must be GetFileExInfoStandard
3220 * @info: pointer to a WapiFileAttributesData structure
3222 * Gets attributes, size and filetimes for @name;
3224 * Return value: %TRUE on success, %FALSE on failure
3226 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3229 WapiFileAttributesData *data;
3231 struct stat buf, linkbuf;
3235 if (level != GetFileExInfoStandard) {
3237 g_message ("%s: info level %d not supported.", __func__,
3241 SetLastError (ERROR_INVALID_PARAMETER);
3247 g_message("%s: name is NULL", __func__);
3250 SetLastError (ERROR_INVALID_NAME);
3254 utf8_name = mono_unicode_to_external (name);
3255 if (utf8_name == NULL) {
3257 g_message ("%s: unicode conversion returned NULL", __func__);
3260 SetLastError (ERROR_INVALID_PARAMETER);
3264 result = _wapi_stat (utf8_name, &buf);
3265 if (result == -1 && errno == ENOENT) {
3266 /* Might be a dangling symlink... */
3267 result = _wapi_lstat (utf8_name, &buf);
3271 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3276 result = _wapi_lstat (utf8_name, &linkbuf);
3278 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3283 /* fill data block */
3285 data = (WapiFileAttributesData *)info;
3287 if (buf.st_mtime < buf.st_ctime)
3288 create_time = buf.st_mtime;
3290 create_time = buf.st_ctime;
3292 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3298 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3299 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3300 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3302 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3303 data->nFileSizeHigh = 0;
3304 data->nFileSizeLow = 0;
3307 data->nFileSizeHigh = buf.st_size >> 32;
3308 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3316 * @name: name of file
3317 * @attrs: attributes to set
3319 * Changes the attributes on a named file.
3321 * Return value: %TRUE on success, %FALSE on failure.
3323 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3325 /* FIXME: think of something clever to do on unix */
3331 * Currently we only handle one *internal* case, with a value that is
3332 * not standard: 0x80000000, which means `set executable bit'
3337 g_message("%s: name is NULL", __func__);
3340 SetLastError (ERROR_INVALID_NAME);
3344 utf8_name = mono_unicode_to_external (name);
3345 if (utf8_name == NULL) {
3347 g_message ("%s: unicode conversion returned NULL", __func__);
3350 SetLastError (ERROR_INVALID_NAME);
3354 result = _wapi_stat (utf8_name, &buf);
3356 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3361 /* Contrary to the documentation, ms allows NORMAL to be
3362 * specified along with other attributes, so dont bother to
3363 * catch that case here.
3365 if (attrs & FILE_ATTRIBUTE_READONLY) {
3366 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3368 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3371 /* Ignore the other attributes for now */
3373 if (attrs & 0x80000000){
3374 mode_t exec_mask = 0;
3376 if ((buf.st_mode & S_IRUSR) != 0)
3377 exec_mask |= S_IXUSR;
3379 if ((buf.st_mode & S_IRGRP) != 0)
3380 exec_mask |= S_IXGRP;
3382 if ((buf.st_mode & S_IROTH) != 0)
3383 exec_mask |= S_IXOTH;
3385 result = chmod (utf8_name, buf.st_mode | exec_mask);
3387 /* Don't bother to reset executable (might need to change this
3397 * GetCurrentDirectory
3398 * @length: size of the buffer
3399 * @buffer: pointer to buffer that recieves path
3401 * Retrieves the current directory for the current process.
3403 * Return value: number of characters in buffer on success, zero on failure
3405 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3407 gunichar2 *utf16_path;
3411 if (getcwd ((char*)buffer, length) == NULL) {
3412 if (errno == ERANGE) { /*buffer length is not big enough */
3413 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*/
3416 utf16_path = mono_unicode_from_external (path, &bytes);
3417 g_free (utf16_path);
3421 _wapi_set_last_error_from_errno ();
3425 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3426 count = (bytes/2)+1;
3427 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3429 /* Add the terminator */
3430 memset (buffer, '\0', bytes+2);
3431 memcpy (buffer, utf16_path, bytes);
3433 g_free (utf16_path);
3439 * SetCurrentDirectory
3440 * @path: path to new directory
3442 * Changes the directory path for the current process.
3444 * Return value: %TRUE on success, %FALSE on failure.
3446 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3452 SetLastError (ERROR_INVALID_PARAMETER);
3456 utf8_path = mono_unicode_to_external (path);
3457 if (_wapi_chdir (utf8_path) != 0) {
3458 _wapi_set_last_error_from_errno ();
3468 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3469 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3471 struct _WapiHandle_file pipe_read_handle = {0};
3472 struct _WapiHandle_file pipe_write_handle = {0};
3473 gpointer read_handle;
3474 gpointer write_handle;
3478 mono_once (&io_ops_once, io_ops_init);
3481 g_message ("%s: Creating pipe", __func__);
3487 g_message ("%s: Error creating pipe: %s", __func__,
3491 _wapi_set_last_error_from_errno ();
3495 if (filedes[0] >= _wapi_fd_reserve ||
3496 filedes[1] >= _wapi_fd_reserve) {
3498 g_message ("%s: File descriptor is too big", __func__);
3501 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3509 /* filedes[0] is open for reading, filedes[1] for writing */
3511 pipe_read_handle.fileaccess = GENERIC_READ;
3512 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3514 if (read_handle == _WAPI_HANDLE_INVALID) {
3515 g_warning ("%s: error creating pipe read handle", __func__);
3518 SetLastError (ERROR_GEN_FAILURE);
3523 pipe_write_handle.fileaccess = GENERIC_WRITE;
3524 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3525 &pipe_write_handle);
3526 if (write_handle == _WAPI_HANDLE_INVALID) {
3527 g_warning ("%s: error creating pipe write handle", __func__);
3528 _wapi_handle_unref (read_handle);
3532 SetLastError (ERROR_GEN_FAILURE);
3537 *readpipe = read_handle;
3538 *writepipe = write_handle;
3541 g_message ("%s: Returning pipe: read handle %p, write handle %p",
3542 __func__, read_handle, write_handle);
3548 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3550 gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3551 gunichar2 *tmpdir16=NULL;
3556 if(tmpdir[strlen (tmpdir)]!='/') {
3558 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3561 tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3562 if(tmpdir16==NULL) {
3570 g_message ("%s: Size %d smaller than needed (%ld)",
3571 __func__, len, dirlen+1);
3576 /* Add the terminator */
3577 memset (buf, '\0', bytes+2);
3578 memcpy (buf, tmpdir16, bytes);
3584 if(tmpdir16!=NULL) {
3592 #ifdef HAVE_GETFSSTAT
3593 /* Darwin has getfsstat */
3594 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3596 struct statfs *stats;
3599 glong length, total = 0;
3601 n = getfsstat (NULL, 0, MNT_NOWAIT);
3604 size = n * sizeof (struct statfs);
3605 stats = (struct statfs *) g_malloc (size);
3608 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3612 for (i = 0; i < n; i++){
3613 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3614 if (total + length < len){
3615 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3616 buf [total+length] = 0;
3619 total += length + 1;
3628 /* In-place octal sequence replacement */
3630 unescape_octal (gchar *str)
3639 while (*rptr != '\0') {
3640 if (*rptr == '\\') {
3643 c = (*(rptr++) - '0') << 6;
3644 c += (*(rptr++) - '0') << 3;
3645 c += *(rptr++) - '0';
3647 } else if (wptr != rptr) {
3657 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3660 gunichar2 *ptr, *dir;
3661 glong length, total = 0;
3665 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3670 /* Sigh, mntent and friends don't work well.
3671 * It stops on the first line that doesn't begin with a '/'.
3672 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3673 fp = fopen ("/etc/mtab", "rt");
3675 fp = fopen ("/etc/mnttab", "rt");
3681 while (fgets (buffer, 512, fp) != NULL) {
3685 splitted = g_strsplit (buffer, " ", 0);
3686 if (!*splitted || !*(splitted + 1)) {
3687 g_strfreev (splitted);
3691 unescape_octal (*(splitted + 1));
3692 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3693 g_strfreev (splitted);
3694 if (total + length + 1 > len) {
3697 return len * 2; /* guess */
3700 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3702 total += length + 1;
3707 /* Commented out, does not work with my mtab!!! - Gonz */
3708 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3712 gunichar2 *ptr, *dir;
3713 glong len, total = 0;
3716 fp = setmntent ("/etc/mtab", "rt");
3718 fp = setmntent ("/etc/mnttab", "rt");
3724 while ((mnt = getmntent (fp)) != NULL) {
3725 g_print ("GOT %s\n", mnt->mnt_dir);
3726 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3727 if (total + len + 1 > len) {
3728 return len * 2; /* guess */
3731 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3743 #if (defined(HAVE_STATVFS) || defined(HAVE_STATFS)) && !defined(PLATFORM_ANDROID)
3744 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3745 WapiULargeInteger *total_number_of_bytes,
3746 WapiULargeInteger *total_number_of_free_bytes)
3749 struct statvfs fsstat;
3750 #elif defined(HAVE_STATFS)
3751 struct statfs fsstat;
3753 gboolean isreadonly;
3754 gchar *utf8_path_name;
3756 unsigned long block_size;
3758 if (path_name == NULL) {
3759 utf8_path_name = g_strdup (g_get_current_dir());
3760 if (utf8_path_name == NULL) {
3761 SetLastError (ERROR_DIRECTORY);
3766 utf8_path_name = mono_unicode_to_external (path_name);
3767 if (utf8_path_name == NULL) {
3769 g_message("%s: unicode conversion returned NULL", __func__);
3772 SetLastError (ERROR_INVALID_NAME);
3779 ret = statvfs (utf8_path_name, &fsstat);
3780 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
3781 block_size = fsstat.f_frsize;
3782 #elif defined(HAVE_STATFS)
3783 ret = statfs (utf8_path_name, &fsstat);
3784 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
3785 block_size = fsstat.f_bsize;
3787 } while(ret == -1 && errno == EINTR);
3789 g_free(utf8_path_name);
3792 _wapi_set_last_error_from_errno ();
3794 g_message ("%s: statvfs failed: %s", __func__, strerror (errno));
3799 /* total number of free bytes for non-root */
3800 if (free_bytes_avail != NULL) {
3802 free_bytes_avail->QuadPart = 0;
3805 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
3809 /* total number of bytes available for non-root */
3810 if (total_number_of_bytes != NULL) {
3811 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
3814 /* total number of bytes available for root */
3815 if (total_number_of_free_bytes != NULL) {
3817 total_number_of_free_bytes->QuadPart = 0;
3820 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
3827 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3828 WapiULargeInteger *total_number_of_bytes,
3829 WapiULargeInteger *total_number_of_free_bytes)
3831 if (free_bytes_avail != NULL) {
3832 free_bytes_avail->QuadPart = (guint64) -1;
3835 if (total_number_of_bytes != NULL) {
3836 total_number_of_bytes->QuadPart = (guint64) -1;
3839 if (total_number_of_free_bytes != NULL) {
3840 total_number_of_free_bytes->QuadPart = (guint64) -1;
3848 * General Unix support
3852 const gchar* fstype;
3855 static _wapi_drive_type _wapi_drive_types[] = {
3857 { DRIVE_REMOTE, "afp" },
3858 { DRIVE_REMOTE, "autofs" },
3859 { DRIVE_CDROM, "cddafs" },
3860 { DRIVE_CDROM, "cd9660" },
3861 { DRIVE_RAMDISK, "devfs" },
3862 { DRIVE_FIXED, "exfat" },
3863 { DRIVE_RAMDISK, "fdesc" },
3864 { DRIVE_REMOTE, "ftp" },
3865 { DRIVE_FIXED, "hfs" },
3866 { DRIVE_FIXED, "msdos" },
3867 { DRIVE_REMOTE, "nfs" },
3868 { DRIVE_FIXED, "ntfs" },
3869 { DRIVE_REMOTE, "smbfs" },
3870 { DRIVE_FIXED, "udf" },
3871 { DRIVE_REMOTE, "webdav" },
3873 { DRIVE_RAMDISK, "ramfs" },
3874 { DRIVE_RAMDISK, "tmpfs" },
3875 { DRIVE_RAMDISK, "proc" },
3876 { DRIVE_RAMDISK, "sysfs" },
3877 { DRIVE_RAMDISK, "debugfs" },
3878 { DRIVE_RAMDISK, "devpts" },
3879 { DRIVE_RAMDISK, "securityfs" },
3880 { DRIVE_CDROM, "iso9660" },
3881 { DRIVE_FIXED, "ext2" },
3882 { DRIVE_FIXED, "ext3" },
3883 { DRIVE_FIXED, "ext4" },
3884 { DRIVE_FIXED, "sysv" },
3885 { DRIVE_FIXED, "reiserfs" },
3886 { DRIVE_FIXED, "ufs" },
3887 { DRIVE_FIXED, "vfat" },
3888 { DRIVE_FIXED, "msdos" },
3889 { DRIVE_FIXED, "udf" },
3890 { DRIVE_FIXED, "hfs" },
3891 { DRIVE_FIXED, "hpfs" },
3892 { DRIVE_FIXED, "qnx4" },
3893 { DRIVE_FIXED, "ntfs" },
3894 { DRIVE_FIXED, "ntfs-3g" },
3895 { DRIVE_REMOTE, "smbfs" },
3896 { DRIVE_REMOTE, "fuse" },
3897 { DRIVE_REMOTE, "nfs" },
3898 { DRIVE_REMOTE, "nfs4" },
3899 { DRIVE_REMOTE, "cifs" },
3900 { DRIVE_REMOTE, "ncpfs" },
3901 { DRIVE_REMOTE, "coda" },
3902 { DRIVE_REMOTE, "afs" },
3904 { DRIVE_UNKNOWN, NULL }
3907 static guint32 _wapi_get_drive_type(const gchar* fstype)
3909 _wapi_drive_type *current;
3911 current = &_wapi_drive_types[0];
3912 while (current->drive_type != DRIVE_UNKNOWN) {
3913 if (strcmp (current->fstype, fstype) == 0)
3919 return current->drive_type;
3922 #if HAVE_SYS_MOUNT_H && !__linux__
3924 GetDriveTypeFromPath (const char *utf8_root_path_name)
3928 if (statfs (utf8_root_path_name, &buf) == -1)
3929 return DRIVE_UNKNOWN;
3930 return _wapi_get_drive_type (buf.f_fstypename);
3934 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
3941 fp = fopen ("/etc/mtab", "rt");
3943 fp = fopen ("/etc/mnttab", "rt");
3945 return(DRIVE_UNKNOWN);
3948 drive_type = DRIVE_NO_ROOT_DIR;
3949 while (fgets (buffer, 512, fp) != NULL) {
3950 splitted = g_strsplit (buffer, " ", 0);
3951 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
3952 g_strfreev (splitted);
3956 /* compare given root_path_name with the one from mtab,
3957 if length of utf8_root_path_name is zero it must be the root dir */
3958 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
3959 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
3960 drive_type = _wapi_get_drive_type (*(splitted + 2));
3961 g_strfreev (splitted);
3965 g_strfreev (splitted);
3973 guint32 GetDriveType(const gunichar2 *root_path_name)
3975 gchar *utf8_root_path_name;
3978 if (root_path_name == NULL) {
3979 utf8_root_path_name = g_strdup (g_get_current_dir());
3980 if (utf8_root_path_name == NULL) {
3981 return(DRIVE_NO_ROOT_DIR);
3985 utf8_root_path_name = mono_unicode_to_external (root_path_name);
3986 if (utf8_root_path_name == NULL) {
3988 g_message("%s: unicode conversion returned NULL", __func__);
3990 return(DRIVE_NO_ROOT_DIR);
3993 /* strip trailing slash for compare below */
3994 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
3995 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
3998 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
3999 g_free (utf8_root_path_name);
4001 return (drive_type);
4004 /* Linux has struct statfs which has a different layout */
4005 #if defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H) && !__linux__
4007 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4011 gboolean status = FALSE;
4014 // We only support getting the file system type
4015 if (fsbuffer == NULL)
4018 utfpath = mono_unicode_to_external (path);
4019 if (statfs (utfpath, &stat) != -1){
4020 gunichar2 *ret = g_utf8_to_utf16 (stat.f_fstypename, -1, NULL, &len, NULL);
4021 if (ret != NULL && len < fsbuffersize){
4022 memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4032 /* Windows has its own GetVolumeInformation */
4035 * Linux does not this case, as the processing is done in managed code, by parsing /etc/mtab
4038 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)