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() */
1744 /* Check to make sure sharing allows us to open the file for
1745 * writing. See bug 323389.
1747 * Do the checks that don't need an open file descriptor, for
1748 * simplicity's sake. If we really have to do the full checks
1749 * then we can implement that later.
1751 if (_wapi_stat (filename, &statbuf) < 0) {
1752 _wapi_set_last_path_error_from_errno (NULL, filename);
1757 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1758 &shareinfo) == FALSE) {
1759 SetLastError (ERROR_SHARING_VIOLATION);
1764 _wapi_handle_share_release (shareinfo);
1767 retval = _wapi_unlink (filename);
1770 _wapi_set_last_path_error_from_errno (NULL, filename);
1782 * @name: a pointer to a NULL-terminated unicode string, that names
1783 * the file to be moved.
1784 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1785 * new name for the file.
1787 * Renames file @name to @dest_name.
1788 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1789 * when it is the same file as the source. In that case it silently succeeds.
1791 * Return value: %TRUE on success, %FALSE otherwise.
1793 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1795 gchar *utf8_name, *utf8_dest_name;
1796 int result, errno_copy;
1797 struct stat stat_src, stat_dest;
1798 gboolean ret = FALSE;
1799 struct _WapiFileShare *shareinfo;
1803 g_message("%s: name is NULL", __func__);
1806 SetLastError (ERROR_INVALID_NAME);
1810 utf8_name = mono_unicode_to_external (name);
1811 if (utf8_name == NULL) {
1813 g_message ("%s: unicode conversion returned NULL", __func__);
1816 SetLastError (ERROR_INVALID_NAME);
1820 if(dest_name==NULL) {
1822 g_message("%s: name is NULL", __func__);
1826 SetLastError (ERROR_INVALID_NAME);
1830 utf8_dest_name = mono_unicode_to_external (dest_name);
1831 if (utf8_dest_name == NULL) {
1833 g_message ("%s: unicode conversion returned NULL", __func__);
1837 SetLastError (ERROR_INVALID_NAME);
1842 * In C# land we check for the existence of src, but not for dest.
1843 * We check it here and return the failure if dest exists and is not
1844 * the same file as src.
1846 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1847 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1848 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1850 g_free (utf8_dest_name);
1855 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1856 if (stat_dest.st_dev != stat_src.st_dev ||
1857 stat_dest.st_ino != stat_src.st_ino) {
1859 g_free (utf8_dest_name);
1860 SetLastError (ERROR_ALREADY_EXISTS);
1865 /* Check to make sure sharing allows us to open the file for
1866 * writing. See bug 377049.
1868 * Do the checks that don't need an open file descriptor, for
1869 * simplicity's sake. If we really have to do the full checks
1870 * then we can implement that later.
1872 if (share_allows_open (&stat_src, 0, GENERIC_WRITE,
1873 &shareinfo) == FALSE) {
1874 SetLastError (ERROR_SHARING_VIOLATION);
1878 _wapi_handle_share_release (shareinfo);
1880 result = _wapi_rename (utf8_name, utf8_dest_name);
1884 switch(errno_copy) {
1886 SetLastError (ERROR_ALREADY_EXISTS);
1890 /* Ignore here, it is dealt with below */
1894 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1899 g_free (utf8_dest_name);
1901 if (result != 0 && errno_copy == EXDEV) {
1902 if (S_ISDIR (stat_src.st_mode)) {
1903 SetLastError (ERROR_NOT_SAME_DEVICE);
1906 /* Try a copy to the new location, and delete the source */
1907 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1908 /* CopyFile will set the error */
1912 return(DeleteFile (name));
1923 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1927 int buf_size = st_src->st_blksize;
1929 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1930 buf = (char *) malloc (buf_size);
1933 remain = read (src_fd, buf, buf_size);
1935 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1939 _wapi_set_last_error_from_errno ();
1949 while (remain > 0) {
1950 if ((n = write (dest_fd, wbuf, remain)) < 0) {
1951 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1955 _wapi_set_last_error_from_errno ();
1957 g_message ("%s: write failed.", __func__);
1974 * @name: a pointer to a NULL-terminated unicode string, that names
1975 * the file to be copied.
1976 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1977 * new name for the file.
1978 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1980 * Copies file @name to @dest_name
1982 * Return value: %TRUE on success, %FALSE otherwise.
1984 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1985 gboolean fail_if_exists)
1987 gchar *utf8_src, *utf8_dest;
1988 int src_fd, dest_fd;
1989 struct stat st, dest_st;
1990 gboolean ret = TRUE;
1994 g_message("%s: name is NULL", __func__);
1997 SetLastError (ERROR_INVALID_NAME);
2001 utf8_src = mono_unicode_to_external (name);
2002 if (utf8_src == NULL) {
2004 g_message ("%s: unicode conversion of source returned NULL",
2008 SetLastError (ERROR_INVALID_PARAMETER);
2012 if(dest_name==NULL) {
2014 g_message("%s: dest is NULL", __func__);
2018 SetLastError (ERROR_INVALID_NAME);
2022 utf8_dest = mono_unicode_to_external (dest_name);
2023 if (utf8_dest == NULL) {
2025 g_message ("%s: unicode conversion of dest returned NULL",
2029 SetLastError (ERROR_INVALID_PARAMETER);
2036 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2038 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2046 if (fstat (src_fd, &st) < 0) {
2047 _wapi_set_last_error_from_errno ();
2056 /* Before trying to open/create the dest, we need to report a 'file busy'
2057 * error if src and dest are actually the same file. We do the check here to take
2058 * advantage of the IOMAP capability */
2059 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
2060 st.st_ino == dest_st.st_ino) {
2066 SetLastError (ERROR_SHARING_VIOLATION);
2070 if (fail_if_exists) {
2071 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2073 /* FIXME: it kinda sucks that this code path potentially scans
2074 * the directory twice due to the weird SetLastError()
2076 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2078 /* The file does not exist, try creating it */
2079 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2081 /* Apparently this error is set if we
2082 * overwrite the dest file
2084 SetLastError (ERROR_ALREADY_EXISTS);
2088 _wapi_set_last_error_from_errno ();
2097 if (!write_file (src_fd, dest_fd, &st, TRUE))
2109 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2115 g_message ("%s: %s is NULL", __func__, arg_name);
2117 SetLastError (ERROR_INVALID_NAME);
2121 utf8_ret = mono_unicode_to_external (arg);
2122 if (utf8_ret == NULL) {
2124 g_message ("%s: unicode conversion of %s returned NULL",
2125 __func__, arg_name);
2127 SetLastError (ERROR_INVALID_PARAMETER);
2135 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2136 const gunichar2 *backupFileName, guint32 replaceFlags,
2137 gpointer exclude, gpointer reserved)
2139 int result, errno_copy, backup_fd = -1,replaced_fd = -1;
2140 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2141 struct stat stBackup;
2142 gboolean ret = FALSE;
2144 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2146 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2147 goto replace_cleanup;
2148 if (backupFileName != NULL) {
2149 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2150 goto replace_cleanup;
2153 if (utf8_backupFileName) {
2154 // Open the backup file for read so we can restore the file if an error occurs.
2155 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2156 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2159 goto replace_cleanup;
2162 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2165 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2166 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2167 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2168 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2171 if (replaced_fd == -1)
2172 goto replace_cleanup;
2174 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2177 goto replace_cleanup;
2183 g_free (utf8_replacedFileName);
2184 g_free (utf8_replacementFileName);
2185 g_free (utf8_backupFileName);
2186 if (backup_fd != -1)
2188 if (replaced_fd != -1)
2189 close (replaced_fd);
2195 * @stdhandle: specifies the file descriptor
2197 * Returns a handle for stdin, stdout, or stderr. Always returns the
2198 * same handle for the same @stdhandle.
2200 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2203 static mono_mutex_t stdhandle_mutex = MONO_MUTEX_INITIALIZER;
2205 gpointer GetStdHandle(WapiStdHandle stdhandle)
2207 struct _WapiHandle_file *file_handle;
2214 case STD_INPUT_HANDLE:
2219 case STD_OUTPUT_HANDLE:
2224 case STD_ERROR_HANDLE:
2231 g_message("%s: unknown standard handle type", __func__);
2234 SetLastError (ERROR_INVALID_PARAMETER);
2235 return(INVALID_HANDLE_VALUE);
2238 handle = GINT_TO_POINTER (fd);
2240 pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2241 (void *)&stdhandle_mutex);
2242 thr_ret = mono_mutex_lock (&stdhandle_mutex);
2243 g_assert (thr_ret == 0);
2245 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2246 (gpointer *)&file_handle);
2248 /* Need to create this console handle */
2249 handle = _wapi_stdhandle_create (fd, name);
2251 if (handle == INVALID_HANDLE_VALUE) {
2252 SetLastError (ERROR_NO_MORE_FILES);
2256 /* Add a reference to this handle */
2257 _wapi_handle_ref (handle);
2261 thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2262 g_assert (thr_ret == 0);
2263 pthread_cleanup_pop (0);
2270 * @handle: The file handle to read from. The handle must have
2271 * %GENERIC_READ access.
2272 * @buffer: The buffer to store read data in
2273 * @numbytes: The maximum number of bytes to read
2274 * @bytesread: The actual number of bytes read is stored here. This
2275 * value can be zero if the handle is positioned at the end of the
2277 * @overlapped: points to a required %WapiOverlapped structure if
2278 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2281 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2282 * function reads up to @numbytes bytes from the file from the current
2283 * file position, and stores them in @buffer. If there are not enough
2284 * bytes left in the file, just the amount available will be read.
2285 * The actual number of bytes read is stored in @bytesread.
2287 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2288 * file position is ignored and the read position is taken from data
2289 * in the @overlapped structure.
2291 * Return value: %TRUE if the read succeeds (even if no bytes were
2292 * read due to an attempt to read past the end of the file), %FALSE on
2295 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2296 guint32 *bytesread, WapiOverlapped *overlapped)
2298 WapiHandleType type;
2300 type = _wapi_handle_type (handle);
2302 if(io_ops[type].readfile==NULL) {
2303 SetLastError (ERROR_INVALID_HANDLE);
2307 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2313 * @handle: The file handle to write to. The handle must have
2314 * %GENERIC_WRITE access.
2315 * @buffer: The buffer to read data from.
2316 * @numbytes: The maximum number of bytes to write.
2317 * @byteswritten: The actual number of bytes written is stored here.
2318 * If the handle is positioned at the file end, the length of the file
2319 * is extended. This parameter may be %NULL.
2320 * @overlapped: points to a required %WapiOverlapped structure if
2321 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2324 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2325 * function writes up to @numbytes bytes from @buffer to the file at
2326 * the current file position. If @handle is positioned at the end of
2327 * the file, the file is extended. The actual number of bytes written
2328 * is stored in @byteswritten.
2330 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2331 * file position is ignored and the write position is taken from data
2332 * in the @overlapped structure.
2334 * Return value: %TRUE if the write succeeds, %FALSE on error.
2336 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2337 guint32 *byteswritten, WapiOverlapped *overlapped)
2339 WapiHandleType type;
2341 type = _wapi_handle_type (handle);
2343 if(io_ops[type].writefile==NULL) {
2344 SetLastError (ERROR_INVALID_HANDLE);
2348 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2354 * @handle: Handle to open file. The handle must have
2355 * %GENERIC_WRITE access.
2357 * Flushes buffers of the file and causes all unwritten data to
2360 * Return value: %TRUE on success, %FALSE otherwise.
2362 gboolean FlushFileBuffers(gpointer handle)
2364 WapiHandleType type;
2366 type = _wapi_handle_type (handle);
2368 if(io_ops[type].flushfile==NULL) {
2369 SetLastError (ERROR_INVALID_HANDLE);
2373 return(io_ops[type].flushfile (handle));
2378 * @handle: The file handle to set. The handle must have
2379 * %GENERIC_WRITE access.
2381 * Moves the end-of-file position to the current position of the file
2382 * pointer. This function is used to truncate or extend a file.
2384 * Return value: %TRUE on success, %FALSE otherwise.
2386 gboolean SetEndOfFile(gpointer handle)
2388 WapiHandleType type;
2390 type = _wapi_handle_type (handle);
2392 if (io_ops[type].setendoffile == NULL) {
2393 SetLastError (ERROR_INVALID_HANDLE);
2397 return(io_ops[type].setendoffile (handle));
2402 * @handle: The file handle to set. The handle must have
2403 * %GENERIC_READ or %GENERIC_WRITE access.
2404 * @movedistance: Low 32 bits of a signed value that specifies the
2405 * number of bytes to move the file pointer.
2406 * @highmovedistance: Pointer to the high 32 bits of a signed value
2407 * that specifies the number of bytes to move the file pointer, or
2409 * @method: The starting point for the file pointer move.
2411 * Sets the file pointer of an open file.
2413 * The distance to move the file pointer is calculated from
2414 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2415 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2416 * is the low 32 bits and @highmovedistance a pointer to the high 32
2417 * bits of a 64 bit signed value. A positive distance moves the file
2418 * pointer forward from the position specified by @method; a negative
2419 * distance moves the file pointer backward.
2421 * If the library is compiled without large file support,
2422 * @highmovedistance is ignored and its value is set to zero on a
2423 * successful return.
2425 * Return value: On success, the low 32 bits of the new file pointer.
2426 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2427 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2429 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2430 gint32 *highmovedistance, WapiSeekMethod method)
2432 WapiHandleType type;
2434 type = _wapi_handle_type (handle);
2436 if (io_ops[type].seek == NULL) {
2437 SetLastError (ERROR_INVALID_HANDLE);
2438 return(INVALID_SET_FILE_POINTER);
2441 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2447 * @handle: The file handle to test.
2449 * Finds the type of file @handle.
2451 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2452 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2453 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2454 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2456 WapiFileType GetFileType(gpointer handle)
2458 WapiHandleType type;
2460 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2461 SetLastError (ERROR_INVALID_HANDLE);
2462 return(FILE_TYPE_UNKNOWN);
2465 type = _wapi_handle_type (handle);
2467 if (io_ops[type].getfiletype == NULL) {
2468 SetLastError (ERROR_INVALID_HANDLE);
2469 return(FILE_TYPE_UNKNOWN);
2472 return(io_ops[type].getfiletype ());
2477 * @handle: The file handle to query. The handle must have
2478 * %GENERIC_READ or %GENERIC_WRITE access.
2479 * @highsize: If non-%NULL, the high 32 bits of the file size are
2482 * Retrieves the size of the file @handle.
2484 * If the library is compiled without large file support, @highsize
2485 * has its value set to zero on a successful return.
2487 * Return value: On success, the low 32 bits of the file size. If
2488 * @highsize is non-%NULL then the high 32 bits of the file size are
2489 * stored here. On failure %INVALID_FILE_SIZE is returned.
2491 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2493 WapiHandleType type;
2495 type = _wapi_handle_type (handle);
2497 if (io_ops[type].getfilesize == NULL) {
2498 SetLastError (ERROR_INVALID_HANDLE);
2499 return(INVALID_FILE_SIZE);
2502 return(io_ops[type].getfilesize (handle, highsize));
2507 * @handle: The file handle to query. The handle must have
2508 * %GENERIC_READ access.
2509 * @create_time: Points to a %WapiFileTime structure to receive the
2510 * number of ticks since the epoch that file was created. May be
2512 * @last_access: Points to a %WapiFileTime structure to receive the
2513 * number of ticks since the epoch when file was last accessed. May be
2515 * @last_write: Points to a %WapiFileTime structure to receive the
2516 * number of ticks since the epoch when file was last written to. May
2519 * Finds the number of ticks since the epoch that the file referenced
2520 * by @handle was created, last accessed and last modified. A tick is
2521 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2524 * Create time isn't recorded on POSIX file systems or reported by
2525 * stat(2), so that time is guessed by returning the oldest of the
2528 * Return value: %TRUE on success, %FALSE otherwise.
2530 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2531 WapiFileTime *last_access, WapiFileTime *last_write)
2533 WapiHandleType type;
2535 type = _wapi_handle_type (handle);
2537 if (io_ops[type].getfiletime == NULL) {
2538 SetLastError (ERROR_INVALID_HANDLE);
2542 return(io_ops[type].getfiletime (handle, create_time, last_access,
2548 * @handle: The file handle to set. The handle must have
2549 * %GENERIC_WRITE access.
2550 * @create_time: Points to a %WapiFileTime structure that contains the
2551 * number of ticks since the epoch that the file was created. May be
2553 * @last_access: Points to a %WapiFileTime structure that contains the
2554 * number of ticks since the epoch when the file was last accessed.
2556 * @last_write: Points to a %WapiFileTime structure that contains the
2557 * number of ticks since the epoch when the file was last written to.
2560 * Sets the number of ticks since the epoch that the file referenced
2561 * by @handle was created, last accessed or last modified. A tick is
2562 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2565 * Create time isn't recorded on POSIX file systems, and is ignored.
2567 * Return value: %TRUE on success, %FALSE otherwise.
2569 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2570 const WapiFileTime *last_access,
2571 const WapiFileTime *last_write)
2573 WapiHandleType type;
2575 type = _wapi_handle_type (handle);
2577 if (io_ops[type].setfiletime == NULL) {
2578 SetLastError (ERROR_INVALID_HANDLE);
2582 return(io_ops[type].setfiletime (handle, create_time, last_access,
2586 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2587 * January 1 1601 GMT
2590 #define TICKS_PER_MILLISECOND 10000L
2591 #define TICKS_PER_SECOND 10000000L
2592 #define TICKS_PER_MINUTE 600000000L
2593 #define TICKS_PER_HOUR 36000000000LL
2594 #define TICKS_PER_DAY 864000000000LL
2596 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2598 static const guint16 mon_yday[2][13]={
2599 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2600 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2604 * FileTimeToSystemTime:
2605 * @file_time: Points to a %WapiFileTime structure that contains the
2606 * number of ticks to convert.
2607 * @system_time: Points to a %WapiSystemTime structure to receive the
2610 * Converts a tick count into broken-out time values.
2612 * Return value: %TRUE on success, %FALSE otherwise.
2614 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2615 WapiSystemTime *system_time)
2617 gint64 file_ticks, totaldays, rem, y;
2620 if(system_time==NULL) {
2622 g_message("%s: system_time NULL", __func__);
2625 SetLastError (ERROR_INVALID_PARAMETER);
2629 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2630 file_time->dwLowDateTime;
2632 /* Really compares if file_ticks>=0x8000000000000000
2633 * (LLONG_MAX+1) but we're working with a signed value for the
2634 * year and day calculation to work later
2638 g_message("%s: file_time too big", __func__);
2641 SetLastError (ERROR_INVALID_PARAMETER);
2645 totaldays=(file_ticks / TICKS_PER_DAY);
2646 rem = file_ticks % TICKS_PER_DAY;
2648 g_message("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2651 system_time->wHour=rem/TICKS_PER_HOUR;
2652 rem %= TICKS_PER_HOUR;
2654 g_message("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2657 system_time->wMinute = rem / TICKS_PER_MINUTE;
2658 rem %= TICKS_PER_MINUTE;
2660 g_message("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2664 system_time->wSecond = rem / TICKS_PER_SECOND;
2665 rem %= TICKS_PER_SECOND;
2667 g_message("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2671 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2673 g_message("%s: Milliseconds: %d", __func__,
2674 system_time->wMilliseconds);
2677 /* January 1, 1601 was a Monday, according to Emacs calendar */
2678 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2680 g_message("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2683 /* This algorithm to find year and month given days from epoch
2688 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2689 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2691 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2692 /* Guess a corrected year, assuming 365 days per year */
2693 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2695 g_message("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2698 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2699 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2702 /* Adjust days and y to match the guessed year. */
2703 totaldays -= ((yg - y) * 365
2704 + LEAPS_THRU_END_OF (yg - 1)
2705 - LEAPS_THRU_END_OF (y - 1));
2707 g_message("%s: totaldays: %lld", __func__, totaldays);
2711 g_message("%s: y: %lld", __func__, y);
2715 system_time->wYear = y;
2717 g_message("%s: Year: %d", __func__, system_time->wYear);
2720 ip = mon_yday[isleap(y)];
2722 for(y=11; totaldays < ip[y]; --y) {
2727 g_message("%s: totaldays: %lld", __func__, totaldays);
2730 system_time->wMonth = y + 1;
2732 g_message("%s: Month: %d", __func__, system_time->wMonth);
2735 system_time->wDay = totaldays + 1;
2737 g_message("%s: Day: %d", __func__, system_time->wDay);
2743 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2745 struct _WapiHandle_find find_handle = {0};
2747 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2750 if (pattern == NULL) {
2752 g_message ("%s: pattern is NULL", __func__);
2755 SetLastError (ERROR_PATH_NOT_FOUND);
2756 return(INVALID_HANDLE_VALUE);
2759 utf8_pattern = mono_unicode_to_external (pattern);
2760 if (utf8_pattern == NULL) {
2762 g_message ("%s: unicode conversion returned NULL", __func__);
2765 SetLastError (ERROR_INVALID_NAME);
2766 return(INVALID_HANDLE_VALUE);
2770 g_message ("%s: looking for [%s]", __func__, utf8_pattern);
2773 /* Figure out which bit of the pattern is the directory */
2774 dir_part = _wapi_dirname (utf8_pattern);
2775 entry_part = _wapi_basename (utf8_pattern);
2778 /* Don't do this check for now, it breaks if directories
2779 * really do have metachars in their names (see bug 58116).
2780 * FIXME: Figure out a better solution to keep some checks...
2782 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2783 SetLastError (ERROR_INVALID_NAME);
2785 g_free (entry_part);
2786 g_free (utf8_pattern);
2787 return(INVALID_HANDLE_VALUE);
2791 /* The pattern can specify a directory or a set of files.
2793 * The pattern can have wildcard characters ? and *, but only
2794 * in the section after the last directory delimiter. (Return
2795 * ERROR_INVALID_NAME if there are wildcards in earlier path
2796 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2797 * means "match one character", "??" seems to mean "match one
2798 * or two characters", "???" seems to mean "match one, two or
2799 * three characters", etc. Windows will also try and match
2800 * the mangled "short name" of files, so 8 character patterns
2801 * with wildcards will show some surprising results.
2803 * All the written documentation I can find says that '?'
2804 * should only match one character, and doesn't mention '??',
2805 * '???' etc. I'm going to assume that the strict behaviour
2806 * (ie '???' means three and only three characters) is the
2807 * correct one, because that lets me use fnmatch(3) rather
2808 * than mess around with regexes.
2811 find_handle.namelist = NULL;
2812 result = _wapi_io_scandir (dir_part, entry_part,
2813 &find_handle.namelist);
2816 /* No files, which windows seems to call
2819 SetLastError (ERROR_FILE_NOT_FOUND);
2820 g_free (utf8_pattern);
2821 g_free (entry_part);
2823 return (INVALID_HANDLE_VALUE);
2828 gint errnum = errno;
2830 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2832 g_message ("%s: scandir error: %s", __func__,
2833 g_strerror (errnum));
2835 g_free (utf8_pattern);
2836 g_free (entry_part);
2838 return (INVALID_HANDLE_VALUE);
2841 g_free (utf8_pattern);
2842 g_free (entry_part);
2845 g_message ("%s: Got %d matches", __func__, result);
2848 find_handle.dir_part = dir_part;
2849 find_handle.num = result;
2850 find_handle.count = 0;
2852 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2853 if (handle == _WAPI_HANDLE_INVALID) {
2854 g_warning ("%s: error creating find handle", __func__);
2856 g_free (entry_part);
2857 g_free (utf8_pattern);
2858 SetLastError (ERROR_GEN_FAILURE);
2860 return(INVALID_HANDLE_VALUE);
2863 if (handle != INVALID_HANDLE_VALUE &&
2864 !FindNextFile (handle, find_data)) {
2866 SetLastError (ERROR_NO_MORE_FILES);
2867 handle = INVALID_HANDLE_VALUE;
2873 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2875 struct _WapiHandle_find *find_handle;
2877 struct stat buf, linkbuf;
2880 gchar *utf8_filename, *utf8_basename;
2881 gunichar2 *utf16_basename;
2885 gboolean ret = FALSE;
2887 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2888 (gpointer *)&find_handle);
2890 g_warning ("%s: error looking up find handle %p", __func__,
2892 SetLastError (ERROR_INVALID_HANDLE);
2896 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2898 thr_ret = _wapi_handle_lock_handle (handle);
2899 g_assert (thr_ret == 0);
2902 if (find_handle->count >= find_handle->num) {
2903 SetLastError (ERROR_NO_MORE_FILES);
2907 /* stat next match */
2909 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2911 result = _wapi_stat (filename, &buf);
2912 if (result == -1 && errno == ENOENT) {
2913 /* Might be a dangling symlink */
2914 result = _wapi_lstat (filename, &buf);
2919 g_message ("%s: stat failed: %s", __func__, filename);
2926 result = _wapi_lstat (filename, &linkbuf);
2929 g_message ("%s: lstat failed: %s", __func__, filename);
2936 utf8_filename = mono_utf8_from_external (filename);
2937 if (utf8_filename == NULL) {
2938 /* We couldn't turn this filename into utf8 (eg the
2939 * encoding of the name wasn't convertible), so just
2942 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2950 g_message ("%s: Found [%s]", __func__, utf8_filename);
2953 /* fill data block */
2955 if (buf.st_mtime < buf.st_ctime)
2956 create_time = buf.st_mtime;
2958 create_time = buf.st_ctime;
2960 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2962 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2963 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2964 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2966 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2967 find_data->nFileSizeHigh = 0;
2968 find_data->nFileSizeLow = 0;
2970 find_data->nFileSizeHigh = buf.st_size >> 32;
2971 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2974 find_data->dwReserved0 = 0;
2975 find_data->dwReserved1 = 0;
2977 utf8_basename = _wapi_basename (utf8_filename);
2978 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2980 if(utf16_basename==NULL) {
2981 g_free (utf8_basename);
2982 g_free (utf8_filename);
2987 /* utf16 is 2 * utf8 */
2990 memset (find_data->cFileName, '\0', (MAX_PATH*2));
2992 /* Truncating a utf16 string like this might leave the last
2995 memcpy (find_data->cFileName, utf16_basename,
2996 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
2998 find_data->cAlternateFileName [0] = 0; /* not used */
3000 g_free (utf8_basename);
3001 g_free (utf8_filename);
3002 g_free (utf16_basename);
3005 thr_ret = _wapi_handle_unlock_handle (handle);
3006 g_assert (thr_ret == 0);
3007 pthread_cleanup_pop (0);
3014 * @wapi_handle: the find handle to close.
3016 * Closes find handle @wapi_handle
3018 * Return value: %TRUE on success, %FALSE otherwise.
3020 gboolean FindClose (gpointer handle)
3022 struct _WapiHandle_find *find_handle;
3026 if (handle == NULL) {
3027 SetLastError (ERROR_INVALID_HANDLE);
3031 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
3032 (gpointer *)&find_handle);
3034 g_warning ("%s: error looking up find handle %p", __func__,
3036 SetLastError (ERROR_INVALID_HANDLE);
3040 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
3042 thr_ret = _wapi_handle_lock_handle (handle);
3043 g_assert (thr_ret == 0);
3045 g_strfreev (find_handle->namelist);
3046 g_free (find_handle->dir_part);
3048 thr_ret = _wapi_handle_unlock_handle (handle);
3049 g_assert (thr_ret == 0);
3050 pthread_cleanup_pop (0);
3052 _wapi_handle_unref (handle);
3059 * @name: a pointer to a NULL-terminated unicode string, that names
3060 * the directory to be created.
3061 * @security: ignored for now
3063 * Creates directory @name
3065 * Return value: %TRUE on success, %FALSE otherwise.
3067 gboolean CreateDirectory (const gunichar2 *name,
3068 WapiSecurityAttributes *security)
3075 g_message("%s: name is NULL", __func__);
3078 SetLastError (ERROR_INVALID_NAME);
3082 utf8_name = mono_unicode_to_external (name);
3083 if (utf8_name == NULL) {
3085 g_message ("%s: unicode conversion returned NULL", __func__);
3088 SetLastError (ERROR_INVALID_NAME);
3092 result = _wapi_mkdir (utf8_name, 0777);
3099 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3106 * @name: a pointer to a NULL-terminated unicode string, that names
3107 * the directory to be removed.
3109 * Removes directory @name
3111 * Return value: %TRUE on success, %FALSE otherwise.
3113 gboolean RemoveDirectory (const gunichar2 *name)
3120 g_message("%s: name is NULL", __func__);
3123 SetLastError (ERROR_INVALID_NAME);
3127 utf8_name = mono_unicode_to_external (name);
3128 if (utf8_name == NULL) {
3130 g_message ("%s: unicode conversion returned NULL", __func__);
3133 SetLastError (ERROR_INVALID_NAME);
3137 result = _wapi_rmdir (utf8_name);
3139 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3150 * GetFileAttributes:
3151 * @name: a pointer to a NULL-terminated unicode filename.
3153 * Gets the attributes for @name;
3155 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3157 guint32 GetFileAttributes (const gunichar2 *name)
3160 struct stat buf, linkbuf;
3166 g_message("%s: name is NULL", __func__);
3169 SetLastError (ERROR_INVALID_NAME);
3173 utf8_name = mono_unicode_to_external (name);
3174 if (utf8_name == NULL) {
3176 g_message ("%s: unicode conversion returned NULL", __func__);
3179 SetLastError (ERROR_INVALID_PARAMETER);
3180 return (INVALID_FILE_ATTRIBUTES);
3183 result = _wapi_stat (utf8_name, &buf);
3184 if (result == -1 && errno == ENOENT) {
3185 /* Might be a dangling symlink... */
3186 result = _wapi_lstat (utf8_name, &buf);
3190 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3192 return (INVALID_FILE_ATTRIBUTES);
3195 result = _wapi_lstat (utf8_name, &linkbuf);
3197 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3199 return (INVALID_FILE_ATTRIBUTES);
3202 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3210 * GetFileAttributesEx:
3211 * @name: a pointer to a NULL-terminated unicode filename.
3212 * @level: must be GetFileExInfoStandard
3213 * @info: pointer to a WapiFileAttributesData structure
3215 * Gets attributes, size and filetimes for @name;
3217 * Return value: %TRUE on success, %FALSE on failure
3219 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3222 WapiFileAttributesData *data;
3224 struct stat buf, linkbuf;
3228 if (level != GetFileExInfoStandard) {
3230 g_message ("%s: info level %d not supported.", __func__,
3234 SetLastError (ERROR_INVALID_PARAMETER);
3240 g_message("%s: name is NULL", __func__);
3243 SetLastError (ERROR_INVALID_NAME);
3247 utf8_name = mono_unicode_to_external (name);
3248 if (utf8_name == NULL) {
3250 g_message ("%s: unicode conversion returned NULL", __func__);
3253 SetLastError (ERROR_INVALID_PARAMETER);
3257 result = _wapi_stat (utf8_name, &buf);
3258 if (result == -1 && errno == ENOENT) {
3259 /* Might be a dangling symlink... */
3260 result = _wapi_lstat (utf8_name, &buf);
3264 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3269 result = _wapi_lstat (utf8_name, &linkbuf);
3271 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3276 /* fill data block */
3278 data = (WapiFileAttributesData *)info;
3280 if (buf.st_mtime < buf.st_ctime)
3281 create_time = buf.st_mtime;
3283 create_time = buf.st_ctime;
3285 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3291 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3292 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3293 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3295 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3296 data->nFileSizeHigh = 0;
3297 data->nFileSizeLow = 0;
3300 data->nFileSizeHigh = buf.st_size >> 32;
3301 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3309 * @name: name of file
3310 * @attrs: attributes to set
3312 * Changes the attributes on a named file.
3314 * Return value: %TRUE on success, %FALSE on failure.
3316 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3318 /* FIXME: think of something clever to do on unix */
3324 * Currently we only handle one *internal* case, with a value that is
3325 * not standard: 0x80000000, which means `set executable bit'
3330 g_message("%s: name is NULL", __func__);
3333 SetLastError (ERROR_INVALID_NAME);
3337 utf8_name = mono_unicode_to_external (name);
3338 if (utf8_name == NULL) {
3340 g_message ("%s: unicode conversion returned NULL", __func__);
3343 SetLastError (ERROR_INVALID_NAME);
3347 result = _wapi_stat (utf8_name, &buf);
3349 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3354 /* Contrary to the documentation, ms allows NORMAL to be
3355 * specified along with other attributes, so dont bother to
3356 * catch that case here.
3358 if (attrs & FILE_ATTRIBUTE_READONLY) {
3359 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3361 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3364 /* Ignore the other attributes for now */
3366 if (attrs & 0x80000000){
3367 mode_t exec_mask = 0;
3369 if ((buf.st_mode & S_IRUSR) != 0)
3370 exec_mask |= S_IXUSR;
3372 if ((buf.st_mode & S_IRGRP) != 0)
3373 exec_mask |= S_IXGRP;
3375 if ((buf.st_mode & S_IROTH) != 0)
3376 exec_mask |= S_IXOTH;
3378 result = chmod (utf8_name, buf.st_mode | exec_mask);
3380 /* Don't bother to reset executable (might need to change this
3390 * GetCurrentDirectory
3391 * @length: size of the buffer
3392 * @buffer: pointer to buffer that recieves path
3394 * Retrieves the current directory for the current process.
3396 * Return value: number of characters in buffer on success, zero on failure
3398 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3400 gunichar2 *utf16_path;
3404 if (getcwd ((char*)buffer, length) == NULL) {
3405 if (errno == ERANGE) { /*buffer length is not big enough */
3406 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*/
3409 utf16_path = mono_unicode_from_external (path, &bytes);
3410 g_free (utf16_path);
3414 _wapi_set_last_error_from_errno ();
3418 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3419 count = (bytes/2)+1;
3420 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3422 /* Add the terminator */
3423 memset (buffer, '\0', bytes+2);
3424 memcpy (buffer, utf16_path, bytes);
3426 g_free (utf16_path);
3432 * SetCurrentDirectory
3433 * @path: path to new directory
3435 * Changes the directory path for the current process.
3437 * Return value: %TRUE on success, %FALSE on failure.
3439 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3445 SetLastError (ERROR_INVALID_PARAMETER);
3449 utf8_path = mono_unicode_to_external (path);
3450 if (_wapi_chdir (utf8_path) != 0) {
3451 _wapi_set_last_error_from_errno ();
3461 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3462 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3464 struct _WapiHandle_file pipe_read_handle = {0};
3465 struct _WapiHandle_file pipe_write_handle = {0};
3466 gpointer read_handle;
3467 gpointer write_handle;
3471 mono_once (&io_ops_once, io_ops_init);
3474 g_message ("%s: Creating pipe", __func__);
3480 g_message ("%s: Error creating pipe: %s", __func__,
3484 _wapi_set_last_error_from_errno ();
3488 if (filedes[0] >= _wapi_fd_reserve ||
3489 filedes[1] >= _wapi_fd_reserve) {
3491 g_message ("%s: File descriptor is too big", __func__);
3494 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3502 /* filedes[0] is open for reading, filedes[1] for writing */
3504 pipe_read_handle.fileaccess = GENERIC_READ;
3505 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3507 if (read_handle == _WAPI_HANDLE_INVALID) {
3508 g_warning ("%s: error creating pipe read handle", __func__);
3511 SetLastError (ERROR_GEN_FAILURE);
3516 pipe_write_handle.fileaccess = GENERIC_WRITE;
3517 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3518 &pipe_write_handle);
3519 if (write_handle == _WAPI_HANDLE_INVALID) {
3520 g_warning ("%s: error creating pipe write handle", __func__);
3521 _wapi_handle_unref (read_handle);
3525 SetLastError (ERROR_GEN_FAILURE);
3530 *readpipe = read_handle;
3531 *writepipe = write_handle;
3534 g_message ("%s: Returning pipe: read handle %p, write handle %p",
3535 __func__, read_handle, write_handle);
3541 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3543 gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3544 gunichar2 *tmpdir16=NULL;
3549 if(tmpdir[strlen (tmpdir)]!='/') {
3551 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3554 tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3555 if(tmpdir16==NULL) {
3563 g_message ("%s: Size %d smaller than needed (%ld)",
3564 __func__, len, dirlen+1);
3569 /* Add the terminator */
3570 memset (buf, '\0', bytes+2);
3571 memcpy (buf, tmpdir16, bytes);
3577 if(tmpdir16!=NULL) {
3585 #ifdef HAVE_GETFSSTAT
3586 /* Darwin has getfsstat */
3587 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3589 struct statfs *stats;
3592 glong length, total = 0;
3594 n = getfsstat (NULL, 0, MNT_NOWAIT);
3597 size = n * sizeof (struct statfs);
3598 stats = (struct statfs *) g_malloc (size);
3601 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3605 for (i = 0; i < n; i++){
3606 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3607 if (total + length < len){
3608 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3609 buf [total+length] = 0;
3612 total += length + 1;
3621 /* In-place octal sequence replacement */
3623 unescape_octal (gchar *str)
3632 while (*rptr != '\0') {
3633 if (*rptr == '\\') {
3636 c = (*(rptr++) - '0') << 6;
3637 c += (*(rptr++) - '0') << 3;
3638 c += *(rptr++) - '0';
3640 } else if (wptr != rptr) {
3648 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3651 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3652 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3653 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3658 guint32 buffer_index;
3659 guint32 mountpoint_index;
3660 guint32 field_number;
3661 guint32 allocated_size;
3662 guint32 fsname_index;
3663 guint32 fstype_index;
3664 gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3665 gchar *mountpoint_allocated;
3666 gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3667 gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3668 gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3671 gboolean check_mount_source;
3672 } LinuxMountInfoParseState;
3674 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3675 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3676 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3677 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3679 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3683 LinuxMountInfoParseState state;
3684 gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3686 memset (buf, 0, len * sizeof (gunichar2));
3687 fd = open ("/proc/self/mountinfo", O_RDONLY);
3689 parser = GetLogicalDriveStrings_MountInfo;
3691 fd = open ("/proc/mounts", O_RDONLY);
3693 parser = GetLogicalDriveStrings_Mounts;
3697 ret = GetLogicalDriveStrings_Mtab (len, buf);
3701 memset (&state, 0, sizeof (LinuxMountInfoParseState));
3702 state.field_number = 1;
3703 state.delimiter = ' ';
3705 while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3706 state.buffer_index = 0;
3708 while ((*parser)(len, buf, &state)) {
3709 if (state.buffer [state.buffer_index] == '\n') {
3710 gboolean quit = add_drive_string (len, buf, &state);
3711 state.field_number = 1;
3712 state.buffer_index++;
3713 if (state.mountpoint_allocated) {
3714 g_free (state.mountpoint_allocated);
3715 state.mountpoint_allocated = NULL;
3732 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3736 if (state->field_number == 1)
3737 state->check_mount_source = TRUE;
3739 while (state->buffer_index < (guint32)state->nbytes) {
3740 if (state->buffer [state->buffer_index] == state->delimiter) {
3741 state->field_number++;
3742 switch (state->field_number) {
3744 state->mountpoint_index = 0;
3748 if (state->mountpoint_allocated)
3749 state->mountpoint_allocated [state->mountpoint_index] = 0;
3751 state->mountpoint [state->mountpoint_index] = 0;
3755 ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3757 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3759 state->buffer_index = state->nbytes;
3762 state->buffer_index++;
3764 } else if (state->buffer [state->buffer_index] == '\n')
3767 switch (state->field_number) {
3769 if (state->check_mount_source) {
3770 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3771 /* We can ignore the rest, it's a device
3773 state->check_mount_source = FALSE;
3774 state->fsname [state->fsname_index++] = '/';
3777 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3778 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3783 append_to_mountpoint (state);
3787 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3788 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3792 state->buffer_index++;
3798 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3800 while (state->buffer_index < (guint32)state->nbytes) {
3801 if (state->buffer [state->buffer_index] == state->delimiter) {
3802 state->field_number++;
3803 switch (state->field_number) {
3805 state->mountpoint_index = 0;
3809 if (state->mountpoint_allocated)
3810 state->mountpoint_allocated [state->mountpoint_index] = 0;
3812 state->mountpoint [state->mountpoint_index] = 0;
3816 state->delimiter = '-';
3820 state->delimiter = ' ';
3824 state->check_mount_source = TRUE;
3827 state->buffer_index++;
3829 } else if (state->buffer [state->buffer_index] == '\n')
3832 switch (state->field_number) {
3834 append_to_mountpoint (state);
3838 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3839 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3843 if (state->check_mount_source) {
3844 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3845 /* We can ignore the rest, it's a device
3847 state->check_mount_source = FALSE;
3848 state->fsname [state->fsname_index++] = '/';
3851 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3852 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3857 state->buffer_index++;
3864 append_to_mountpoint (LinuxMountInfoParseState *state)
3866 gchar ch = state->buffer [state->buffer_index];
3867 if (state->mountpoint_allocated) {
3868 if (state->mountpoint_index >= state->allocated_size) {
3869 guint32 newsize = (state->allocated_size << 1) + 1;
3870 gchar *newbuf = g_malloc0 (newsize * sizeof (gchar));
3872 memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3873 g_free (state->mountpoint_allocated);
3874 state->mountpoint_allocated = newbuf;
3875 state->allocated_size = newsize;
3877 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3879 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3880 state->allocated_size = (state->mountpoint_index << 1) + 1;
3881 state->mountpoint_allocated = g_malloc0 (state->allocated_size * sizeof (gchar));
3882 memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3883 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3885 state->mountpoint [state->mountpoint_index++] = ch;
3890 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3892 gboolean quit = FALSE;
3893 gboolean ignore_entry;
3895 if (state->fsname_index == 1 && state->fsname [0] == '/')
3896 ignore_entry = FALSE;
3897 else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0)
3898 ignore_entry = TRUE;
3899 else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3900 /* Ignore GNOME's gvfs */
3901 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3902 ignore_entry = TRUE;
3904 ignore_entry = FALSE;
3906 ignore_entry = TRUE;
3908 if (!ignore_entry) {
3911 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3913 unescape_octal (mountpoint);
3914 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3915 if (state->total + length + 1 > len) {
3917 state->total = len * 2;
3920 memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3921 state->total += length;
3925 state->fsname_index = 0;
3926 state->fstype_index = 0;
3932 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3934 return GetLogicalDriveStrings_Mtab (len, buf);
3938 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3941 gunichar2 *ptr, *dir;
3942 glong length, total = 0;
3946 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3951 /* Sigh, mntent and friends don't work well.
3952 * It stops on the first line that doesn't begin with a '/'.
3953 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3954 fp = fopen ("/etc/mtab", "rt");
3956 fp = fopen ("/etc/mnttab", "rt");
3962 while (fgets (buffer, 512, fp) != NULL) {
3966 splitted = g_strsplit (buffer, " ", 0);
3967 if (!*splitted || !*(splitted + 1)) {
3968 g_strfreev (splitted);
3972 unescape_octal (*(splitted + 1));
3973 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3974 g_strfreev (splitted);
3975 if (total + length + 1 > len) {
3978 return len * 2; /* guess */
3981 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3983 total += length + 1;
3988 /* Commented out, does not work with my mtab!!! - Gonz */
3989 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3993 gunichar2 *ptr, *dir;
3994 glong len, total = 0;
3997 fp = setmntent ("/etc/mtab", "rt");
3999 fp = setmntent ("/etc/mnttab", "rt");
4005 while ((mnt = getmntent (fp)) != NULL) {
4006 g_print ("GOT %s\n", mnt->mnt_dir);
4007 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
4008 if (total + len + 1 > len) {
4009 return len * 2; /* guess */
4012 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
4024 #if (defined(HAVE_STATVFS) || defined(HAVE_STATFS)) && !defined(PLATFORM_ANDROID)
4025 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4026 WapiULargeInteger *total_number_of_bytes,
4027 WapiULargeInteger *total_number_of_free_bytes)
4030 struct statvfs fsstat;
4031 #elif defined(HAVE_STATFS)
4032 struct statfs fsstat;
4034 gboolean isreadonly;
4035 gchar *utf8_path_name;
4037 unsigned long block_size;
4039 if (path_name == NULL) {
4040 utf8_path_name = g_strdup (g_get_current_dir());
4041 if (utf8_path_name == NULL) {
4042 SetLastError (ERROR_DIRECTORY);
4047 utf8_path_name = mono_unicode_to_external (path_name);
4048 if (utf8_path_name == NULL) {
4050 g_message("%s: unicode conversion returned NULL", __func__);
4053 SetLastError (ERROR_INVALID_NAME);
4060 ret = statvfs (utf8_path_name, &fsstat);
4061 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
4062 block_size = fsstat.f_frsize;
4063 #elif defined(HAVE_STATFS)
4064 ret = statfs (utf8_path_name, &fsstat);
4065 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
4066 block_size = fsstat.f_bsize;
4068 } while(ret == -1 && errno == EINTR);
4070 g_free(utf8_path_name);
4073 _wapi_set_last_error_from_errno ();
4075 g_message ("%s: statvfs failed: %s", __func__, strerror (errno));
4080 /* total number of free bytes for non-root */
4081 if (free_bytes_avail != NULL) {
4083 free_bytes_avail->QuadPart = 0;
4086 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
4090 /* total number of bytes available for non-root */
4091 if (total_number_of_bytes != NULL) {
4092 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
4095 /* total number of bytes available for root */
4096 if (total_number_of_free_bytes != NULL) {
4098 total_number_of_free_bytes->QuadPart = 0;
4101 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
4108 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4109 WapiULargeInteger *total_number_of_bytes,
4110 WapiULargeInteger *total_number_of_free_bytes)
4112 if (free_bytes_avail != NULL) {
4113 free_bytes_avail->QuadPart = (guint64) -1;
4116 if (total_number_of_bytes != NULL) {
4117 total_number_of_bytes->QuadPart = (guint64) -1;
4120 if (total_number_of_free_bytes != NULL) {
4121 total_number_of_free_bytes->QuadPart = (guint64) -1;
4129 * General Unix support
4134 const long fstypeid;
4136 const gchar* fstype;
4139 static _wapi_drive_type _wapi_drive_types[] = {
4141 { DRIVE_REMOTE, "afp" },
4142 { DRIVE_REMOTE, "autofs" },
4143 { DRIVE_CDROM, "cddafs" },
4144 { DRIVE_CDROM, "cd9660" },
4145 { DRIVE_RAMDISK, "devfs" },
4146 { DRIVE_FIXED, "exfat" },
4147 { DRIVE_RAMDISK, "fdesc" },
4148 { DRIVE_REMOTE, "ftp" },
4149 { DRIVE_FIXED, "hfs" },
4150 { DRIVE_FIXED, "msdos" },
4151 { DRIVE_REMOTE, "nfs" },
4152 { DRIVE_FIXED, "ntfs" },
4153 { DRIVE_REMOTE, "smbfs" },
4154 { DRIVE_FIXED, "udf" },
4155 { DRIVE_REMOTE, "webdav" },
4156 { DRIVE_UNKNOWN, NULL }
4158 { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
4159 { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
4160 { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
4161 { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
4162 { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
4163 { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
4164 { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
4165 { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
4166 { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
4167 { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
4168 { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
4169 { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
4170 { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
4171 { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
4172 { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
4173 { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
4174 { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
4175 { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4176 { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4177 { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4178 { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4179 { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4180 { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4181 { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4182 { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4183 { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4184 { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4185 { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4186 { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4187 { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4188 { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4189 { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4190 { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4191 { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4192 { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4193 { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4194 { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4195 { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4196 { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4197 { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4198 { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4199 { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4200 { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4201 { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4202 { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4203 { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4204 { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4205 { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4206 { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4207 { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4208 { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4209 { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4210 { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4211 { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4212 { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4213 { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4214 { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4215 { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4216 { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4217 { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4218 { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4219 { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4220 { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4221 { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4222 { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4223 { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4224 { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4225 { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4226 { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4227 { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4228 { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4229 { DRIVE_UNKNOWN, 0, NULL}
4231 { DRIVE_RAMDISK, "ramfs" },
4232 { DRIVE_RAMDISK, "tmpfs" },
4233 { DRIVE_RAMDISK, "proc" },
4234 { DRIVE_RAMDISK, "sysfs" },
4235 { DRIVE_RAMDISK, "debugfs" },
4236 { DRIVE_RAMDISK, "devpts" },
4237 { DRIVE_RAMDISK, "securityfs" },
4238 { DRIVE_CDROM, "iso9660" },
4239 { DRIVE_FIXED, "ext2" },
4240 { DRIVE_FIXED, "ext3" },
4241 { DRIVE_FIXED, "ext4" },
4242 { DRIVE_FIXED, "sysv" },
4243 { DRIVE_FIXED, "reiserfs" },
4244 { DRIVE_FIXED, "ufs" },
4245 { DRIVE_FIXED, "vfat" },
4246 { DRIVE_FIXED, "msdos" },
4247 { DRIVE_FIXED, "udf" },
4248 { DRIVE_FIXED, "hfs" },
4249 { DRIVE_FIXED, "hpfs" },
4250 { DRIVE_FIXED, "qnx4" },
4251 { DRIVE_FIXED, "ntfs" },
4252 { DRIVE_FIXED, "ntfs-3g" },
4253 { DRIVE_REMOTE, "smbfs" },
4254 { DRIVE_REMOTE, "fuse" },
4255 { DRIVE_REMOTE, "nfs" },
4256 { DRIVE_REMOTE, "nfs4" },
4257 { DRIVE_REMOTE, "cifs" },
4258 { DRIVE_REMOTE, "ncpfs" },
4259 { DRIVE_REMOTE, "coda" },
4260 { DRIVE_REMOTE, "afs" },
4261 { DRIVE_UNKNOWN, NULL }
4266 static guint32 _wapi_get_drive_type(long f_type)
4268 _wapi_drive_type *current;
4270 current = &_wapi_drive_types[0];
4271 while (current->drive_type != DRIVE_UNKNOWN) {
4272 if (current->fstypeid == f_type)
4273 return current->drive_type;
4277 return DRIVE_UNKNOWN;
4280 static guint32 _wapi_get_drive_type(const gchar* fstype)
4282 _wapi_drive_type *current;
4284 current = &_wapi_drive_types[0];
4285 while (current->drive_type != DRIVE_UNKNOWN) {
4286 if (strcmp (current->fstype, fstype) == 0)
4292 return current->drive_type;
4296 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4298 GetDriveTypeFromPath (const char *utf8_root_path_name)
4302 if (statfs (utf8_root_path_name, &buf) == -1)
4303 return DRIVE_UNKNOWN;
4305 return _wapi_get_drive_type (buf.f_fstypename);
4307 return _wapi_get_drive_type (buf.f_type);
4312 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4319 fp = fopen ("/etc/mtab", "rt");
4321 fp = fopen ("/etc/mnttab", "rt");
4323 return(DRIVE_UNKNOWN);
4326 drive_type = DRIVE_NO_ROOT_DIR;
4327 while (fgets (buffer, 512, fp) != NULL) {
4328 splitted = g_strsplit (buffer, " ", 0);
4329 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4330 g_strfreev (splitted);
4334 /* compare given root_path_name with the one from mtab,
4335 if length of utf8_root_path_name is zero it must be the root dir */
4336 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4337 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4338 drive_type = _wapi_get_drive_type (*(splitted + 2));
4339 g_strfreev (splitted);
4343 g_strfreev (splitted);
4351 guint32 GetDriveType(const gunichar2 *root_path_name)
4353 gchar *utf8_root_path_name;
4356 if (root_path_name == NULL) {
4357 utf8_root_path_name = g_strdup (g_get_current_dir());
4358 if (utf8_root_path_name == NULL) {
4359 return(DRIVE_NO_ROOT_DIR);
4363 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4364 if (utf8_root_path_name == NULL) {
4366 g_message("%s: unicode conversion returned NULL", __func__);
4368 return(DRIVE_NO_ROOT_DIR);
4371 /* strip trailing slash for compare below */
4372 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4373 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4376 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4377 g_free (utf8_root_path_name);
4379 return (drive_type);
4383 get_fstypename (gchar *utfpath)
4385 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4388 _wapi_drive_type *current;
4390 if (statfs (utfpath, &stat) == -1)
4393 return stat.f_fstypename;
4395 current = &_wapi_drive_types[0];
4396 while (current->drive_type != DRIVE_UNKNOWN) {
4397 if (stat.f_type == current->fstypeid)
4398 return current->fstype;
4408 /* Linux has struct statfs which has a different layout */
4409 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__)
4411 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4414 const gchar *fstypename;
4415 gboolean status = FALSE;
4418 // We only support getting the file system type
4419 if (fsbuffer == NULL)
4422 utfpath = mono_unicode_to_external (path);
4423 if ((fstypename = get_fstypename (utfpath)) != NULL){
4424 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4425 if (ret != NULL && len < fsbuffersize){
4426 memcpy (fsbuffer, ret, len * sizeof (gunichar2));