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>
21 #if defined(HAVE_SYS_STATFS_H)
22 #include <sys/statfs.h>
24 #if defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H)
25 #include <sys/param.h>
26 #include <sys/mount.h>
28 #include <sys/types.h>
34 #include <sys/ioctl.h>
36 #include <mono/utils/linux_magic.h>
39 #include <mono/io-layer/wapi.h>
40 #include <mono/io-layer/wapi-private.h>
41 #include <mono/io-layer/handles-private.h>
42 #include <mono/io-layer/io-private.h>
43 #include <mono/io-layer/timefuncs-private.h>
44 #include <mono/io-layer/thread-private.h>
45 #include <mono/io-layer/io-portability.h>
46 #include <mono/utils/strenc.h>
50 static void file_close (gpointer handle, gpointer data);
51 static WapiFileType file_getfiletype(void);
52 static gboolean file_read(gpointer handle, gpointer buffer,
53 guint32 numbytes, guint32 *bytesread,
54 WapiOverlapped *overlapped);
55 static gboolean file_write(gpointer handle, gconstpointer buffer,
56 guint32 numbytes, guint32 *byteswritten,
57 WapiOverlapped *overlapped);
58 static gboolean file_flush(gpointer handle);
59 static guint32 file_seek(gpointer handle, gint32 movedistance,
60 gint32 *highmovedistance, WapiSeekMethod method);
61 static gboolean file_setendoffile(gpointer handle);
62 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
63 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
64 WapiFileTime *last_access,
65 WapiFileTime *last_write);
66 static gboolean file_setfiletime(gpointer handle,
67 const WapiFileTime *create_time,
68 const WapiFileTime *last_access,
69 const WapiFileTime *last_write);
70 static guint32 GetDriveTypeFromPath (const gchar *utf8_root_path_name);
72 /* File handle is only signalled for overlapped IO */
73 struct _WapiHandleOps _wapi_file_ops = {
74 file_close, /* close */
78 NULL, /* special_wait */
82 void _wapi_file_details (gpointer handle_info)
84 struct _WapiHandle_file *file = (struct _WapiHandle_file *)handle_info;
86 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
88 file->fileaccess&GENERIC_READ?'R':'.',
89 file->fileaccess&GENERIC_WRITE?'W':'.',
90 file->fileaccess&GENERIC_EXECUTE?'X':'.',
91 file->sharemode&FILE_SHARE_READ?'R':'.',
92 file->sharemode&FILE_SHARE_WRITE?'W':'.',
93 file->sharemode&FILE_SHARE_DELETE?'D':'.',
97 static void console_close (gpointer handle, gpointer data);
98 static WapiFileType console_getfiletype(void);
99 static gboolean console_read(gpointer handle, gpointer buffer,
100 guint32 numbytes, guint32 *bytesread,
101 WapiOverlapped *overlapped);
102 static gboolean console_write(gpointer handle, gconstpointer buffer,
103 guint32 numbytes, guint32 *byteswritten,
104 WapiOverlapped *overlapped);
106 /* Console is mostly the same as file, except it can block waiting for
109 struct _WapiHandleOps _wapi_console_ops = {
110 console_close, /* close */
114 NULL, /* special_wait */
118 void _wapi_console_details (gpointer handle_info)
120 _wapi_file_details (handle_info);
123 /* Find handle has no ops.
125 struct _WapiHandleOps _wapi_find_ops = {
130 NULL, /* special_wait */
134 static void pipe_close (gpointer handle, gpointer data);
135 static WapiFileType pipe_getfiletype (void);
136 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
137 guint32 *bytesread, WapiOverlapped *overlapped);
138 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
139 guint32 numbytes, guint32 *byteswritten,
140 WapiOverlapped *overlapped);
144 struct _WapiHandleOps _wapi_pipe_ops = {
145 pipe_close, /* close */
149 NULL, /* special_wait */
153 void _wapi_pipe_details (gpointer handle_info)
155 _wapi_file_details (handle_info);
158 static const struct {
159 /* File, console and pipe handles */
160 WapiFileType (*getfiletype)(void);
162 /* File, console and pipe handles */
163 gboolean (*readfile)(gpointer handle, gpointer buffer,
164 guint32 numbytes, guint32 *bytesread,
165 WapiOverlapped *overlapped);
166 gboolean (*writefile)(gpointer handle, gconstpointer buffer,
167 guint32 numbytes, guint32 *byteswritten,
168 WapiOverlapped *overlapped);
169 gboolean (*flushfile)(gpointer handle);
172 guint32 (*seek)(gpointer handle, gint32 movedistance,
173 gint32 *highmovedistance, WapiSeekMethod method);
174 gboolean (*setendoffile)(gpointer handle);
175 guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
176 gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
177 WapiFileTime *last_access,
178 WapiFileTime *last_write);
179 gboolean (*setfiletime)(gpointer handle,
180 const WapiFileTime *create_time,
181 const WapiFileTime *last_access,
182 const WapiFileTime *last_write);
183 } io_ops[WAPI_HANDLE_COUNT]={
184 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
187 file_read, file_write,
188 file_flush, file_seek,
194 {console_getfiletype,
197 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},
205 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
206 /* socket (will need at least read and write) */
207 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
209 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
211 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
216 NULL, NULL, NULL, NULL, NULL, NULL},
219 static mono_once_t io_ops_once=MONO_ONCE_INIT;
220 static gboolean lock_while_writing = FALSE;
222 static void io_ops_init (void)
224 /* _wapi_handle_register_capabilities (WAPI_HANDLE_FILE, */
225 /* WAPI_HANDLE_CAP_WAIT); */
226 /* _wapi_handle_register_capabilities (WAPI_HANDLE_CONSOLE, */
227 /* WAPI_HANDLE_CAP_WAIT); */
229 if (g_getenv ("MONO_STRICT_IO_EMULATION") != NULL) {
230 lock_while_writing = TRUE;
234 /* Some utility functions.
237 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
244 /* FIXME: this could definitely be better, but there seems to
245 * be no pattern to the attributes that are set
248 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
249 if (S_ISSOCK (buf->st_mode))
250 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
252 filename = _wapi_basename (pathname);
254 if (S_ISDIR (buf->st_mode)) {
255 attrs = FILE_ATTRIBUTE_DIRECTORY;
256 if (!(buf->st_mode & S_IWUSR)) {
257 attrs |= FILE_ATTRIBUTE_READONLY;
259 if (filename[0] == '.') {
260 attrs |= FILE_ATTRIBUTE_HIDDEN;
263 if (!(buf->st_mode & S_IWUSR)) {
264 attrs = FILE_ATTRIBUTE_READONLY;
266 if (filename[0] == '.') {
267 attrs |= FILE_ATTRIBUTE_HIDDEN;
269 } else if (filename[0] == '.') {
270 attrs = FILE_ATTRIBUTE_HIDDEN;
272 attrs = FILE_ATTRIBUTE_NORMAL;
277 if (S_ISLNK (lbuf->st_mode)) {
278 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
288 _wapi_set_last_error_from_errno (void)
290 SetLastError (_wapi_get_win32_file_error (errno));
293 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
296 if (errno == ENOENT) {
297 /* Check the path - if it's a missing directory then
298 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
304 dirname = _wapi_dirname (path);
306 dirname = g_strdup (dir);
309 if (_wapi_access (dirname, F_OK) == 0) {
310 SetLastError (ERROR_FILE_NOT_FOUND);
312 SetLastError (ERROR_PATH_NOT_FOUND);
317 _wapi_set_last_error_from_errno ();
323 static void file_close (gpointer handle, gpointer data)
325 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
328 g_message("%s: closing file handle %p [%s]", __func__, handle,
329 file_handle->filename);
332 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
333 _wapi_unlink (file_handle->filename);
335 g_free (file_handle->filename);
337 if (file_handle->share_info)
338 _wapi_handle_share_release (file_handle->share_info);
340 close (GPOINTER_TO_UINT(handle));
343 static WapiFileType file_getfiletype(void)
345 return(FILE_TYPE_DISK);
348 static gboolean file_read(gpointer handle, gpointer buffer,
349 guint32 numbytes, guint32 *bytesread,
350 WapiOverlapped *overlapped)
352 struct _WapiHandle_file *file_handle;
354 int fd = GPOINTER_TO_UINT(handle);
357 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
358 (gpointer *)&file_handle);
360 g_warning ("%s: error looking up file handle %p", __func__,
362 SetLastError (ERROR_INVALID_HANDLE);
366 if(bytesread!=NULL) {
370 if(!(file_handle->fileaccess & GENERIC_READ) &&
371 !(file_handle->fileaccess & GENERIC_ALL)) {
373 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
374 __func__, handle, file_handle->fileaccess);
377 SetLastError (ERROR_ACCESS_DENIED);
382 ret = read (fd, buffer, numbytes);
383 } while (ret == -1 && errno == EINTR &&
384 !_wapi_thread_cur_apc_pending());
390 g_message("%s: read of handle %p error: %s", __func__,
391 handle, strerror(err));
393 SetLastError (_wapi_get_win32_file_error (err));
397 if (bytesread != NULL) {
404 static gboolean file_write(gpointer handle, gconstpointer buffer,
405 guint32 numbytes, guint32 *byteswritten,
406 WapiOverlapped *overlapped G_GNUC_UNUSED)
408 struct _WapiHandle_file *file_handle;
411 off_t current_pos = 0;
412 int fd = GPOINTER_TO_UINT(handle);
414 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
415 (gpointer *)&file_handle);
417 g_warning ("%s: error looking up file handle %p", __func__,
419 SetLastError (ERROR_INVALID_HANDLE);
423 if(byteswritten!=NULL) {
427 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
428 !(file_handle->fileaccess & GENERIC_ALL)) {
430 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
433 SetLastError (ERROR_ACCESS_DENIED);
437 if (lock_while_writing) {
438 /* Need to lock the region we're about to write to,
439 * because we only do advisory locking on POSIX
442 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
443 if (current_pos == -1) {
445 g_message ("%s: handle %p lseek failed: %s", __func__,
446 handle, strerror (errno));
448 _wapi_set_last_error_from_errno ();
452 if (_wapi_lock_file_region (fd, current_pos,
453 numbytes) == FALSE) {
454 /* The error has already been set */
460 ret = write (fd, buffer, numbytes);
461 } while (ret == -1 && errno == EINTR &&
462 !_wapi_thread_cur_apc_pending());
464 if (lock_while_writing) {
465 _wapi_unlock_file_region (fd, current_pos, numbytes);
469 if (errno == EINTR) {
472 _wapi_set_last_error_from_errno ();
475 g_message("%s: write of handle %p error: %s",
476 __func__, handle, strerror(errno));
482 if (byteswritten != NULL) {
488 static gboolean file_flush(gpointer handle)
490 struct _WapiHandle_file *file_handle;
493 int fd = GPOINTER_TO_UINT(handle);
495 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
496 (gpointer *)&file_handle);
498 g_warning ("%s: error looking up file handle %p", __func__,
500 SetLastError (ERROR_INVALID_HANDLE);
504 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
505 !(file_handle->fileaccess & GENERIC_ALL)) {
507 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
510 SetLastError (ERROR_ACCESS_DENIED);
517 g_message("%s: fsync of handle %p error: %s", __func__, handle,
521 _wapi_set_last_error_from_errno ();
528 static guint32 file_seek(gpointer handle, gint32 movedistance,
529 gint32 *highmovedistance, WapiSeekMethod method)
531 struct _WapiHandle_file *file_handle;
533 off_t offset, newpos;
536 int fd = GPOINTER_TO_UINT(handle);
538 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
539 (gpointer *)&file_handle);
541 g_warning ("%s: error looking up file handle %p", __func__,
543 SetLastError (ERROR_INVALID_HANDLE);
544 return(INVALID_SET_FILE_POINTER);
547 if(!(file_handle->fileaccess & GENERIC_READ) &&
548 !(file_handle->fileaccess & GENERIC_WRITE) &&
549 !(file_handle->fileaccess & GENERIC_ALL)) {
551 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
554 SetLastError (ERROR_ACCESS_DENIED);
555 return(INVALID_SET_FILE_POINTER);
570 g_message("%s: invalid seek type %d", __func__, method);
573 SetLastError (ERROR_INVALID_PARAMETER);
574 return(INVALID_SET_FILE_POINTER);
577 #ifdef HAVE_LARGE_FILE_SUPPORT
578 if(highmovedistance==NULL) {
581 g_message("%s: setting offset to %lld (low %d)", __func__,
582 offset, movedistance);
585 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
588 g_message("%s: setting offset to %lld 0x%llx (high %d 0x%x, low %d 0x%x)", __func__, offset, offset, *highmovedistance, *highmovedistance, movedistance, movedistance);
596 #ifdef HAVE_LARGE_FILE_SUPPORT
597 g_message("%s: moving handle %p by %lld bytes from %d", __func__,
598 handle, offset, whence);
600 g_message("%s: moving handle %p fd %d by %ld bytes from %d", __func__,
601 handle, offset, whence);
605 newpos=lseek(fd, offset, whence);
608 g_message("%s: lseek on handle %p returned error %s",
609 __func__, handle, strerror(errno));
612 _wapi_set_last_error_from_errno ();
613 return(INVALID_SET_FILE_POINTER);
617 #ifdef HAVE_LARGE_FILE_SUPPORT
618 g_message("%s: lseek returns %lld", __func__, newpos);
620 g_message ("%s: lseek returns %ld", __func__, newpos);
624 #ifdef HAVE_LARGE_FILE_SUPPORT
625 ret=newpos & 0xFFFFFFFF;
626 if(highmovedistance!=NULL) {
627 *highmovedistance=newpos>>32;
631 if(highmovedistance!=NULL) {
632 /* Accurate, but potentially dodgy :-) */
638 g_message ("%s: move of handle %p returning %d/%d", __func__,
639 handle, ret, highmovedistance==NULL?0:*highmovedistance);
645 static gboolean file_setendoffile(gpointer handle)
647 struct _WapiHandle_file *file_handle;
652 int fd = GPOINTER_TO_UINT(handle);
654 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
655 (gpointer *)&file_handle);
657 g_warning ("%s: error looking up file handle %p", __func__,
659 SetLastError (ERROR_INVALID_HANDLE);
663 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
664 !(file_handle->fileaccess & GENERIC_ALL)) {
666 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
669 SetLastError (ERROR_ACCESS_DENIED);
673 /* Find the current file position, and the file length. If
674 * the file position is greater than the length, write to
675 * extend the file with a hole. If the file position is less
676 * than the length, truncate the file.
679 ret=fstat(fd, &statbuf);
682 g_message ("%s: handle %p fstat failed: %s", __func__,
683 handle, strerror(errno));
686 _wapi_set_last_error_from_errno ();
689 size=statbuf.st_size;
691 pos=lseek(fd, (off_t)0, SEEK_CUR);
694 g_message("%s: handle %p lseek failed: %s", __func__,
695 handle, strerror(errno));
698 _wapi_set_last_error_from_errno ();
702 #ifdef FTRUNCATE_DOESNT_EXTEND
703 /* I haven't bothered to write the configure.in stuff for this
704 * because I don't know if any platform needs it. I'm leaving
705 * this code just in case though
708 /* Extend the file. Use write() here, because some
709 * manuals say that ftruncate() behaviour is undefined
710 * when the file needs extending. The POSIX spec says
711 * that on XSI-conformant systems it extends, so if
712 * every system we care about conforms, then we can
716 ret = write (fd, "", 1);
717 } while (ret == -1 && errno == EINTR &&
718 !_wapi_thread_cur_apc_pending());
722 g_message("%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
725 _wapi_set_last_error_from_errno ();
729 /* And put the file position back after the write */
730 ret = lseek (fd, pos, SEEK_SET);
733 g_message ("%s: handle %p second lseek failed: %s",
734 __func__, handle, strerror(errno));
737 _wapi_set_last_error_from_errno ();
743 /* always truncate, because the extend write() adds an extra
744 * byte to the end of the file
747 ret=ftruncate(fd, pos);
749 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
752 g_message("%s: handle %p ftruncate failed: %s", __func__,
753 handle, strerror(errno));
756 _wapi_set_last_error_from_errno ();
763 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
765 struct _WapiHandle_file *file_handle;
770 int fd = GPOINTER_TO_UINT(handle);
772 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
773 (gpointer *)&file_handle);
775 g_warning ("%s: error looking up file handle %p", __func__,
777 SetLastError (ERROR_INVALID_HANDLE);
778 return(INVALID_FILE_SIZE);
781 if(!(file_handle->fileaccess & GENERIC_READ) &&
782 !(file_handle->fileaccess & GENERIC_WRITE) &&
783 !(file_handle->fileaccess & GENERIC_ALL)) {
785 g_message("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
788 SetLastError (ERROR_ACCESS_DENIED);
789 return(INVALID_FILE_SIZE);
792 /* If the file has a size with the low bits 0xFFFFFFFF the
793 * caller can't tell if this is an error, so clear the error
796 SetLastError (ERROR_SUCCESS);
798 ret = fstat(fd, &statbuf);
801 g_message ("%s: handle %p fstat failed: %s", __func__,
802 handle, strerror(errno));
805 _wapi_set_last_error_from_errno ();
806 return(INVALID_FILE_SIZE);
809 /* fstat indicates block devices as zero-length, so go a different path */
811 if (S_ISBLK(statbuf.st_mode)) {
813 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
815 g_message ("%s: handle %p ioctl BLKGETSIZE64 failed: %s",
816 __func__, handle, strerror(errno));
819 _wapi_set_last_error_from_errno ();
820 return(INVALID_FILE_SIZE);
823 size = bigsize & 0xFFFFFFFF;
824 if (highsize != NULL) {
825 *highsize = bigsize>>32;
829 g_message ("%s: Returning block device size %d/%d",
830 __func__, size, *highsize);
837 #ifdef HAVE_LARGE_FILE_SUPPORT
838 size = statbuf.st_size & 0xFFFFFFFF;
839 if (highsize != NULL) {
840 *highsize = statbuf.st_size>>32;
843 if (highsize != NULL) {
844 /* Accurate, but potentially dodgy :-) */
847 size = statbuf.st_size;
851 g_message ("%s: Returning size %d/%d", __func__, size, *highsize);
857 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
858 WapiFileTime *last_access,
859 WapiFileTime *last_write)
861 struct _WapiHandle_file *file_handle;
864 guint64 create_ticks, access_ticks, write_ticks;
866 int fd = GPOINTER_TO_UINT(handle);
868 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
869 (gpointer *)&file_handle);
871 g_warning ("%s: error looking up file handle %p", __func__,
873 SetLastError (ERROR_INVALID_HANDLE);
877 if(!(file_handle->fileaccess & GENERIC_READ) &&
878 !(file_handle->fileaccess & GENERIC_ALL)) {
880 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
881 __func__, handle, file_handle->fileaccess);
884 SetLastError (ERROR_ACCESS_DENIED);
888 ret=fstat(fd, &statbuf);
891 g_message("%s: handle %p fstat failed: %s", __func__, handle,
895 _wapi_set_last_error_from_errno ();
900 g_message("%s: atime: %ld ctime: %ld mtime: %ld", __func__,
901 statbuf.st_atime, statbuf.st_ctime,
905 /* Try and guess a meaningful create time by using the older
908 /* The magic constant comes from msdn documentation
909 * "Converting a time_t Value to a File Time"
911 if(statbuf.st_atime < statbuf.st_ctime) {
912 create_ticks=((guint64)statbuf.st_atime*10000000)
913 + 116444736000000000ULL;
915 create_ticks=((guint64)statbuf.st_ctime*10000000)
916 + 116444736000000000ULL;
919 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
920 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
923 g_message("%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
924 access_ticks, create_ticks, write_ticks);
927 if(create_time!=NULL) {
928 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
929 create_time->dwHighDateTime = create_ticks >> 32;
932 if(last_access!=NULL) {
933 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
934 last_access->dwHighDateTime = access_ticks >> 32;
937 if(last_write!=NULL) {
938 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
939 last_write->dwHighDateTime = write_ticks >> 32;
945 static gboolean file_setfiletime(gpointer handle,
946 const WapiFileTime *create_time G_GNUC_UNUSED,
947 const WapiFileTime *last_access,
948 const WapiFileTime *last_write)
950 struct _WapiHandle_file *file_handle;
952 struct utimbuf utbuf;
954 guint64 access_ticks, write_ticks;
956 int fd = GPOINTER_TO_UINT(handle);
958 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
959 (gpointer *)&file_handle);
961 g_warning ("%s: error looking up file handle %p", __func__,
963 SetLastError (ERROR_INVALID_HANDLE);
967 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
968 !(file_handle->fileaccess & GENERIC_ALL)) {
970 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
973 SetLastError (ERROR_ACCESS_DENIED);
977 if(file_handle->filename == NULL) {
979 g_message("%s: handle %p unknown filename", __func__, handle);
982 SetLastError (ERROR_INVALID_HANDLE);
986 /* Get the current times, so we can put the same times back in
987 * the event that one of the FileTime structs is NULL
989 ret=fstat (fd, &statbuf);
992 g_message("%s: handle %p fstat failed: %s", __func__, handle,
996 SetLastError (ERROR_INVALID_PARAMETER);
1000 if(last_access!=NULL) {
1001 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
1002 last_access->dwLowDateTime;
1003 /* This is (time_t)0. We can actually go to INT_MIN,
1004 * but this will do for now.
1006 if (access_ticks < 116444736000000000ULL) {
1008 g_message ("%s: attempt to set access time too early",
1011 SetLastError (ERROR_INVALID_PARAMETER);
1015 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
1017 utbuf.actime=statbuf.st_atime;
1020 if(last_write!=NULL) {
1021 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
1022 last_write->dwLowDateTime;
1023 /* This is (time_t)0. We can actually go to INT_MIN,
1024 * but this will do for now.
1026 if (write_ticks < 116444736000000000ULL) {
1028 g_message ("%s: attempt to set write time too early",
1031 SetLastError (ERROR_INVALID_PARAMETER);
1035 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1037 utbuf.modtime=statbuf.st_mtime;
1041 g_message ("%s: setting handle %p access %ld write %ld", __func__,
1042 handle, utbuf.actime, utbuf.modtime);
1045 ret = _wapi_utime (file_handle->filename, &utbuf);
1048 g_message ("%s: handle %p [%s] utime failed: %s", __func__,
1049 handle, file_handle->filename, strerror(errno));
1052 SetLastError (ERROR_INVALID_PARAMETER);
1059 static void console_close (gpointer handle, gpointer data)
1061 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1064 g_message("%s: closing console handle %p", __func__, handle);
1067 g_free (console_handle->filename);
1069 close (GPOINTER_TO_UINT(handle));
1072 static WapiFileType console_getfiletype(void)
1074 return(FILE_TYPE_CHAR);
1077 static gboolean console_read(gpointer handle, gpointer buffer,
1078 guint32 numbytes, guint32 *bytesread,
1079 WapiOverlapped *overlapped G_GNUC_UNUSED)
1081 struct _WapiHandle_file *console_handle;
1084 int fd = GPOINTER_TO_UINT(handle);
1086 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1087 (gpointer *)&console_handle);
1089 g_warning ("%s: error looking up console handle %p", __func__,
1091 SetLastError (ERROR_INVALID_HANDLE);
1095 if(bytesread!=NULL) {
1099 if(!(console_handle->fileaccess & GENERIC_READ) &&
1100 !(console_handle->fileaccess & GENERIC_ALL)) {
1102 g_message ("%s: handle %p doesn't have GENERIC_READ access: %u",
1103 __func__, handle, console_handle->fileaccess);
1106 SetLastError (ERROR_ACCESS_DENIED);
1111 ret=read(fd, buffer, numbytes);
1112 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1116 g_message("%s: read of handle %p error: %s", __func__, handle,
1120 _wapi_set_last_error_from_errno ();
1124 if(bytesread!=NULL) {
1131 static gboolean console_write(gpointer handle, gconstpointer buffer,
1132 guint32 numbytes, guint32 *byteswritten,
1133 WapiOverlapped *overlapped G_GNUC_UNUSED)
1135 struct _WapiHandle_file *console_handle;
1138 int fd = GPOINTER_TO_UINT(handle);
1140 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1141 (gpointer *)&console_handle);
1143 g_warning ("%s: error looking up console handle %p", __func__,
1145 SetLastError (ERROR_INVALID_HANDLE);
1149 if(byteswritten!=NULL) {
1153 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1154 !(console_handle->fileaccess & GENERIC_ALL)) {
1156 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, console_handle->fileaccess);
1159 SetLastError (ERROR_ACCESS_DENIED);
1164 ret = write(fd, buffer, numbytes);
1165 } while (ret == -1 && errno == EINTR &&
1166 !_wapi_thread_cur_apc_pending());
1169 if (errno == EINTR) {
1172 _wapi_set_last_error_from_errno ();
1175 g_message ("%s: write of handle %p error: %s",
1176 __func__, handle, strerror(errno));
1182 if(byteswritten!=NULL) {
1189 static void pipe_close (gpointer handle, gpointer data G_GNUC_UNUSED)
1192 g_message("%s: closing pipe handle %p", __func__, handle);
1195 /* No filename with pipe handles */
1197 close(GPOINTER_TO_UINT(handle));
1200 static WapiFileType pipe_getfiletype(void)
1202 return(FILE_TYPE_PIPE);
1205 static gboolean pipe_read (gpointer handle, gpointer buffer,
1206 guint32 numbytes, guint32 *bytesread,
1207 WapiOverlapped *overlapped G_GNUC_UNUSED)
1209 struct _WapiHandle_file *pipe_handle;
1212 int fd = GPOINTER_TO_UINT(handle);
1214 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1215 (gpointer *)&pipe_handle);
1217 g_warning ("%s: error looking up pipe handle %p", __func__,
1219 SetLastError (ERROR_INVALID_HANDLE);
1223 if(bytesread!=NULL) {
1227 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1228 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1230 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
1231 __func__, handle, pipe_handle->fileaccess);
1234 SetLastError (ERROR_ACCESS_DENIED);
1239 g_message ("%s: reading up to %d bytes from pipe %p", __func__,
1244 ret=read(fd, buffer, numbytes);
1245 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1248 if (errno == EINTR) {
1251 _wapi_set_last_error_from_errno ();
1254 g_message("%s: read of handle %p error: %s", __func__,
1255 handle, strerror(errno));
1263 g_message ("%s: read %d bytes from pipe", __func__, ret);
1266 if(bytesread!=NULL) {
1273 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1274 guint32 numbytes, guint32 *byteswritten,
1275 WapiOverlapped *overlapped G_GNUC_UNUSED)
1277 struct _WapiHandle_file *pipe_handle;
1280 int fd = GPOINTER_TO_UINT(handle);
1282 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1283 (gpointer *)&pipe_handle);
1285 g_warning ("%s: error looking up pipe handle %p", __func__,
1287 SetLastError (ERROR_INVALID_HANDLE);
1291 if(byteswritten!=NULL) {
1295 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1296 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1298 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, pipe_handle->fileaccess);
1301 SetLastError (ERROR_ACCESS_DENIED);
1306 g_message ("%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1311 ret = write (fd, buffer, numbytes);
1312 } while (ret == -1 && errno == EINTR &&
1313 !_wapi_thread_cur_apc_pending());
1316 if (errno == EINTR) {
1319 _wapi_set_last_error_from_errno ();
1322 g_message("%s: write of handle %p error: %s", __func__,
1323 handle, strerror(errno));
1329 if(byteswritten!=NULL) {
1336 static int convert_flags(guint32 fileaccess, guint32 createmode)
1340 switch(fileaccess) {
1347 case GENERIC_READ|GENERIC_WRITE:
1352 g_message("%s: Unknown access type 0x%x", __func__,
1358 switch(createmode) {
1360 flags|=O_CREAT|O_EXCL;
1363 flags|=O_CREAT|O_TRUNC;
1370 case TRUNCATE_EXISTING:
1375 g_message("%s: Unknown create mode 0x%x", __func__,
1385 static mode_t convert_perms(guint32 sharemode)
1389 if(sharemode&FILE_SHARE_READ) {
1392 if(sharemode&FILE_SHARE_WRITE) {
1400 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1402 struct _WapiFileShare **share_info)
1404 gboolean file_already_shared;
1405 guint32 file_existing_share, file_existing_access;
1407 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);
1409 if (file_already_shared) {
1410 /* The reference to this share info was incremented
1411 * when we looked it up, so be careful to put it back
1412 * if we conclude we can't use this file.
1414 if (file_existing_share == 0) {
1415 /* Quick and easy, no possibility to share */
1417 g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
1420 _wapi_handle_share_release (*share_info);
1425 if (((file_existing_share == FILE_SHARE_READ) &&
1426 (fileaccess != GENERIC_READ)) ||
1427 ((file_existing_share == FILE_SHARE_WRITE) &&
1428 (fileaccess != GENERIC_WRITE))) {
1429 /* New access mode doesn't match up */
1431 g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
1434 _wapi_handle_share_release (*share_info);
1439 if (((file_existing_access & GENERIC_READ) &&
1440 !(sharemode & FILE_SHARE_READ)) ||
1441 ((file_existing_access & GENERIC_WRITE) &&
1442 !(sharemode & FILE_SHARE_WRITE))) {
1443 /* New share mode doesn't match up */
1445 g_message ("%s: Access mode prevents open: requested share: 0x%x, file has access: 0x%x", __func__, sharemode, file_existing_access);
1448 _wapi_handle_share_release (*share_info);
1454 g_message ("%s: New file!", __func__);
1461 static gboolean share_check (struct stat *statbuf, guint32 sharemode,
1463 struct _WapiFileShare **share_info, int fd)
1465 if (share_allows_open (statbuf, sharemode, fileaccess,
1466 share_info) == TRUE) {
1470 /* Got a share violation. Double check that the file is still
1471 * open by someone, in case a process crashed while still
1472 * holding a file handle. This will also cope with someone
1473 * using Mono.Posix to close the file. This is cheaper and
1474 * less intrusive to other processes than initiating a handle
1478 _wapi_handle_check_share (*share_info, fd);
1479 if (share_allows_open (statbuf, sharemode, fileaccess,
1480 share_info) == TRUE) {
1484 /* Still violating. It's possible that a process crashed
1485 * while still holding a file handle, and that a non-mono
1486 * process has the file open. (For example, C-c mcs while
1487 * editing a source file.) As a last resort, run a handle
1488 * collection, which will remove stale share entries.
1490 _wapi_handle_collect ();
1492 return(share_allows_open (statbuf, sharemode, fileaccess, share_info));
1497 * @name: a pointer to a NULL-terminated unicode string, that names
1498 * the file or other object to create.
1499 * @fileaccess: specifies the file access mode
1500 * @sharemode: whether the file should be shared. This parameter is
1501 * currently ignored.
1502 * @security: Ignored for now.
1503 * @createmode: specifies whether to create a new file, whether to
1504 * overwrite an existing file, whether to truncate the file, etc.
1505 * @attrs: specifies file attributes and flags. On win32 attributes
1506 * are characteristics of the file, not the handle, and are ignored
1507 * when an existing file is opened. Flags give the library hints on
1508 * how to process a file to optimise performance.
1509 * @template: the handle of an open %GENERIC_READ file that specifies
1510 * attributes to apply to a newly created file, ignoring @attrs.
1511 * Normally this parameter is NULL. This parameter is ignored when an
1512 * existing file is opened.
1514 * Creates a new file handle. This only applies to normal files:
1515 * pipes are handled by CreatePipe(), and console handles are created
1516 * with GetStdHandle().
1518 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1520 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1521 guint32 sharemode, WapiSecurityAttributes *security,
1522 guint32 createmode, guint32 attrs,
1523 gpointer template G_GNUC_UNUSED)
1525 struct _WapiHandle_file file_handle = {0};
1527 int flags=convert_flags(fileaccess, createmode);
1528 /*mode_t perms=convert_perms(sharemode);*/
1529 /* we don't use sharemode, because that relates to sharing of
1530 * the file when the file is open and is already handled by
1531 * other code, perms instead are the on-disk permissions and
1532 * this is a sane default.
1538 struct stat statbuf;
1540 mono_once (&io_ops_once, io_ops_init);
1542 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1545 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1546 SetLastError (ERROR_ENCRYPTION_FAILED);
1547 return INVALID_HANDLE_VALUE;
1552 g_message ("%s: name is NULL", __func__);
1555 SetLastError (ERROR_INVALID_NAME);
1556 return(INVALID_HANDLE_VALUE);
1559 filename = mono_unicode_to_external (name);
1560 if (filename == NULL) {
1562 g_message("%s: unicode conversion returned NULL", __func__);
1565 SetLastError (ERROR_INVALID_NAME);
1566 return(INVALID_HANDLE_VALUE);
1570 g_message ("%s: Opening %s with share 0x%x and access 0x%x", __func__,
1571 filename, sharemode, fileaccess);
1574 fd = _wapi_open (filename, flags, perms);
1576 /* If we were trying to open a directory with write permissions
1577 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1578 * EISDIR. However, this is a bit bogus because calls to
1579 * manipulate the directory (e.g. SetFileTime) will still work on
1580 * the directory because they use other API calls
1581 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1582 * to open the directory again without write permission.
1584 if (fd == -1 && errno == EISDIR)
1586 /* Try again but don't try to make it writable */
1587 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1592 g_message("%s: Error opening file %s: %s", __func__, filename,
1595 _wapi_set_last_path_error_from_errno (NULL, filename);
1598 return(INVALID_HANDLE_VALUE);
1601 if (fd >= _wapi_fd_reserve) {
1603 g_message ("%s: File descriptor is too big", __func__);
1606 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1611 return(INVALID_HANDLE_VALUE);
1614 ret = fstat (fd, &statbuf);
1617 g_message ("%s: fstat error of file %s: %s", __func__,
1618 filename, strerror (errno));
1620 _wapi_set_last_error_from_errno ();
1624 return(INVALID_HANDLE_VALUE);
1627 if (share_check (&statbuf, sharemode, fileaccess,
1628 &file_handle.share_info, fd) == FALSE) {
1629 SetLastError (ERROR_SHARING_VIOLATION);
1633 return (INVALID_HANDLE_VALUE);
1635 if (file_handle.share_info == NULL) {
1636 /* No space, so no more files can be opened */
1638 g_message ("%s: No space in the share table", __func__);
1641 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1645 return(INVALID_HANDLE_VALUE);
1648 file_handle.filename = filename;
1650 if(security!=NULL) {
1651 //file_handle->security_attributes=_wapi_handle_scratch_store (
1652 //security, sizeof(WapiSecurityAttributes));
1655 file_handle.fileaccess=fileaccess;
1656 file_handle.sharemode=sharemode;
1657 file_handle.attrs=attrs;
1659 #ifdef HAVE_POSIX_FADVISE
1660 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1661 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1662 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1663 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1667 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1669 if (S_ISFIFO (statbuf.st_mode)) {
1670 handle_type = WAPI_HANDLE_PIPE;
1671 } else if (S_ISCHR (statbuf.st_mode)) {
1672 handle_type = WAPI_HANDLE_CONSOLE;
1674 handle_type = WAPI_HANDLE_FILE;
1677 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1678 if (handle == _WAPI_HANDLE_INVALID) {
1679 g_warning ("%s: error creating file handle", __func__);
1683 SetLastError (ERROR_GEN_FAILURE);
1684 return(INVALID_HANDLE_VALUE);
1688 g_message("%s: returning handle %p", __func__, handle);
1696 * @name: a pointer to a NULL-terminated unicode string, that names
1697 * the file to be deleted.
1699 * Deletes file @name.
1701 * Return value: %TRUE on success, %FALSE otherwise.
1703 gboolean DeleteFile(const gunichar2 *name)
1707 gboolean ret = FALSE;
1710 struct stat statbuf;
1711 struct _WapiFileShare *shareinfo;
1716 g_message("%s: name is NULL", __func__);
1719 SetLastError (ERROR_INVALID_NAME);
1723 filename=mono_unicode_to_external(name);
1724 if(filename==NULL) {
1726 g_message("%s: unicode conversion returned NULL", __func__);
1729 SetLastError (ERROR_INVALID_NAME);
1733 attrs = GetFileAttributes (name);
1734 if (attrs == INVALID_FILE_ATTRIBUTES) {
1736 g_message ("%s: file attributes error", __func__);
1738 /* Error set by GetFileAttributes() */
1743 if (attrs & FILE_ATTRIBUTE_READONLY) {
1745 g_message ("%s: file %s is readonly", __func__, filename);
1747 SetLastError (ERROR_ACCESS_DENIED);
1753 /* Check to make sure sharing allows us to open the file for
1754 * writing. See bug 323389.
1756 * Do the checks that don't need an open file descriptor, for
1757 * simplicity's sake. If we really have to do the full checks
1758 * then we can implement that later.
1760 if (_wapi_stat (filename, &statbuf) < 0) {
1761 _wapi_set_last_path_error_from_errno (NULL, filename);
1766 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1767 &shareinfo) == FALSE) {
1768 SetLastError (ERROR_SHARING_VIOLATION);
1773 _wapi_handle_share_release (shareinfo);
1776 retval = _wapi_unlink (filename);
1779 _wapi_set_last_path_error_from_errno (NULL, filename);
1791 * @name: a pointer to a NULL-terminated unicode string, that names
1792 * the file to be moved.
1793 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1794 * new name for the file.
1796 * Renames file @name to @dest_name.
1797 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1798 * when it is the same file as the source. In that case it silently succeeds.
1800 * Return value: %TRUE on success, %FALSE otherwise.
1802 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1804 gchar *utf8_name, *utf8_dest_name;
1805 int result, errno_copy;
1806 struct stat stat_src, stat_dest;
1807 gboolean ret = FALSE;
1808 struct _WapiFileShare *shareinfo;
1812 g_message("%s: name is NULL", __func__);
1815 SetLastError (ERROR_INVALID_NAME);
1819 utf8_name = mono_unicode_to_external (name);
1820 if (utf8_name == NULL) {
1822 g_message ("%s: unicode conversion returned NULL", __func__);
1825 SetLastError (ERROR_INVALID_NAME);
1829 if(dest_name==NULL) {
1831 g_message("%s: name is NULL", __func__);
1835 SetLastError (ERROR_INVALID_NAME);
1839 utf8_dest_name = mono_unicode_to_external (dest_name);
1840 if (utf8_dest_name == NULL) {
1842 g_message ("%s: unicode conversion returned NULL", __func__);
1846 SetLastError (ERROR_INVALID_NAME);
1851 * In C# land we check for the existence of src, but not for dest.
1852 * We check it here and return the failure if dest exists and is not
1853 * the same file as src.
1855 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1856 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1857 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1859 g_free (utf8_dest_name);
1864 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1865 if (stat_dest.st_dev != stat_src.st_dev ||
1866 stat_dest.st_ino != stat_src.st_ino) {
1868 g_free (utf8_dest_name);
1869 SetLastError (ERROR_ALREADY_EXISTS);
1874 /* Check to make sure sharing allows us to open the file for
1875 * writing. See bug 377049.
1877 * Do the checks that don't need an open file descriptor, for
1878 * simplicity's sake. If we really have to do the full checks
1879 * then we can implement that later.
1881 if (share_allows_open (&stat_src, 0, GENERIC_WRITE,
1882 &shareinfo) == FALSE) {
1883 SetLastError (ERROR_SHARING_VIOLATION);
1887 _wapi_handle_share_release (shareinfo);
1889 result = _wapi_rename (utf8_name, utf8_dest_name);
1893 switch(errno_copy) {
1895 SetLastError (ERROR_ALREADY_EXISTS);
1899 /* Ignore here, it is dealt with below */
1903 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1908 g_free (utf8_dest_name);
1910 if (result != 0 && errno_copy == EXDEV) {
1911 if (S_ISDIR (stat_src.st_mode)) {
1912 SetLastError (ERROR_NOT_SAME_DEVICE);
1915 /* Try a copy to the new location, and delete the source */
1916 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1917 /* CopyFile will set the error */
1921 return(DeleteFile (name));
1932 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1936 int buf_size = st_src->st_blksize;
1938 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1939 buf = (char *) malloc (buf_size);
1942 remain = read (src_fd, buf, buf_size);
1944 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1948 _wapi_set_last_error_from_errno ();
1958 while (remain > 0) {
1959 if ((n = write (dest_fd, wbuf, remain)) < 0) {
1960 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1964 _wapi_set_last_error_from_errno ();
1966 g_message ("%s: write failed.", __func__);
1983 * @name: a pointer to a NULL-terminated unicode string, that names
1984 * the file to be copied.
1985 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1986 * new name for the file.
1987 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1989 * Copies file @name to @dest_name
1991 * Return value: %TRUE on success, %FALSE otherwise.
1993 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1994 gboolean fail_if_exists)
1996 gchar *utf8_src, *utf8_dest;
1997 int src_fd, dest_fd;
1998 struct stat st, dest_st;
1999 gboolean ret = TRUE;
2003 g_message("%s: name is NULL", __func__);
2006 SetLastError (ERROR_INVALID_NAME);
2010 utf8_src = mono_unicode_to_external (name);
2011 if (utf8_src == NULL) {
2013 g_message ("%s: unicode conversion of source returned NULL",
2017 SetLastError (ERROR_INVALID_PARAMETER);
2021 if(dest_name==NULL) {
2023 g_message("%s: dest is NULL", __func__);
2027 SetLastError (ERROR_INVALID_NAME);
2031 utf8_dest = mono_unicode_to_external (dest_name);
2032 if (utf8_dest == NULL) {
2034 g_message ("%s: unicode conversion of dest returned NULL",
2038 SetLastError (ERROR_INVALID_PARAMETER);
2045 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2047 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2055 if (fstat (src_fd, &st) < 0) {
2056 _wapi_set_last_error_from_errno ();
2065 /* Before trying to open/create the dest, we need to report a 'file busy'
2066 * error if src and dest are actually the same file. We do the check here to take
2067 * advantage of the IOMAP capability */
2068 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
2069 st.st_ino == dest_st.st_ino) {
2075 SetLastError (ERROR_SHARING_VIOLATION);
2079 if (fail_if_exists) {
2080 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2082 /* FIXME: it kinda sucks that this code path potentially scans
2083 * the directory twice due to the weird SetLastError()
2085 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2087 /* The file does not exist, try creating it */
2088 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2090 /* Apparently this error is set if we
2091 * overwrite the dest file
2093 SetLastError (ERROR_ALREADY_EXISTS);
2097 _wapi_set_last_error_from_errno ();
2106 if (!write_file (src_fd, dest_fd, &st, TRUE))
2118 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2124 g_message ("%s: %s is NULL", __func__, arg_name);
2126 SetLastError (ERROR_INVALID_NAME);
2130 utf8_ret = mono_unicode_to_external (arg);
2131 if (utf8_ret == NULL) {
2133 g_message ("%s: unicode conversion of %s returned NULL",
2134 __func__, arg_name);
2136 SetLastError (ERROR_INVALID_PARAMETER);
2144 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2145 const gunichar2 *backupFileName, guint32 replaceFlags,
2146 gpointer exclude, gpointer reserved)
2148 int result, errno_copy, backup_fd = -1,replaced_fd = -1;
2149 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2150 struct stat stBackup;
2151 gboolean ret = FALSE;
2153 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2155 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2156 goto replace_cleanup;
2157 if (backupFileName != NULL) {
2158 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2159 goto replace_cleanup;
2162 if (utf8_backupFileName) {
2163 // Open the backup file for read so we can restore the file if an error occurs.
2164 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2165 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2168 goto replace_cleanup;
2171 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2174 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2175 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2176 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2177 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2180 if (replaced_fd == -1)
2181 goto replace_cleanup;
2183 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2186 goto replace_cleanup;
2192 g_free (utf8_replacedFileName);
2193 g_free (utf8_replacementFileName);
2194 g_free (utf8_backupFileName);
2195 if (backup_fd != -1)
2197 if (replaced_fd != -1)
2198 close (replaced_fd);
2204 * @stdhandle: specifies the file descriptor
2206 * Returns a handle for stdin, stdout, or stderr. Always returns the
2207 * same handle for the same @stdhandle.
2209 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2212 static mono_mutex_t stdhandle_mutex = MONO_MUTEX_INITIALIZER;
2214 gpointer GetStdHandle(WapiStdHandle stdhandle)
2216 struct _WapiHandle_file *file_handle;
2223 case STD_INPUT_HANDLE:
2228 case STD_OUTPUT_HANDLE:
2233 case STD_ERROR_HANDLE:
2240 g_message("%s: unknown standard handle type", __func__);
2243 SetLastError (ERROR_INVALID_PARAMETER);
2244 return(INVALID_HANDLE_VALUE);
2247 handle = GINT_TO_POINTER (fd);
2249 pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2250 (void *)&stdhandle_mutex);
2251 thr_ret = mono_mutex_lock (&stdhandle_mutex);
2252 g_assert (thr_ret == 0);
2254 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2255 (gpointer *)&file_handle);
2257 /* Need to create this console handle */
2258 handle = _wapi_stdhandle_create (fd, name);
2260 if (handle == INVALID_HANDLE_VALUE) {
2261 SetLastError (ERROR_NO_MORE_FILES);
2265 /* Add a reference to this handle */
2266 _wapi_handle_ref (handle);
2270 thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2271 g_assert (thr_ret == 0);
2272 pthread_cleanup_pop (0);
2279 * @handle: The file handle to read from. The handle must have
2280 * %GENERIC_READ access.
2281 * @buffer: The buffer to store read data in
2282 * @numbytes: The maximum number of bytes to read
2283 * @bytesread: The actual number of bytes read is stored here. This
2284 * value can be zero if the handle is positioned at the end of the
2286 * @overlapped: points to a required %WapiOverlapped structure if
2287 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2290 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2291 * function reads up to @numbytes bytes from the file from the current
2292 * file position, and stores them in @buffer. If there are not enough
2293 * bytes left in the file, just the amount available will be read.
2294 * The actual number of bytes read is stored in @bytesread.
2296 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2297 * file position is ignored and the read position is taken from data
2298 * in the @overlapped structure.
2300 * Return value: %TRUE if the read succeeds (even if no bytes were
2301 * read due to an attempt to read past the end of the file), %FALSE on
2304 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2305 guint32 *bytesread, WapiOverlapped *overlapped)
2307 WapiHandleType type;
2309 type = _wapi_handle_type (handle);
2311 if(io_ops[type].readfile==NULL) {
2312 SetLastError (ERROR_INVALID_HANDLE);
2316 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2322 * @handle: The file handle to write to. The handle must have
2323 * %GENERIC_WRITE access.
2324 * @buffer: The buffer to read data from.
2325 * @numbytes: The maximum number of bytes to write.
2326 * @byteswritten: The actual number of bytes written is stored here.
2327 * If the handle is positioned at the file end, the length of the file
2328 * is extended. This parameter may be %NULL.
2329 * @overlapped: points to a required %WapiOverlapped structure if
2330 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2333 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2334 * function writes up to @numbytes bytes from @buffer to the file at
2335 * the current file position. If @handle is positioned at the end of
2336 * the file, the file is extended. The actual number of bytes written
2337 * is stored in @byteswritten.
2339 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2340 * file position is ignored and the write position is taken from data
2341 * in the @overlapped structure.
2343 * Return value: %TRUE if the write succeeds, %FALSE on error.
2345 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2346 guint32 *byteswritten, WapiOverlapped *overlapped)
2348 WapiHandleType type;
2350 type = _wapi_handle_type (handle);
2352 if(io_ops[type].writefile==NULL) {
2353 SetLastError (ERROR_INVALID_HANDLE);
2357 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2363 * @handle: Handle to open file. The handle must have
2364 * %GENERIC_WRITE access.
2366 * Flushes buffers of the file and causes all unwritten data to
2369 * Return value: %TRUE on success, %FALSE otherwise.
2371 gboolean FlushFileBuffers(gpointer handle)
2373 WapiHandleType type;
2375 type = _wapi_handle_type (handle);
2377 if(io_ops[type].flushfile==NULL) {
2378 SetLastError (ERROR_INVALID_HANDLE);
2382 return(io_ops[type].flushfile (handle));
2387 * @handle: The file handle to set. The handle must have
2388 * %GENERIC_WRITE access.
2390 * Moves the end-of-file position to the current position of the file
2391 * pointer. This function is used to truncate or extend a file.
2393 * Return value: %TRUE on success, %FALSE otherwise.
2395 gboolean SetEndOfFile(gpointer handle)
2397 WapiHandleType type;
2399 type = _wapi_handle_type (handle);
2401 if (io_ops[type].setendoffile == NULL) {
2402 SetLastError (ERROR_INVALID_HANDLE);
2406 return(io_ops[type].setendoffile (handle));
2411 * @handle: The file handle to set. The handle must have
2412 * %GENERIC_READ or %GENERIC_WRITE access.
2413 * @movedistance: Low 32 bits of a signed value that specifies the
2414 * number of bytes to move the file pointer.
2415 * @highmovedistance: Pointer to the high 32 bits of a signed value
2416 * that specifies the number of bytes to move the file pointer, or
2418 * @method: The starting point for the file pointer move.
2420 * Sets the file pointer of an open file.
2422 * The distance to move the file pointer is calculated from
2423 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2424 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2425 * is the low 32 bits and @highmovedistance a pointer to the high 32
2426 * bits of a 64 bit signed value. A positive distance moves the file
2427 * pointer forward from the position specified by @method; a negative
2428 * distance moves the file pointer backward.
2430 * If the library is compiled without large file support,
2431 * @highmovedistance is ignored and its value is set to zero on a
2432 * successful return.
2434 * Return value: On success, the low 32 bits of the new file pointer.
2435 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2436 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2438 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2439 gint32 *highmovedistance, WapiSeekMethod method)
2441 WapiHandleType type;
2443 type = _wapi_handle_type (handle);
2445 if (io_ops[type].seek == NULL) {
2446 SetLastError (ERROR_INVALID_HANDLE);
2447 return(INVALID_SET_FILE_POINTER);
2450 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2456 * @handle: The file handle to test.
2458 * Finds the type of file @handle.
2460 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2461 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2462 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2463 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2465 WapiFileType GetFileType(gpointer handle)
2467 WapiHandleType type;
2469 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2470 SetLastError (ERROR_INVALID_HANDLE);
2471 return(FILE_TYPE_UNKNOWN);
2474 type = _wapi_handle_type (handle);
2476 if (io_ops[type].getfiletype == NULL) {
2477 SetLastError (ERROR_INVALID_HANDLE);
2478 return(FILE_TYPE_UNKNOWN);
2481 return(io_ops[type].getfiletype ());
2486 * @handle: The file handle to query. The handle must have
2487 * %GENERIC_READ or %GENERIC_WRITE access.
2488 * @highsize: If non-%NULL, the high 32 bits of the file size are
2491 * Retrieves the size of the file @handle.
2493 * If the library is compiled without large file support, @highsize
2494 * has its value set to zero on a successful return.
2496 * Return value: On success, the low 32 bits of the file size. If
2497 * @highsize is non-%NULL then the high 32 bits of the file size are
2498 * stored here. On failure %INVALID_FILE_SIZE is returned.
2500 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2502 WapiHandleType type;
2504 type = _wapi_handle_type (handle);
2506 if (io_ops[type].getfilesize == NULL) {
2507 SetLastError (ERROR_INVALID_HANDLE);
2508 return(INVALID_FILE_SIZE);
2511 return(io_ops[type].getfilesize (handle, highsize));
2516 * @handle: The file handle to query. The handle must have
2517 * %GENERIC_READ access.
2518 * @create_time: Points to a %WapiFileTime structure to receive the
2519 * number of ticks since the epoch that file was created. May be
2521 * @last_access: Points to a %WapiFileTime structure to receive the
2522 * number of ticks since the epoch when file was last accessed. May be
2524 * @last_write: Points to a %WapiFileTime structure to receive the
2525 * number of ticks since the epoch when file was last written to. May
2528 * Finds the number of ticks since the epoch that the file referenced
2529 * by @handle was created, last accessed and last modified. A tick is
2530 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2533 * Create time isn't recorded on POSIX file systems or reported by
2534 * stat(2), so that time is guessed by returning the oldest of the
2537 * Return value: %TRUE on success, %FALSE otherwise.
2539 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2540 WapiFileTime *last_access, WapiFileTime *last_write)
2542 WapiHandleType type;
2544 type = _wapi_handle_type (handle);
2546 if (io_ops[type].getfiletime == NULL) {
2547 SetLastError (ERROR_INVALID_HANDLE);
2551 return(io_ops[type].getfiletime (handle, create_time, last_access,
2557 * @handle: The file handle to set. The handle must have
2558 * %GENERIC_WRITE access.
2559 * @create_time: Points to a %WapiFileTime structure that contains the
2560 * number of ticks since the epoch that the file was created. May be
2562 * @last_access: Points to a %WapiFileTime structure that contains the
2563 * number of ticks since the epoch when the file was last accessed.
2565 * @last_write: Points to a %WapiFileTime structure that contains the
2566 * number of ticks since the epoch when the file was last written to.
2569 * Sets the number of ticks since the epoch that the file referenced
2570 * by @handle was created, last accessed or last modified. A tick is
2571 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2574 * Create time isn't recorded on POSIX file systems, and is ignored.
2576 * Return value: %TRUE on success, %FALSE otherwise.
2578 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2579 const WapiFileTime *last_access,
2580 const WapiFileTime *last_write)
2582 WapiHandleType type;
2584 type = _wapi_handle_type (handle);
2586 if (io_ops[type].setfiletime == NULL) {
2587 SetLastError (ERROR_INVALID_HANDLE);
2591 return(io_ops[type].setfiletime (handle, create_time, last_access,
2595 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2596 * January 1 1601 GMT
2599 #define TICKS_PER_MILLISECOND 10000L
2600 #define TICKS_PER_SECOND 10000000L
2601 #define TICKS_PER_MINUTE 600000000L
2602 #define TICKS_PER_HOUR 36000000000LL
2603 #define TICKS_PER_DAY 864000000000LL
2605 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2607 static const guint16 mon_yday[2][13]={
2608 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2609 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2613 * FileTimeToSystemTime:
2614 * @file_time: Points to a %WapiFileTime structure that contains the
2615 * number of ticks to convert.
2616 * @system_time: Points to a %WapiSystemTime structure to receive the
2619 * Converts a tick count into broken-out time values.
2621 * Return value: %TRUE on success, %FALSE otherwise.
2623 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2624 WapiSystemTime *system_time)
2626 gint64 file_ticks, totaldays, rem, y;
2629 if(system_time==NULL) {
2631 g_message("%s: system_time NULL", __func__);
2634 SetLastError (ERROR_INVALID_PARAMETER);
2638 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2639 file_time->dwLowDateTime;
2641 /* Really compares if file_ticks>=0x8000000000000000
2642 * (LLONG_MAX+1) but we're working with a signed value for the
2643 * year and day calculation to work later
2647 g_message("%s: file_time too big", __func__);
2650 SetLastError (ERROR_INVALID_PARAMETER);
2654 totaldays=(file_ticks / TICKS_PER_DAY);
2655 rem = file_ticks % TICKS_PER_DAY;
2657 g_message("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2660 system_time->wHour=rem/TICKS_PER_HOUR;
2661 rem %= TICKS_PER_HOUR;
2663 g_message("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2666 system_time->wMinute = rem / TICKS_PER_MINUTE;
2667 rem %= TICKS_PER_MINUTE;
2669 g_message("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2673 system_time->wSecond = rem / TICKS_PER_SECOND;
2674 rem %= TICKS_PER_SECOND;
2676 g_message("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2680 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2682 g_message("%s: Milliseconds: %d", __func__,
2683 system_time->wMilliseconds);
2686 /* January 1, 1601 was a Monday, according to Emacs calendar */
2687 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2689 g_message("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2692 /* This algorithm to find year and month given days from epoch
2697 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2698 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2700 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2701 /* Guess a corrected year, assuming 365 days per year */
2702 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2704 g_message("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2707 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2708 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2711 /* Adjust days and y to match the guessed year. */
2712 totaldays -= ((yg - y) * 365
2713 + LEAPS_THRU_END_OF (yg - 1)
2714 - LEAPS_THRU_END_OF (y - 1));
2716 g_message("%s: totaldays: %lld", __func__, totaldays);
2720 g_message("%s: y: %lld", __func__, y);
2724 system_time->wYear = y;
2726 g_message("%s: Year: %d", __func__, system_time->wYear);
2729 ip = mon_yday[isleap(y)];
2731 for(y=11; totaldays < ip[y]; --y) {
2736 g_message("%s: totaldays: %lld", __func__, totaldays);
2739 system_time->wMonth = y + 1;
2741 g_message("%s: Month: %d", __func__, system_time->wMonth);
2744 system_time->wDay = totaldays + 1;
2746 g_message("%s: Day: %d", __func__, system_time->wDay);
2752 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2754 struct _WapiHandle_find find_handle = {0};
2756 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2759 if (pattern == NULL) {
2761 g_message ("%s: pattern is NULL", __func__);
2764 SetLastError (ERROR_PATH_NOT_FOUND);
2765 return(INVALID_HANDLE_VALUE);
2768 utf8_pattern = mono_unicode_to_external (pattern);
2769 if (utf8_pattern == NULL) {
2771 g_message ("%s: unicode conversion returned NULL", __func__);
2774 SetLastError (ERROR_INVALID_NAME);
2775 return(INVALID_HANDLE_VALUE);
2779 g_message ("%s: looking for [%s]", __func__, utf8_pattern);
2782 /* Figure out which bit of the pattern is the directory */
2783 dir_part = _wapi_dirname (utf8_pattern);
2784 entry_part = _wapi_basename (utf8_pattern);
2787 /* Don't do this check for now, it breaks if directories
2788 * really do have metachars in their names (see bug 58116).
2789 * FIXME: Figure out a better solution to keep some checks...
2791 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2792 SetLastError (ERROR_INVALID_NAME);
2794 g_free (entry_part);
2795 g_free (utf8_pattern);
2796 return(INVALID_HANDLE_VALUE);
2800 /* The pattern can specify a directory or a set of files.
2802 * The pattern can have wildcard characters ? and *, but only
2803 * in the section after the last directory delimiter. (Return
2804 * ERROR_INVALID_NAME if there are wildcards in earlier path
2805 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2806 * means "match one character", "??" seems to mean "match one
2807 * or two characters", "???" seems to mean "match one, two or
2808 * three characters", etc. Windows will also try and match
2809 * the mangled "short name" of files, so 8 character patterns
2810 * with wildcards will show some surprising results.
2812 * All the written documentation I can find says that '?'
2813 * should only match one character, and doesn't mention '??',
2814 * '???' etc. I'm going to assume that the strict behaviour
2815 * (ie '???' means three and only three characters) is the
2816 * correct one, because that lets me use fnmatch(3) rather
2817 * than mess around with regexes.
2820 find_handle.namelist = NULL;
2821 result = _wapi_io_scandir (dir_part, entry_part,
2822 &find_handle.namelist);
2825 /* No files, which windows seems to call
2828 SetLastError (ERROR_FILE_NOT_FOUND);
2829 g_free (utf8_pattern);
2830 g_free (entry_part);
2832 return (INVALID_HANDLE_VALUE);
2837 gint errnum = errno;
2839 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2841 g_message ("%s: scandir error: %s", __func__,
2842 g_strerror (errnum));
2844 g_free (utf8_pattern);
2845 g_free (entry_part);
2847 return (INVALID_HANDLE_VALUE);
2850 g_free (utf8_pattern);
2851 g_free (entry_part);
2854 g_message ("%s: Got %d matches", __func__, result);
2857 find_handle.dir_part = dir_part;
2858 find_handle.num = result;
2859 find_handle.count = 0;
2861 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2862 if (handle == _WAPI_HANDLE_INVALID) {
2863 g_warning ("%s: error creating find handle", __func__);
2865 g_free (entry_part);
2866 g_free (utf8_pattern);
2867 SetLastError (ERROR_GEN_FAILURE);
2869 return(INVALID_HANDLE_VALUE);
2872 if (handle != INVALID_HANDLE_VALUE &&
2873 !FindNextFile (handle, find_data)) {
2875 SetLastError (ERROR_NO_MORE_FILES);
2876 handle = INVALID_HANDLE_VALUE;
2882 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2884 struct _WapiHandle_find *find_handle;
2886 struct stat buf, linkbuf;
2889 gchar *utf8_filename, *utf8_basename;
2890 gunichar2 *utf16_basename;
2894 gboolean ret = FALSE;
2896 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2897 (gpointer *)&find_handle);
2899 g_warning ("%s: error looking up find handle %p", __func__,
2901 SetLastError (ERROR_INVALID_HANDLE);
2905 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2907 thr_ret = _wapi_handle_lock_handle (handle);
2908 g_assert (thr_ret == 0);
2911 if (find_handle->count >= find_handle->num) {
2912 SetLastError (ERROR_NO_MORE_FILES);
2916 /* stat next match */
2918 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2920 result = _wapi_stat (filename, &buf);
2921 if (result == -1 && errno == ENOENT) {
2922 /* Might be a dangling symlink */
2923 result = _wapi_lstat (filename, &buf);
2928 g_message ("%s: stat failed: %s", __func__, filename);
2935 result = _wapi_lstat (filename, &linkbuf);
2938 g_message ("%s: lstat failed: %s", __func__, filename);
2945 utf8_filename = mono_utf8_from_external (filename);
2946 if (utf8_filename == NULL) {
2947 /* We couldn't turn this filename into utf8 (eg the
2948 * encoding of the name wasn't convertible), so just
2951 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2959 g_message ("%s: Found [%s]", __func__, utf8_filename);
2962 /* fill data block */
2964 if (buf.st_mtime < buf.st_ctime)
2965 create_time = buf.st_mtime;
2967 create_time = buf.st_ctime;
2969 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2971 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2972 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2973 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2975 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2976 find_data->nFileSizeHigh = 0;
2977 find_data->nFileSizeLow = 0;
2979 find_data->nFileSizeHigh = buf.st_size >> 32;
2980 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2983 find_data->dwReserved0 = 0;
2984 find_data->dwReserved1 = 0;
2986 utf8_basename = _wapi_basename (utf8_filename);
2987 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2989 if(utf16_basename==NULL) {
2990 g_free (utf8_basename);
2991 g_free (utf8_filename);
2996 /* utf16 is 2 * utf8 */
2999 memset (find_data->cFileName, '\0', (MAX_PATH*2));
3001 /* Truncating a utf16 string like this might leave the last
3004 memcpy (find_data->cFileName, utf16_basename,
3005 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3007 find_data->cAlternateFileName [0] = 0; /* not used */
3009 g_free (utf8_basename);
3010 g_free (utf8_filename);
3011 g_free (utf16_basename);
3014 thr_ret = _wapi_handle_unlock_handle (handle);
3015 g_assert (thr_ret == 0);
3016 pthread_cleanup_pop (0);
3023 * @wapi_handle: the find handle to close.
3025 * Closes find handle @wapi_handle
3027 * Return value: %TRUE on success, %FALSE otherwise.
3029 gboolean FindClose (gpointer handle)
3031 struct _WapiHandle_find *find_handle;
3035 if (handle == NULL) {
3036 SetLastError (ERROR_INVALID_HANDLE);
3040 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
3041 (gpointer *)&find_handle);
3043 g_warning ("%s: error looking up find handle %p", __func__,
3045 SetLastError (ERROR_INVALID_HANDLE);
3049 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
3051 thr_ret = _wapi_handle_lock_handle (handle);
3052 g_assert (thr_ret == 0);
3054 g_strfreev (find_handle->namelist);
3055 g_free (find_handle->dir_part);
3057 thr_ret = _wapi_handle_unlock_handle (handle);
3058 g_assert (thr_ret == 0);
3059 pthread_cleanup_pop (0);
3061 _wapi_handle_unref (handle);
3068 * @name: a pointer to a NULL-terminated unicode string, that names
3069 * the directory to be created.
3070 * @security: ignored for now
3072 * Creates directory @name
3074 * Return value: %TRUE on success, %FALSE otherwise.
3076 gboolean CreateDirectory (const gunichar2 *name,
3077 WapiSecurityAttributes *security)
3084 g_message("%s: name is NULL", __func__);
3087 SetLastError (ERROR_INVALID_NAME);
3091 utf8_name = mono_unicode_to_external (name);
3092 if (utf8_name == NULL) {
3094 g_message ("%s: unicode conversion returned NULL", __func__);
3097 SetLastError (ERROR_INVALID_NAME);
3101 result = _wapi_mkdir (utf8_name, 0777);
3108 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3115 * @name: a pointer to a NULL-terminated unicode string, that names
3116 * the directory to be removed.
3118 * Removes directory @name
3120 * Return value: %TRUE on success, %FALSE otherwise.
3122 gboolean RemoveDirectory (const gunichar2 *name)
3129 g_message("%s: name is NULL", __func__);
3132 SetLastError (ERROR_INVALID_NAME);
3136 utf8_name = mono_unicode_to_external (name);
3137 if (utf8_name == NULL) {
3139 g_message ("%s: unicode conversion returned NULL", __func__);
3142 SetLastError (ERROR_INVALID_NAME);
3146 result = _wapi_rmdir (utf8_name);
3148 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3159 * GetFileAttributes:
3160 * @name: a pointer to a NULL-terminated unicode filename.
3162 * Gets the attributes for @name;
3164 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3166 guint32 GetFileAttributes (const gunichar2 *name)
3169 struct stat buf, linkbuf;
3175 g_message("%s: name is NULL", __func__);
3178 SetLastError (ERROR_INVALID_NAME);
3182 utf8_name = mono_unicode_to_external (name);
3183 if (utf8_name == NULL) {
3185 g_message ("%s: unicode conversion returned NULL", __func__);
3188 SetLastError (ERROR_INVALID_PARAMETER);
3189 return (INVALID_FILE_ATTRIBUTES);
3192 result = _wapi_stat (utf8_name, &buf);
3193 if (result == -1 && errno == ENOENT) {
3194 /* Might be a dangling symlink... */
3195 result = _wapi_lstat (utf8_name, &buf);
3199 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3201 return (INVALID_FILE_ATTRIBUTES);
3204 result = _wapi_lstat (utf8_name, &linkbuf);
3206 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3208 return (INVALID_FILE_ATTRIBUTES);
3211 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3219 * GetFileAttributesEx:
3220 * @name: a pointer to a NULL-terminated unicode filename.
3221 * @level: must be GetFileExInfoStandard
3222 * @info: pointer to a WapiFileAttributesData structure
3224 * Gets attributes, size and filetimes for @name;
3226 * Return value: %TRUE on success, %FALSE on failure
3228 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3231 WapiFileAttributesData *data;
3233 struct stat buf, linkbuf;
3237 if (level != GetFileExInfoStandard) {
3239 g_message ("%s: info level %d not supported.", __func__,
3243 SetLastError (ERROR_INVALID_PARAMETER);
3249 g_message("%s: name is NULL", __func__);
3252 SetLastError (ERROR_INVALID_NAME);
3256 utf8_name = mono_unicode_to_external (name);
3257 if (utf8_name == NULL) {
3259 g_message ("%s: unicode conversion returned NULL", __func__);
3262 SetLastError (ERROR_INVALID_PARAMETER);
3266 result = _wapi_stat (utf8_name, &buf);
3267 if (result == -1 && errno == ENOENT) {
3268 /* Might be a dangling symlink... */
3269 result = _wapi_lstat (utf8_name, &buf);
3273 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3278 result = _wapi_lstat (utf8_name, &linkbuf);
3280 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3285 /* fill data block */
3287 data = (WapiFileAttributesData *)info;
3289 if (buf.st_mtime < buf.st_ctime)
3290 create_time = buf.st_mtime;
3292 create_time = buf.st_ctime;
3294 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3300 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3301 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3302 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3304 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3305 data->nFileSizeHigh = 0;
3306 data->nFileSizeLow = 0;
3309 data->nFileSizeHigh = buf.st_size >> 32;
3310 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3318 * @name: name of file
3319 * @attrs: attributes to set
3321 * Changes the attributes on a named file.
3323 * Return value: %TRUE on success, %FALSE on failure.
3325 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3327 /* FIXME: think of something clever to do on unix */
3333 * Currently we only handle one *internal* case, with a value that is
3334 * not standard: 0x80000000, which means `set executable bit'
3339 g_message("%s: name is NULL", __func__);
3342 SetLastError (ERROR_INVALID_NAME);
3346 utf8_name = mono_unicode_to_external (name);
3347 if (utf8_name == NULL) {
3349 g_message ("%s: unicode conversion returned NULL", __func__);
3352 SetLastError (ERROR_INVALID_NAME);
3356 result = _wapi_stat (utf8_name, &buf);
3358 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3363 /* Contrary to the documentation, ms allows NORMAL to be
3364 * specified along with other attributes, so dont bother to
3365 * catch that case here.
3367 if (attrs & FILE_ATTRIBUTE_READONLY) {
3368 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3370 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3373 /* Ignore the other attributes for now */
3375 if (attrs & 0x80000000){
3376 mode_t exec_mask = 0;
3378 if ((buf.st_mode & S_IRUSR) != 0)
3379 exec_mask |= S_IXUSR;
3381 if ((buf.st_mode & S_IRGRP) != 0)
3382 exec_mask |= S_IXGRP;
3384 if ((buf.st_mode & S_IROTH) != 0)
3385 exec_mask |= S_IXOTH;
3387 result = chmod (utf8_name, buf.st_mode | exec_mask);
3389 /* Don't bother to reset executable (might need to change this
3399 * GetCurrentDirectory
3400 * @length: size of the buffer
3401 * @buffer: pointer to buffer that recieves path
3403 * Retrieves the current directory for the current process.
3405 * Return value: number of characters in buffer on success, zero on failure
3407 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3409 gunichar2 *utf16_path;
3413 if (getcwd ((char*)buffer, length) == NULL) {
3414 if (errno == ERANGE) { /*buffer length is not big enough */
3415 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*/
3418 utf16_path = mono_unicode_from_external (path, &bytes);
3419 g_free (utf16_path);
3423 _wapi_set_last_error_from_errno ();
3427 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3428 count = (bytes/2)+1;
3429 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3431 /* Add the terminator */
3432 memset (buffer, '\0', bytes+2);
3433 memcpy (buffer, utf16_path, bytes);
3435 g_free (utf16_path);
3441 * SetCurrentDirectory
3442 * @path: path to new directory
3444 * Changes the directory path for the current process.
3446 * Return value: %TRUE on success, %FALSE on failure.
3448 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3454 SetLastError (ERROR_INVALID_PARAMETER);
3458 utf8_path = mono_unicode_to_external (path);
3459 if (_wapi_chdir (utf8_path) != 0) {
3460 _wapi_set_last_error_from_errno ();
3470 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3471 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3473 struct _WapiHandle_file pipe_read_handle = {0};
3474 struct _WapiHandle_file pipe_write_handle = {0};
3475 gpointer read_handle;
3476 gpointer write_handle;
3480 mono_once (&io_ops_once, io_ops_init);
3483 g_message ("%s: Creating pipe", __func__);
3489 g_message ("%s: Error creating pipe: %s", __func__,
3493 _wapi_set_last_error_from_errno ();
3497 if (filedes[0] >= _wapi_fd_reserve ||
3498 filedes[1] >= _wapi_fd_reserve) {
3500 g_message ("%s: File descriptor is too big", __func__);
3503 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3511 /* filedes[0] is open for reading, filedes[1] for writing */
3513 pipe_read_handle.fileaccess = GENERIC_READ;
3514 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3516 if (read_handle == _WAPI_HANDLE_INVALID) {
3517 g_warning ("%s: error creating pipe read handle", __func__);
3520 SetLastError (ERROR_GEN_FAILURE);
3525 pipe_write_handle.fileaccess = GENERIC_WRITE;
3526 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3527 &pipe_write_handle);
3528 if (write_handle == _WAPI_HANDLE_INVALID) {
3529 g_warning ("%s: error creating pipe write handle", __func__);
3530 _wapi_handle_unref (read_handle);
3534 SetLastError (ERROR_GEN_FAILURE);
3539 *readpipe = read_handle;
3540 *writepipe = write_handle;
3543 g_message ("%s: Returning pipe: read handle %p, write handle %p",
3544 __func__, read_handle, write_handle);
3550 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3552 gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3553 gunichar2 *tmpdir16=NULL;
3558 if(tmpdir[strlen (tmpdir)]!='/') {
3560 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3563 tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3564 if(tmpdir16==NULL) {
3572 g_message ("%s: Size %d smaller than needed (%ld)",
3573 __func__, len, dirlen+1);
3578 /* Add the terminator */
3579 memset (buf, '\0', bytes+2);
3580 memcpy (buf, tmpdir16, bytes);
3586 if(tmpdir16!=NULL) {
3594 #ifdef HAVE_GETFSSTAT
3595 /* Darwin has getfsstat */
3596 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3598 struct statfs *stats;
3601 glong length, total = 0;
3603 n = getfsstat (NULL, 0, MNT_NOWAIT);
3606 size = n * sizeof (struct statfs);
3607 stats = (struct statfs *) g_malloc (size);
3610 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3614 for (i = 0; i < n; i++){
3615 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3616 if (total + length < len){
3617 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3618 buf [total+length] = 0;
3621 total += length + 1;
3630 /* In-place octal sequence replacement */
3632 unescape_octal (gchar *str)
3641 while (*rptr != '\0') {
3642 if (*rptr == '\\') {
3645 c = (*(rptr++) - '0') << 6;
3646 c += (*(rptr++) - '0') << 3;
3647 c += *(rptr++) - '0';
3649 } else if (wptr != rptr) {
3658 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3659 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3660 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3665 guint32 buffer_index;
3666 guint32 mountpoint_index;
3667 guint32 field_number;
3668 guint32 allocated_size;
3669 guint32 fsname_index;
3670 guint32 fstype_index;
3671 gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3672 gchar *mountpoint_allocated;
3673 gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3674 gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3675 gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3678 gboolean check_mount_source;
3679 } LinuxMountInfoParseState;
3681 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3682 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3683 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3684 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3685 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3687 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3691 LinuxMountInfoParseState state;
3692 gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3694 memset (buf, 0, len * sizeof (gunichar2));
3695 fd = open ("/proc/self/mountinfo", O_RDONLY);
3697 parser = GetLogicalDriveStrings_MountInfo;
3699 fd = open ("/proc/mounts", O_RDONLY);
3701 parser = GetLogicalDriveStrings_Mounts;
3705 ret = GetLogicalDriveStrings_Mtab (len, buf);
3709 memset (&state, 0, sizeof (LinuxMountInfoParseState));
3710 state.field_number = 1;
3711 state.delimiter = ' ';
3713 while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3714 state.buffer_index = 0;
3716 while ((*parser)(len, buf, &state)) {
3717 if (state.buffer [state.buffer_index] == '\n') {
3718 gboolean quit = add_drive_string (len, buf, &state);
3719 state.field_number = 1;
3720 state.buffer_index++;
3721 if (state.mountpoint_allocated) {
3722 g_free (state.mountpoint_allocated);
3723 state.mountpoint_allocated = NULL;
3740 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3744 if (state->field_number == 1)
3745 state->check_mount_source = TRUE;
3747 while (state->buffer_index < (guint32)state->nbytes) {
3748 if (state->buffer [state->buffer_index] == state->delimiter) {
3749 state->field_number++;
3750 switch (state->field_number) {
3752 state->mountpoint_index = 0;
3756 if (state->mountpoint_allocated)
3757 state->mountpoint_allocated [state->mountpoint_index] = 0;
3759 state->mountpoint [state->mountpoint_index] = 0;
3763 ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3765 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3767 state->buffer_index = state->nbytes;
3770 state->buffer_index++;
3772 } else if (state->buffer [state->buffer_index] == '\n')
3775 switch (state->field_number) {
3777 if (state->check_mount_source) {
3778 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3779 /* We can ignore the rest, it's a device
3781 state->check_mount_source = FALSE;
3782 state->fsname [state->fsname_index++] = '/';
3785 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3786 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3791 append_to_mountpoint (state);
3795 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3796 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3800 state->buffer_index++;
3806 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3808 while (state->buffer_index < (guint32)state->nbytes) {
3809 if (state->buffer [state->buffer_index] == state->delimiter) {
3810 state->field_number++;
3811 switch (state->field_number) {
3813 state->mountpoint_index = 0;
3817 if (state->mountpoint_allocated)
3818 state->mountpoint_allocated [state->mountpoint_index] = 0;
3820 state->mountpoint [state->mountpoint_index] = 0;
3824 state->delimiter = '-';
3828 state->delimiter = ' ';
3832 state->check_mount_source = TRUE;
3835 state->buffer_index++;
3837 } else if (state->buffer [state->buffer_index] == '\n')
3840 switch (state->field_number) {
3842 append_to_mountpoint (state);
3846 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3847 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3851 if (state->check_mount_source) {
3852 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3853 /* We can ignore the rest, it's a device
3855 state->check_mount_source = FALSE;
3856 state->fsname [state->fsname_index++] = '/';
3859 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3860 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3865 state->buffer_index++;
3872 append_to_mountpoint (LinuxMountInfoParseState *state)
3874 gchar ch = state->buffer [state->buffer_index];
3875 if (state->mountpoint_allocated) {
3876 if (state->mountpoint_index >= state->allocated_size) {
3877 guint32 newsize = (state->allocated_size << 1) + 1;
3878 gchar *newbuf = g_malloc0 (newsize * sizeof (gchar));
3880 memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3881 g_free (state->mountpoint_allocated);
3882 state->mountpoint_allocated = newbuf;
3883 state->allocated_size = newsize;
3885 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3887 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3888 state->allocated_size = (state->mountpoint_index << 1) + 1;
3889 state->mountpoint_allocated = g_malloc0 (state->allocated_size * sizeof (gchar));
3890 memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3891 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3893 state->mountpoint [state->mountpoint_index++] = ch;
3898 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3900 gboolean quit = FALSE;
3901 gboolean ignore_entry;
3903 if (state->fsname_index == 1 && state->fsname [0] == '/')
3904 ignore_entry = FALSE;
3905 else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0)
3906 ignore_entry = TRUE;
3907 else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3908 /* Ignore GNOME's gvfs */
3909 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3910 ignore_entry = TRUE;
3912 ignore_entry = FALSE;
3914 ignore_entry = TRUE;
3916 if (!ignore_entry) {
3919 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3921 unescape_octal (mountpoint);
3922 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3923 if (state->total + length + 1 > len) {
3925 state->total = len * 2;
3928 memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3929 state->total += length;
3933 state->fsname_index = 0;
3934 state->fstype_index = 0;
3940 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3942 return GetLogicalDriveStrings_Mtab (len, buf);
3946 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3949 gunichar2 *ptr, *dir;
3950 glong length, total = 0;
3954 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3959 /* Sigh, mntent and friends don't work well.
3960 * It stops on the first line that doesn't begin with a '/'.
3961 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3962 fp = fopen ("/etc/mtab", "rt");
3964 fp = fopen ("/etc/mnttab", "rt");
3970 while (fgets (buffer, 512, fp) != NULL) {
3974 splitted = g_strsplit (buffer, " ", 0);
3975 if (!*splitted || !*(splitted + 1)) {
3976 g_strfreev (splitted);
3980 unescape_octal (*(splitted + 1));
3981 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3982 g_strfreev (splitted);
3983 if (total + length + 1 > len) {
3986 return len * 2; /* guess */
3989 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3991 total += length + 1;
3996 /* Commented out, does not work with my mtab!!! - Gonz */
3997 #ifdef NOTENABLED /* HAVE_MNTENT_H */
4001 gunichar2 *ptr, *dir;
4002 glong len, total = 0;
4005 fp = setmntent ("/etc/mtab", "rt");
4007 fp = setmntent ("/etc/mnttab", "rt");
4013 while ((mnt = getmntent (fp)) != NULL) {
4014 g_print ("GOT %s\n", mnt->mnt_dir);
4015 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
4016 if (total + len + 1 > len) {
4017 return len * 2; /* guess */
4020 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
4032 #if (defined(HAVE_STATVFS) || defined(HAVE_STATFS)) && !defined(PLATFORM_ANDROID)
4033 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4034 WapiULargeInteger *total_number_of_bytes,
4035 WapiULargeInteger *total_number_of_free_bytes)
4038 struct statvfs fsstat;
4039 #elif defined(HAVE_STATFS)
4040 struct statfs fsstat;
4042 gboolean isreadonly;
4043 gchar *utf8_path_name;
4045 unsigned long block_size;
4047 if (path_name == NULL) {
4048 utf8_path_name = g_strdup (g_get_current_dir());
4049 if (utf8_path_name == NULL) {
4050 SetLastError (ERROR_DIRECTORY);
4055 utf8_path_name = mono_unicode_to_external (path_name);
4056 if (utf8_path_name == NULL) {
4058 g_message("%s: unicode conversion returned NULL", __func__);
4061 SetLastError (ERROR_INVALID_NAME);
4068 ret = statvfs (utf8_path_name, &fsstat);
4069 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
4070 block_size = fsstat.f_frsize;
4071 #elif defined(HAVE_STATFS)
4072 ret = statfs (utf8_path_name, &fsstat);
4073 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
4074 block_size = fsstat.f_bsize;
4076 } while(ret == -1 && errno == EINTR);
4078 g_free(utf8_path_name);
4081 _wapi_set_last_error_from_errno ();
4083 g_message ("%s: statvfs failed: %s", __func__, strerror (errno));
4088 /* total number of free bytes for non-root */
4089 if (free_bytes_avail != NULL) {
4091 free_bytes_avail->QuadPart = 0;
4094 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
4098 /* total number of bytes available for non-root */
4099 if (total_number_of_bytes != NULL) {
4100 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
4103 /* total number of bytes available for root */
4104 if (total_number_of_free_bytes != NULL) {
4106 total_number_of_free_bytes->QuadPart = 0;
4109 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
4116 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4117 WapiULargeInteger *total_number_of_bytes,
4118 WapiULargeInteger *total_number_of_free_bytes)
4120 if (free_bytes_avail != NULL) {
4121 free_bytes_avail->QuadPart = (guint64) -1;
4124 if (total_number_of_bytes != NULL) {
4125 total_number_of_bytes->QuadPart = (guint64) -1;
4128 if (total_number_of_free_bytes != NULL) {
4129 total_number_of_free_bytes->QuadPart = (guint64) -1;
4137 * General Unix support
4142 const long fstypeid;
4144 const gchar* fstype;
4147 static _wapi_drive_type _wapi_drive_types[] = {
4149 { DRIVE_REMOTE, "afp" },
4150 { DRIVE_REMOTE, "autofs" },
4151 { DRIVE_CDROM, "cddafs" },
4152 { DRIVE_CDROM, "cd9660" },
4153 { DRIVE_RAMDISK, "devfs" },
4154 { DRIVE_FIXED, "exfat" },
4155 { DRIVE_RAMDISK, "fdesc" },
4156 { DRIVE_REMOTE, "ftp" },
4157 { DRIVE_FIXED, "hfs" },
4158 { DRIVE_FIXED, "msdos" },
4159 { DRIVE_REMOTE, "nfs" },
4160 { DRIVE_FIXED, "ntfs" },
4161 { DRIVE_REMOTE, "smbfs" },
4162 { DRIVE_FIXED, "udf" },
4163 { DRIVE_REMOTE, "webdav" },
4164 { DRIVE_UNKNOWN, NULL }
4166 { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
4167 { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
4168 { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
4169 { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
4170 { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
4171 { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
4172 { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
4173 { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
4174 { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
4175 { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
4176 { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
4177 { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
4178 { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
4179 { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
4180 { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
4181 { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
4182 { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
4183 { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4184 { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4185 { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4186 { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4187 { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4188 { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4189 { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4190 { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4191 { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4192 { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4193 { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4194 { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4195 { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4196 { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4197 { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4198 { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4199 { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4200 { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4201 { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4202 { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4203 { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4204 { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4205 { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4206 { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4207 { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4208 { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4209 { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4210 { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4211 { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4212 { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4213 { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4214 { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4215 { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4216 { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4217 { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4218 { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4219 { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4220 { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4221 { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4222 { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4223 { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4224 { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4225 { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4226 { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4227 { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4228 { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4229 { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4230 { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4231 { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4232 { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4233 { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4234 { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4235 { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4236 { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4237 { DRIVE_UNKNOWN, 0, NULL}
4239 { DRIVE_RAMDISK, "ramfs" },
4240 { DRIVE_RAMDISK, "tmpfs" },
4241 { DRIVE_RAMDISK, "proc" },
4242 { DRIVE_RAMDISK, "sysfs" },
4243 { DRIVE_RAMDISK, "debugfs" },
4244 { DRIVE_RAMDISK, "devpts" },
4245 { DRIVE_RAMDISK, "securityfs" },
4246 { DRIVE_CDROM, "iso9660" },
4247 { DRIVE_FIXED, "ext2" },
4248 { DRIVE_FIXED, "ext3" },
4249 { DRIVE_FIXED, "ext4" },
4250 { DRIVE_FIXED, "sysv" },
4251 { DRIVE_FIXED, "reiserfs" },
4252 { DRIVE_FIXED, "ufs" },
4253 { DRIVE_FIXED, "vfat" },
4254 { DRIVE_FIXED, "msdos" },
4255 { DRIVE_FIXED, "udf" },
4256 { DRIVE_FIXED, "hfs" },
4257 { DRIVE_FIXED, "hpfs" },
4258 { DRIVE_FIXED, "qnx4" },
4259 { DRIVE_FIXED, "ntfs" },
4260 { DRIVE_FIXED, "ntfs-3g" },
4261 { DRIVE_REMOTE, "smbfs" },
4262 { DRIVE_REMOTE, "fuse" },
4263 { DRIVE_REMOTE, "nfs" },
4264 { DRIVE_REMOTE, "nfs4" },
4265 { DRIVE_REMOTE, "cifs" },
4266 { DRIVE_REMOTE, "ncpfs" },
4267 { DRIVE_REMOTE, "coda" },
4268 { DRIVE_REMOTE, "afs" },
4269 { DRIVE_UNKNOWN, NULL }
4274 static guint32 _wapi_get_drive_type(long f_type)
4276 _wapi_drive_type *current;
4278 current = &_wapi_drive_types[0];
4279 while (current->drive_type != DRIVE_UNKNOWN) {
4280 if (current->fstypeid == f_type)
4281 return current->drive_type;
4285 return DRIVE_UNKNOWN;
4288 static guint32 _wapi_get_drive_type(const gchar* fstype)
4290 _wapi_drive_type *current;
4292 current = &_wapi_drive_types[0];
4293 while (current->drive_type != DRIVE_UNKNOWN) {
4294 if (strcmp (current->fstype, fstype) == 0)
4300 return current->drive_type;
4304 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4306 GetDriveTypeFromPath (const char *utf8_root_path_name)
4310 if (statfs (utf8_root_path_name, &buf) == -1)
4311 return DRIVE_UNKNOWN;
4313 return _wapi_get_drive_type (buf.f_fstypename);
4315 return _wapi_get_drive_type (buf.f_type);
4320 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4327 fp = fopen ("/etc/mtab", "rt");
4329 fp = fopen ("/etc/mnttab", "rt");
4331 return(DRIVE_UNKNOWN);
4334 drive_type = DRIVE_NO_ROOT_DIR;
4335 while (fgets (buffer, 512, fp) != NULL) {
4336 splitted = g_strsplit (buffer, " ", 0);
4337 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4338 g_strfreev (splitted);
4342 /* compare given root_path_name with the one from mtab,
4343 if length of utf8_root_path_name is zero it must be the root dir */
4344 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4345 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4346 drive_type = _wapi_get_drive_type (*(splitted + 2));
4347 g_strfreev (splitted);
4351 g_strfreev (splitted);
4359 guint32 GetDriveType(const gunichar2 *root_path_name)
4361 gchar *utf8_root_path_name;
4364 if (root_path_name == NULL) {
4365 utf8_root_path_name = g_strdup (g_get_current_dir());
4366 if (utf8_root_path_name == NULL) {
4367 return(DRIVE_NO_ROOT_DIR);
4371 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4372 if (utf8_root_path_name == NULL) {
4374 g_message("%s: unicode conversion returned NULL", __func__);
4376 return(DRIVE_NO_ROOT_DIR);
4379 /* strip trailing slash for compare below */
4380 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4381 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4384 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4385 g_free (utf8_root_path_name);
4387 return (drive_type);
4391 get_fstypename (gchar *utfpath)
4393 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4396 _wapi_drive_type *current;
4398 if (statfs (utfpath, &stat) == -1)
4401 return stat.f_fstypename;
4403 current = &_wapi_drive_types[0];
4404 while (current->drive_type != DRIVE_UNKNOWN) {
4405 if (stat.f_type == current->fstypeid)
4406 return current->fstype;
4416 /* Linux has struct statfs which has a different layout */
4417 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD)
4419 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4422 const gchar *fstypename;
4423 gboolean status = FALSE;
4426 // We only support getting the file system type
4427 if (fsbuffer == NULL)
4430 utfpath = mono_unicode_to_external (path);
4431 if ((fstypename = get_fstypename (utfpath)) != NULL){
4432 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4433 if (ret != NULL && len < fsbuffersize){
4434 memcpy (fsbuffer, ret, len * sizeof (gunichar2));