2 * io.c: File, console and find handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002 Ximian, Inc.
8 * Copyright (c) 2002-2006 Novell, Inc.
18 #ifdef HAVE_SYS_STATVFS_H
19 #include <sys/statvfs.h>
20 #elif defined(HAVE_SYS_STATFS_H)
21 #include <sys/statfs.h>
22 #elif defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H)
23 #include <sys/param.h>
24 #include <sys/mount.h>
26 #include <sys/types.h>
32 #include <sys/ioctl.h>
36 #include <mono/io-layer/wapi.h>
37 #include <mono/io-layer/wapi-private.h>
38 #include <mono/io-layer/handles-private.h>
39 #include <mono/io-layer/io-private.h>
40 #include <mono/io-layer/timefuncs-private.h>
41 #include <mono/io-layer/thread-private.h>
42 #include <mono/io-layer/io-portability.h>
43 #include <mono/utils/strenc.h>
47 static void file_close (gpointer handle, gpointer data);
48 static WapiFileType file_getfiletype(void);
49 static gboolean file_read(gpointer handle, gpointer buffer,
50 guint32 numbytes, guint32 *bytesread,
51 WapiOverlapped *overlapped);
52 static gboolean file_write(gpointer handle, gconstpointer buffer,
53 guint32 numbytes, guint32 *byteswritten,
54 WapiOverlapped *overlapped);
55 static gboolean file_flush(gpointer handle);
56 static guint32 file_seek(gpointer handle, gint32 movedistance,
57 gint32 *highmovedistance, WapiSeekMethod method);
58 static gboolean file_setendoffile(gpointer handle);
59 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
60 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
61 WapiFileTime *last_access,
62 WapiFileTime *last_write);
63 static gboolean file_setfiletime(gpointer handle,
64 const WapiFileTime *create_time,
65 const WapiFileTime *last_access,
66 const WapiFileTime *last_write);
68 /* File handle is only signalled for overlapped IO */
69 struct _WapiHandleOps _wapi_file_ops = {
70 file_close, /* close */
74 NULL, /* special_wait */
78 void _wapi_file_details (gpointer handle_info)
80 struct _WapiHandle_file *file = (struct _WapiHandle_file *)handle_info;
82 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
84 file->fileaccess&GENERIC_READ?'R':'.',
85 file->fileaccess&GENERIC_WRITE?'W':'.',
86 file->fileaccess&GENERIC_EXECUTE?'X':'.',
87 file->sharemode&FILE_SHARE_READ?'R':'.',
88 file->sharemode&FILE_SHARE_WRITE?'W':'.',
89 file->sharemode&FILE_SHARE_DELETE?'D':'.',
93 static void console_close (gpointer handle, gpointer data);
94 static WapiFileType console_getfiletype(void);
95 static gboolean console_read(gpointer handle, gpointer buffer,
96 guint32 numbytes, guint32 *bytesread,
97 WapiOverlapped *overlapped);
98 static gboolean console_write(gpointer handle, gconstpointer buffer,
99 guint32 numbytes, guint32 *byteswritten,
100 WapiOverlapped *overlapped);
102 /* Console is mostly the same as file, except it can block waiting for
105 struct _WapiHandleOps _wapi_console_ops = {
106 console_close, /* close */
110 NULL, /* special_wait */
114 void _wapi_console_details (gpointer handle_info)
116 _wapi_file_details (handle_info);
119 /* Find handle has no ops.
121 struct _WapiHandleOps _wapi_find_ops = {
126 NULL, /* special_wait */
130 static void pipe_close (gpointer handle, gpointer data);
131 static WapiFileType pipe_getfiletype (void);
132 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
133 guint32 *bytesread, WapiOverlapped *overlapped);
134 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
135 guint32 numbytes, guint32 *byteswritten,
136 WapiOverlapped *overlapped);
140 struct _WapiHandleOps _wapi_pipe_ops = {
141 pipe_close, /* close */
145 NULL, /* special_wait */
149 void _wapi_pipe_details (gpointer handle_info)
151 _wapi_file_details (handle_info);
154 static const struct {
155 /* File, console and pipe handles */
156 WapiFileType (*getfiletype)(void);
158 /* File, console and pipe handles */
159 gboolean (*readfile)(gpointer handle, gpointer buffer,
160 guint32 numbytes, guint32 *bytesread,
161 WapiOverlapped *overlapped);
162 gboolean (*writefile)(gpointer handle, gconstpointer buffer,
163 guint32 numbytes, guint32 *byteswritten,
164 WapiOverlapped *overlapped);
165 gboolean (*flushfile)(gpointer handle);
168 guint32 (*seek)(gpointer handle, gint32 movedistance,
169 gint32 *highmovedistance, WapiSeekMethod method);
170 gboolean (*setendoffile)(gpointer handle);
171 guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
172 gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
173 WapiFileTime *last_access,
174 WapiFileTime *last_write);
175 gboolean (*setfiletime)(gpointer handle,
176 const WapiFileTime *create_time,
177 const WapiFileTime *last_access,
178 const WapiFileTime *last_write);
179 } io_ops[WAPI_HANDLE_COUNT]={
180 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
183 file_read, file_write,
184 file_flush, file_seek,
190 {console_getfiletype,
193 NULL, NULL, NULL, NULL, NULL, NULL},
195 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
197 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
199 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
201 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
202 /* socket (will need at least read and write) */
203 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
205 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
207 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
212 NULL, NULL, NULL, NULL, NULL, NULL},
215 static mono_once_t io_ops_once=MONO_ONCE_INIT;
216 static gboolean lock_while_writing = FALSE;
218 static void io_ops_init (void)
220 /* _wapi_handle_register_capabilities (WAPI_HANDLE_FILE, */
221 /* WAPI_HANDLE_CAP_WAIT); */
222 /* _wapi_handle_register_capabilities (WAPI_HANDLE_CONSOLE, */
223 /* WAPI_HANDLE_CAP_WAIT); */
225 if (g_getenv ("MONO_STRICT_IO_EMULATION") != NULL) {
226 lock_while_writing = TRUE;
230 /* Some utility functions.
233 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
240 /* FIXME: this could definitely be better, but there seems to
241 * be no pattern to the attributes that are set
244 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
245 if (S_ISSOCK (buf->st_mode))
246 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
248 filename = _wapi_basename (pathname);
250 if (S_ISDIR (buf->st_mode)) {
251 attrs = FILE_ATTRIBUTE_DIRECTORY;
252 if (!(buf->st_mode & S_IWUSR)) {
253 attrs |= FILE_ATTRIBUTE_READONLY;
255 if (filename[0] == '.') {
256 attrs |= FILE_ATTRIBUTE_HIDDEN;
259 if (!(buf->st_mode & S_IWUSR)) {
260 attrs = FILE_ATTRIBUTE_READONLY;
262 if (filename[0] == '.') {
263 attrs |= FILE_ATTRIBUTE_HIDDEN;
265 } else if (filename[0] == '.') {
266 attrs = FILE_ATTRIBUTE_HIDDEN;
268 attrs = FILE_ATTRIBUTE_NORMAL;
273 if (S_ISLNK (lbuf->st_mode)) {
274 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
284 _wapi_set_last_error_from_errno (void)
286 SetLastError (_wapi_get_win32_file_error (errno));
289 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
292 if (errno == ENOENT) {
293 /* Check the path - if it's a missing directory then
294 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
300 dirname = _wapi_dirname (path);
302 dirname = g_strdup (dir);
305 if (_wapi_access (dirname, F_OK) == 0) {
306 SetLastError (ERROR_FILE_NOT_FOUND);
308 SetLastError (ERROR_PATH_NOT_FOUND);
313 _wapi_set_last_error_from_errno ();
319 static void file_close (gpointer handle, gpointer data)
321 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
324 g_message("%s: closing file handle %p [%s]", __func__, handle,
325 file_handle->filename);
328 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
329 _wapi_unlink (file_handle->filename);
331 g_free (file_handle->filename);
333 if (file_handle->share_info)
334 _wapi_handle_share_release (file_handle->share_info);
336 close (GPOINTER_TO_UINT(handle));
339 static WapiFileType file_getfiletype(void)
341 return(FILE_TYPE_DISK);
344 static gboolean file_read(gpointer handle, gpointer buffer,
345 guint32 numbytes, guint32 *bytesread,
346 WapiOverlapped *overlapped)
348 struct _WapiHandle_file *file_handle;
350 int fd = GPOINTER_TO_UINT(handle);
353 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
354 (gpointer *)&file_handle);
356 g_warning ("%s: error looking up file handle %p", __func__,
358 SetLastError (ERROR_INVALID_HANDLE);
362 if(bytesread!=NULL) {
366 if(!(file_handle->fileaccess & GENERIC_READ) &&
367 !(file_handle->fileaccess & GENERIC_ALL)) {
369 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
370 __func__, handle, file_handle->fileaccess);
373 SetLastError (ERROR_ACCESS_DENIED);
378 ret = read (fd, buffer, numbytes);
379 } while (ret == -1 && errno == EINTR &&
380 !_wapi_thread_cur_apc_pending());
386 g_message("%s: read of handle %p error: %s", __func__,
387 handle, strerror(err));
389 SetLastError (_wapi_get_win32_file_error (err));
393 if (bytesread != NULL) {
400 static gboolean file_write(gpointer handle, gconstpointer buffer,
401 guint32 numbytes, guint32 *byteswritten,
402 WapiOverlapped *overlapped G_GNUC_UNUSED)
404 struct _WapiHandle_file *file_handle;
407 off_t current_pos = 0;
408 int fd = GPOINTER_TO_UINT(handle);
410 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
411 (gpointer *)&file_handle);
413 g_warning ("%s: error looking up file handle %p", __func__,
415 SetLastError (ERROR_INVALID_HANDLE);
419 if(byteswritten!=NULL) {
423 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
424 !(file_handle->fileaccess & GENERIC_ALL)) {
426 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
429 SetLastError (ERROR_ACCESS_DENIED);
433 if (lock_while_writing) {
434 /* Need to lock the region we're about to write to,
435 * because we only do advisory locking on POSIX
438 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
439 if (current_pos == -1) {
441 g_message ("%s: handle %p lseek failed: %s", __func__,
442 handle, strerror (errno));
444 _wapi_set_last_error_from_errno ();
448 if (_wapi_lock_file_region (fd, current_pos,
449 numbytes) == FALSE) {
450 /* The error has already been set */
456 ret = write (fd, buffer, numbytes);
457 } while (ret == -1 && errno == EINTR &&
458 !_wapi_thread_cur_apc_pending());
460 if (lock_while_writing) {
461 _wapi_unlock_file_region (fd, current_pos, numbytes);
465 if (errno == EINTR) {
468 _wapi_set_last_error_from_errno ();
471 g_message("%s: write of handle %p error: %s",
472 __func__, handle, strerror(errno));
478 if (byteswritten != NULL) {
484 static gboolean file_flush(gpointer handle)
486 struct _WapiHandle_file *file_handle;
489 int fd = GPOINTER_TO_UINT(handle);
491 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
492 (gpointer *)&file_handle);
494 g_warning ("%s: error looking up file handle %p", __func__,
496 SetLastError (ERROR_INVALID_HANDLE);
500 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
501 !(file_handle->fileaccess & GENERIC_ALL)) {
503 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
506 SetLastError (ERROR_ACCESS_DENIED);
513 g_message("%s: fsync of handle %p error: %s", __func__, handle,
517 _wapi_set_last_error_from_errno ();
524 static guint32 file_seek(gpointer handle, gint32 movedistance,
525 gint32 *highmovedistance, WapiSeekMethod method)
527 struct _WapiHandle_file *file_handle;
529 off_t offset, newpos;
532 int fd = GPOINTER_TO_UINT(handle);
534 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
535 (gpointer *)&file_handle);
537 g_warning ("%s: error looking up file handle %p", __func__,
539 SetLastError (ERROR_INVALID_HANDLE);
540 return(INVALID_SET_FILE_POINTER);
543 if(!(file_handle->fileaccess & GENERIC_READ) &&
544 !(file_handle->fileaccess & GENERIC_WRITE) &&
545 !(file_handle->fileaccess & GENERIC_ALL)) {
547 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
550 SetLastError (ERROR_ACCESS_DENIED);
551 return(INVALID_SET_FILE_POINTER);
566 g_message("%s: invalid seek type %d", __func__, method);
569 SetLastError (ERROR_INVALID_PARAMETER);
570 return(INVALID_SET_FILE_POINTER);
573 #ifdef HAVE_LARGE_FILE_SUPPORT
574 if(highmovedistance==NULL) {
577 g_message("%s: setting offset to %lld (low %d)", __func__,
578 offset, movedistance);
581 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
584 g_message("%s: setting offset to %lld 0x%llx (high %d 0x%x, low %d 0x%x)", __func__, offset, offset, *highmovedistance, *highmovedistance, movedistance, movedistance);
592 #ifdef HAVE_LARGE_FILE_SUPPORT
593 g_message("%s: moving handle %p by %lld bytes from %d", __func__,
594 handle, offset, whence);
596 g_message("%s: moving handle %p fd %d by %ld bytes from %d", __func__,
597 handle, offset, whence);
601 newpos=lseek(fd, offset, whence);
604 g_message("%s: lseek on handle %p returned error %s",
605 __func__, handle, strerror(errno));
608 _wapi_set_last_error_from_errno ();
609 return(INVALID_SET_FILE_POINTER);
613 #ifdef HAVE_LARGE_FILE_SUPPORT
614 g_message("%s: lseek returns %lld", __func__, newpos);
616 g_message ("%s: lseek returns %ld", __func__, newpos);
620 #ifdef HAVE_LARGE_FILE_SUPPORT
621 ret=newpos & 0xFFFFFFFF;
622 if(highmovedistance!=NULL) {
623 *highmovedistance=newpos>>32;
627 if(highmovedistance!=NULL) {
628 /* Accurate, but potentially dodgy :-) */
634 g_message ("%s: move of handle %p returning %d/%d", __func__,
635 handle, ret, highmovedistance==NULL?0:*highmovedistance);
641 static gboolean file_setendoffile(gpointer handle)
643 struct _WapiHandle_file *file_handle;
648 int fd = GPOINTER_TO_UINT(handle);
650 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
651 (gpointer *)&file_handle);
653 g_warning ("%s: error looking up file handle %p", __func__,
655 SetLastError (ERROR_INVALID_HANDLE);
659 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
660 !(file_handle->fileaccess & GENERIC_ALL)) {
662 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
665 SetLastError (ERROR_ACCESS_DENIED);
669 /* Find the current file position, and the file length. If
670 * the file position is greater than the length, write to
671 * extend the file with a hole. If the file position is less
672 * than the length, truncate the file.
675 ret=fstat(fd, &statbuf);
678 g_message ("%s: handle %p fstat failed: %s", __func__,
679 handle, strerror(errno));
682 _wapi_set_last_error_from_errno ();
685 size=statbuf.st_size;
687 pos=lseek(fd, (off_t)0, SEEK_CUR);
690 g_message("%s: handle %p lseek failed: %s", __func__,
691 handle, strerror(errno));
694 _wapi_set_last_error_from_errno ();
698 #ifdef FTRUNCATE_DOESNT_EXTEND
699 /* I haven't bothered to write the configure.in stuff for this
700 * because I don't know if any platform needs it. I'm leaving
701 * this code just in case though
704 /* Extend the file. Use write() here, because some
705 * manuals say that ftruncate() behaviour is undefined
706 * when the file needs extending. The POSIX spec says
707 * that on XSI-conformant systems it extends, so if
708 * every system we care about conforms, then we can
712 ret = write (fd, "", 1);
713 } while (ret == -1 && errno == EINTR &&
714 !_wapi_thread_cur_apc_pending());
718 g_message("%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
721 _wapi_set_last_error_from_errno ();
725 /* And put the file position back after the write */
726 ret = lseek (fd, pos, SEEK_SET);
729 g_message ("%s: handle %p second lseek failed: %s",
730 __func__, handle, strerror(errno));
733 _wapi_set_last_error_from_errno ();
739 /* always truncate, because the extend write() adds an extra
740 * byte to the end of the file
743 ret=ftruncate(fd, pos);
745 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
748 g_message("%s: handle %p ftruncate failed: %s", __func__,
749 handle, strerror(errno));
752 _wapi_set_last_error_from_errno ();
759 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
761 struct _WapiHandle_file *file_handle;
766 int fd = GPOINTER_TO_UINT(handle);
768 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
769 (gpointer *)&file_handle);
771 g_warning ("%s: error looking up file handle %p", __func__,
773 SetLastError (ERROR_INVALID_HANDLE);
774 return(INVALID_FILE_SIZE);
777 if(!(file_handle->fileaccess & GENERIC_READ) &&
778 !(file_handle->fileaccess & GENERIC_WRITE) &&
779 !(file_handle->fileaccess & GENERIC_ALL)) {
781 g_message("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
784 SetLastError (ERROR_ACCESS_DENIED);
785 return(INVALID_FILE_SIZE);
788 /* If the file has a size with the low bits 0xFFFFFFFF the
789 * caller can't tell if this is an error, so clear the error
792 SetLastError (ERROR_SUCCESS);
794 ret = fstat(fd, &statbuf);
797 g_message ("%s: handle %p fstat failed: %s", __func__,
798 handle, strerror(errno));
801 _wapi_set_last_error_from_errno ();
802 return(INVALID_FILE_SIZE);
805 /* fstat indicates block devices as zero-length, so go a different path */
807 if (S_ISBLK(statbuf.st_mode)) {
809 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
811 g_message ("%s: handle %p ioctl BLKGETSIZE64 failed: %s",
812 __func__, handle, strerror(errno));
815 _wapi_set_last_error_from_errno ();
816 return(INVALID_FILE_SIZE);
819 size = bigsize & 0xFFFFFFFF;
820 if (highsize != NULL) {
821 *highsize = bigsize>>32;
825 g_message ("%s: Returning block device size %d/%d",
826 __func__, size, *highsize);
833 #ifdef HAVE_LARGE_FILE_SUPPORT
834 size = statbuf.st_size & 0xFFFFFFFF;
835 if (highsize != NULL) {
836 *highsize = statbuf.st_size>>32;
839 if (highsize != NULL) {
840 /* Accurate, but potentially dodgy :-) */
843 size = statbuf.st_size;
847 g_message ("%s: Returning size %d/%d", __func__, size, *highsize);
853 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
854 WapiFileTime *last_access,
855 WapiFileTime *last_write)
857 struct _WapiHandle_file *file_handle;
860 guint64 create_ticks, access_ticks, write_ticks;
862 int fd = GPOINTER_TO_UINT(handle);
864 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
865 (gpointer *)&file_handle);
867 g_warning ("%s: error looking up file handle %p", __func__,
869 SetLastError (ERROR_INVALID_HANDLE);
873 if(!(file_handle->fileaccess & GENERIC_READ) &&
874 !(file_handle->fileaccess & GENERIC_ALL)) {
876 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
877 __func__, handle, file_handle->fileaccess);
880 SetLastError (ERROR_ACCESS_DENIED);
884 ret=fstat(fd, &statbuf);
887 g_message("%s: handle %p fstat failed: %s", __func__, handle,
891 _wapi_set_last_error_from_errno ();
896 g_message("%s: atime: %ld ctime: %ld mtime: %ld", __func__,
897 statbuf.st_atime, statbuf.st_ctime,
901 /* Try and guess a meaningful create time by using the older
904 /* The magic constant comes from msdn documentation
905 * "Converting a time_t Value to a File Time"
907 if(statbuf.st_atime < statbuf.st_ctime) {
908 create_ticks=((guint64)statbuf.st_atime*10000000)
909 + 116444736000000000ULL;
911 create_ticks=((guint64)statbuf.st_ctime*10000000)
912 + 116444736000000000ULL;
915 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
916 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
919 g_message("%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
920 access_ticks, create_ticks, write_ticks);
923 if(create_time!=NULL) {
924 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
925 create_time->dwHighDateTime = create_ticks >> 32;
928 if(last_access!=NULL) {
929 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
930 last_access->dwHighDateTime = access_ticks >> 32;
933 if(last_write!=NULL) {
934 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
935 last_write->dwHighDateTime = write_ticks >> 32;
941 static gboolean file_setfiletime(gpointer handle,
942 const WapiFileTime *create_time G_GNUC_UNUSED,
943 const WapiFileTime *last_access,
944 const WapiFileTime *last_write)
946 struct _WapiHandle_file *file_handle;
948 struct utimbuf utbuf;
950 guint64 access_ticks, write_ticks;
952 int fd = GPOINTER_TO_UINT(handle);
954 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
955 (gpointer *)&file_handle);
957 g_warning ("%s: error looking up file handle %p", __func__,
959 SetLastError (ERROR_INVALID_HANDLE);
963 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
964 !(file_handle->fileaccess & GENERIC_ALL)) {
966 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
969 SetLastError (ERROR_ACCESS_DENIED);
973 if(file_handle->filename == NULL) {
975 g_message("%s: handle %p unknown filename", __func__, handle);
978 SetLastError (ERROR_INVALID_HANDLE);
982 /* Get the current times, so we can put the same times back in
983 * the event that one of the FileTime structs is NULL
985 ret=fstat (fd, &statbuf);
988 g_message("%s: handle %p fstat failed: %s", __func__, handle,
992 SetLastError (ERROR_INVALID_PARAMETER);
996 if(last_access!=NULL) {
997 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
998 last_access->dwLowDateTime;
999 /* This is (time_t)0. We can actually go to INT_MIN,
1000 * but this will do for now.
1002 if (access_ticks < 116444736000000000ULL) {
1004 g_message ("%s: attempt to set access time too early",
1007 SetLastError (ERROR_INVALID_PARAMETER);
1011 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
1013 utbuf.actime=statbuf.st_atime;
1016 if(last_write!=NULL) {
1017 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
1018 last_write->dwLowDateTime;
1019 /* This is (time_t)0. We can actually go to INT_MIN,
1020 * but this will do for now.
1022 if (write_ticks < 116444736000000000ULL) {
1024 g_message ("%s: attempt to set write time too early",
1027 SetLastError (ERROR_INVALID_PARAMETER);
1031 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1033 utbuf.modtime=statbuf.st_mtime;
1037 g_message ("%s: setting handle %p access %ld write %ld", __func__,
1038 handle, utbuf.actime, utbuf.modtime);
1041 ret = _wapi_utime (file_handle->filename, &utbuf);
1044 g_message ("%s: handle %p [%s] utime failed: %s", __func__,
1045 handle, file_handle->filename, strerror(errno));
1048 SetLastError (ERROR_INVALID_PARAMETER);
1055 static void console_close (gpointer handle, gpointer data)
1057 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1060 g_message("%s: closing console handle %p", __func__, handle);
1063 g_free (console_handle->filename);
1065 close (GPOINTER_TO_UINT(handle));
1068 static WapiFileType console_getfiletype(void)
1070 return(FILE_TYPE_CHAR);
1073 static gboolean console_read(gpointer handle, gpointer buffer,
1074 guint32 numbytes, guint32 *bytesread,
1075 WapiOverlapped *overlapped G_GNUC_UNUSED)
1077 struct _WapiHandle_file *console_handle;
1080 int fd = GPOINTER_TO_UINT(handle);
1082 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1083 (gpointer *)&console_handle);
1085 g_warning ("%s: error looking up console handle %p", __func__,
1087 SetLastError (ERROR_INVALID_HANDLE);
1091 if(bytesread!=NULL) {
1095 if(!(console_handle->fileaccess & GENERIC_READ) &&
1096 !(console_handle->fileaccess & GENERIC_ALL)) {
1098 g_message ("%s: handle %p doesn't have GENERIC_READ access: %u",
1099 __func__, handle, console_handle->fileaccess);
1102 SetLastError (ERROR_ACCESS_DENIED);
1107 ret=read(fd, buffer, numbytes);
1108 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1112 g_message("%s: read of handle %p error: %s", __func__, handle,
1116 _wapi_set_last_error_from_errno ();
1120 if(bytesread!=NULL) {
1127 static gboolean console_write(gpointer handle, gconstpointer buffer,
1128 guint32 numbytes, guint32 *byteswritten,
1129 WapiOverlapped *overlapped G_GNUC_UNUSED)
1131 struct _WapiHandle_file *console_handle;
1134 int fd = GPOINTER_TO_UINT(handle);
1136 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1137 (gpointer *)&console_handle);
1139 g_warning ("%s: error looking up console handle %p", __func__,
1141 SetLastError (ERROR_INVALID_HANDLE);
1145 if(byteswritten!=NULL) {
1149 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1150 !(console_handle->fileaccess & GENERIC_ALL)) {
1152 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, console_handle->fileaccess);
1155 SetLastError (ERROR_ACCESS_DENIED);
1160 ret = write(fd, buffer, numbytes);
1161 } while (ret == -1 && errno == EINTR &&
1162 !_wapi_thread_cur_apc_pending());
1165 if (errno == EINTR) {
1168 _wapi_set_last_error_from_errno ();
1171 g_message ("%s: write of handle %p error: %s",
1172 __func__, handle, strerror(errno));
1178 if(byteswritten!=NULL) {
1185 static void pipe_close (gpointer handle, gpointer data G_GNUC_UNUSED)
1188 g_message("%s: closing pipe handle %p", __func__, handle);
1191 /* No filename with pipe handles */
1193 close(GPOINTER_TO_UINT(handle));
1196 static WapiFileType pipe_getfiletype(void)
1198 return(FILE_TYPE_PIPE);
1201 static gboolean pipe_read (gpointer handle, gpointer buffer,
1202 guint32 numbytes, guint32 *bytesread,
1203 WapiOverlapped *overlapped G_GNUC_UNUSED)
1205 struct _WapiHandle_file *pipe_handle;
1208 int fd = GPOINTER_TO_UINT(handle);
1210 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1211 (gpointer *)&pipe_handle);
1213 g_warning ("%s: error looking up pipe handle %p", __func__,
1215 SetLastError (ERROR_INVALID_HANDLE);
1219 if(bytesread!=NULL) {
1223 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1224 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1226 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
1227 __func__, handle, pipe_handle->fileaccess);
1230 SetLastError (ERROR_ACCESS_DENIED);
1235 g_message ("%s: reading up to %d bytes from pipe %p", __func__,
1240 ret=read(fd, buffer, numbytes);
1241 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1244 if (errno == EINTR) {
1247 _wapi_set_last_error_from_errno ();
1250 g_message("%s: read of handle %p error: %s", __func__,
1251 handle, strerror(errno));
1259 g_message ("%s: read %d bytes from pipe", __func__, ret);
1262 if(bytesread!=NULL) {
1269 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1270 guint32 numbytes, guint32 *byteswritten,
1271 WapiOverlapped *overlapped G_GNUC_UNUSED)
1273 struct _WapiHandle_file *pipe_handle;
1276 int fd = GPOINTER_TO_UINT(handle);
1278 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1279 (gpointer *)&pipe_handle);
1281 g_warning ("%s: error looking up pipe handle %p", __func__,
1283 SetLastError (ERROR_INVALID_HANDLE);
1287 if(byteswritten!=NULL) {
1291 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1292 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1294 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, pipe_handle->fileaccess);
1297 SetLastError (ERROR_ACCESS_DENIED);
1302 g_message ("%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1307 ret = write (fd, buffer, numbytes);
1308 } while (ret == -1 && errno == EINTR &&
1309 !_wapi_thread_cur_apc_pending());
1312 if (errno == EINTR) {
1315 _wapi_set_last_error_from_errno ();
1318 g_message("%s: write of handle %p error: %s", __func__,
1319 handle, strerror(errno));
1325 if(byteswritten!=NULL) {
1332 static int convert_flags(guint32 fileaccess, guint32 createmode)
1336 switch(fileaccess) {
1343 case GENERIC_READ|GENERIC_WRITE:
1348 g_message("%s: Unknown access type 0x%x", __func__,
1354 switch(createmode) {
1356 flags|=O_CREAT|O_EXCL;
1359 flags|=O_CREAT|O_TRUNC;
1366 case TRUNCATE_EXISTING:
1371 g_message("%s: Unknown create mode 0x%x", __func__,
1381 static mode_t convert_perms(guint32 sharemode)
1385 if(sharemode&FILE_SHARE_READ) {
1388 if(sharemode&FILE_SHARE_WRITE) {
1396 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1398 struct _WapiFileShare **share_info)
1400 gboolean file_already_shared;
1401 guint32 file_existing_share, file_existing_access;
1403 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);
1405 if (file_already_shared) {
1406 /* The reference to this share info was incremented
1407 * when we looked it up, so be careful to put it back
1408 * if we conclude we can't use this file.
1410 if (file_existing_share == 0) {
1411 /* Quick and easy, no possibility to share */
1413 g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
1416 _wapi_handle_share_release (*share_info);
1421 if (((file_existing_share == FILE_SHARE_READ) &&
1422 (fileaccess != GENERIC_READ)) ||
1423 ((file_existing_share == FILE_SHARE_WRITE) &&
1424 (fileaccess != GENERIC_WRITE))) {
1425 /* New access mode doesn't match up */
1427 g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
1430 _wapi_handle_share_release (*share_info);
1435 if (((file_existing_access & GENERIC_READ) &&
1436 !(sharemode & FILE_SHARE_READ)) ||
1437 ((file_existing_access & GENERIC_WRITE) &&
1438 !(sharemode & FILE_SHARE_WRITE))) {
1439 /* New share mode doesn't match up */
1441 g_message ("%s: Access mode prevents open: requested share: 0x%x, file has access: 0x%x", __func__, sharemode, file_existing_access);
1444 _wapi_handle_share_release (*share_info);
1450 g_message ("%s: New file!", __func__);
1457 static gboolean share_check (struct stat *statbuf, guint32 sharemode,
1459 struct _WapiFileShare **share_info, int fd)
1461 if (share_allows_open (statbuf, sharemode, fileaccess,
1462 share_info) == TRUE) {
1466 /* Got a share violation. Double check that the file is still
1467 * open by someone, in case a process crashed while still
1468 * holding a file handle. This will also cope with someone
1469 * using Mono.Posix to close the file. This is cheaper and
1470 * less intrusive to other processes than initiating a handle
1474 _wapi_handle_check_share (*share_info, fd);
1475 if (share_allows_open (statbuf, sharemode, fileaccess,
1476 share_info) == TRUE) {
1480 /* Still violating. It's possible that a process crashed
1481 * while still holding a file handle, and that a non-mono
1482 * process has the file open. (For example, C-c mcs while
1483 * editing a source file.) As a last resort, run a handle
1484 * collection, which will remove stale share entries.
1486 _wapi_handle_collect ();
1488 return(share_allows_open (statbuf, sharemode, fileaccess, share_info));
1493 * @name: a pointer to a NULL-terminated unicode string, that names
1494 * the file or other object to create.
1495 * @fileaccess: specifies the file access mode
1496 * @sharemode: whether the file should be shared. This parameter is
1497 * currently ignored.
1498 * @security: Ignored for now.
1499 * @createmode: specifies whether to create a new file, whether to
1500 * overwrite an existing file, whether to truncate the file, etc.
1501 * @attrs: specifies file attributes and flags. On win32 attributes
1502 * are characteristics of the file, not the handle, and are ignored
1503 * when an existing file is opened. Flags give the library hints on
1504 * how to process a file to optimise performance.
1505 * @template: the handle of an open %GENERIC_READ file that specifies
1506 * attributes to apply to a newly created file, ignoring @attrs.
1507 * Normally this parameter is NULL. This parameter is ignored when an
1508 * existing file is opened.
1510 * Creates a new file handle. This only applies to normal files:
1511 * pipes are handled by CreatePipe(), and console handles are created
1512 * with GetStdHandle().
1514 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1516 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1517 guint32 sharemode, WapiSecurityAttributes *security,
1518 guint32 createmode, guint32 attrs,
1519 gpointer template G_GNUC_UNUSED)
1521 struct _WapiHandle_file file_handle = {0};
1523 int flags=convert_flags(fileaccess, createmode);
1524 /*mode_t perms=convert_perms(sharemode);*/
1525 /* we don't use sharemode, because that relates to sharing of
1526 * the file when the file is open and is already handled by
1527 * other code, perms instead are the on-disk permissions and
1528 * this is a sane default.
1534 struct stat statbuf;
1536 mono_once (&io_ops_once, io_ops_init);
1538 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1541 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1542 SetLastError (ERROR_ENCRYPTION_FAILED);
1543 return INVALID_HANDLE_VALUE;
1548 g_message ("%s: name is NULL", __func__);
1551 SetLastError (ERROR_INVALID_NAME);
1552 return(INVALID_HANDLE_VALUE);
1555 filename = mono_unicode_to_external (name);
1556 if (filename == NULL) {
1558 g_message("%s: unicode conversion returned NULL", __func__);
1561 SetLastError (ERROR_INVALID_NAME);
1562 return(INVALID_HANDLE_VALUE);
1566 g_message ("%s: Opening %s with share 0x%x and access 0x%x", __func__,
1567 filename, sharemode, fileaccess);
1570 fd = _wapi_open (filename, flags, perms);
1572 /* If we were trying to open a directory with write permissions
1573 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1574 * EISDIR. However, this is a bit bogus because calls to
1575 * manipulate the directory (e.g. SetFileTime) will still work on
1576 * the directory because they use other API calls
1577 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1578 * to open the directory again without write permission.
1580 if (fd == -1 && errno == EISDIR)
1582 /* Try again but don't try to make it writable */
1583 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1588 g_message("%s: Error opening file %s: %s", __func__, filename,
1591 _wapi_set_last_path_error_from_errno (NULL, filename);
1594 return(INVALID_HANDLE_VALUE);
1597 if (fd >= _wapi_fd_reserve) {
1599 g_message ("%s: File descriptor is too big", __func__);
1602 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1607 return(INVALID_HANDLE_VALUE);
1610 ret = fstat (fd, &statbuf);
1613 g_message ("%s: fstat error of file %s: %s", __func__,
1614 filename, strerror (errno));
1616 _wapi_set_last_error_from_errno ();
1620 return(INVALID_HANDLE_VALUE);
1623 if (share_check (&statbuf, sharemode, fileaccess,
1624 &file_handle.share_info, fd) == FALSE) {
1625 SetLastError (ERROR_SHARING_VIOLATION);
1629 return (INVALID_HANDLE_VALUE);
1631 if (file_handle.share_info == NULL) {
1632 /* No space, so no more files can be opened */
1634 g_message ("%s: No space in the share table", __func__);
1637 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1641 return(INVALID_HANDLE_VALUE);
1644 file_handle.filename = filename;
1646 if(security!=NULL) {
1647 //file_handle->security_attributes=_wapi_handle_scratch_store (
1648 //security, sizeof(WapiSecurityAttributes));
1651 file_handle.fileaccess=fileaccess;
1652 file_handle.sharemode=sharemode;
1653 file_handle.attrs=attrs;
1655 #ifdef HAVE_POSIX_FADVISE
1656 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1657 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1658 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1659 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1663 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1665 if (S_ISFIFO (statbuf.st_mode)) {
1666 handle_type = WAPI_HANDLE_PIPE;
1667 } else if (S_ISCHR (statbuf.st_mode)) {
1668 handle_type = WAPI_HANDLE_CONSOLE;
1670 handle_type = WAPI_HANDLE_FILE;
1673 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1674 if (handle == _WAPI_HANDLE_INVALID) {
1675 g_warning ("%s: error creating file handle", __func__);
1679 SetLastError (ERROR_GEN_FAILURE);
1680 return(INVALID_HANDLE_VALUE);
1684 g_message("%s: returning handle %p", __func__, handle);
1692 * @name: a pointer to a NULL-terminated unicode string, that names
1693 * the file to be deleted.
1695 * Deletes file @name.
1697 * Return value: %TRUE on success, %FALSE otherwise.
1699 gboolean DeleteFile(const gunichar2 *name)
1703 gboolean ret = FALSE;
1706 struct stat statbuf;
1707 struct _WapiFileShare *shareinfo;
1712 g_message("%s: name is NULL", __func__);
1715 SetLastError (ERROR_INVALID_NAME);
1719 filename=mono_unicode_to_external(name);
1720 if(filename==NULL) {
1722 g_message("%s: unicode conversion returned NULL", __func__);
1725 SetLastError (ERROR_INVALID_NAME);
1729 attrs = GetFileAttributes (name);
1730 if (attrs == INVALID_FILE_ATTRIBUTES) {
1732 g_message ("%s: file attributes error", __func__);
1734 /* Error set by GetFileAttributes() */
1739 if (attrs & FILE_ATTRIBUTE_READONLY) {
1741 g_message ("%s: file %s is readonly", __func__, filename);
1743 SetLastError (ERROR_ACCESS_DENIED);
1749 /* Check to make sure sharing allows us to open the file for
1750 * writing. See bug 323389.
1752 * Do the checks that don't need an open file descriptor, for
1753 * simplicity's sake. If we really have to do the full checks
1754 * then we can implement that later.
1756 if (_wapi_stat (filename, &statbuf) < 0) {
1757 _wapi_set_last_path_error_from_errno (NULL, filename);
1762 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1763 &shareinfo) == FALSE) {
1764 SetLastError (ERROR_SHARING_VIOLATION);
1769 _wapi_handle_share_release (shareinfo);
1772 retval = _wapi_unlink (filename);
1775 _wapi_set_last_path_error_from_errno (NULL, filename);
1787 * @name: a pointer to a NULL-terminated unicode string, that names
1788 * the file to be moved.
1789 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1790 * new name for the file.
1792 * Renames file @name to @dest_name.
1793 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1794 * when it is the same file as the source. In that case it silently succeeds.
1796 * Return value: %TRUE on success, %FALSE otherwise.
1798 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1800 gchar *utf8_name, *utf8_dest_name;
1801 int result, errno_copy;
1802 struct stat stat_src, stat_dest;
1803 gboolean ret = FALSE;
1804 struct _WapiFileShare *shareinfo;
1808 g_message("%s: name is NULL", __func__);
1811 SetLastError (ERROR_INVALID_NAME);
1815 utf8_name = mono_unicode_to_external (name);
1816 if (utf8_name == NULL) {
1818 g_message ("%s: unicode conversion returned NULL", __func__);
1821 SetLastError (ERROR_INVALID_NAME);
1825 if(dest_name==NULL) {
1827 g_message("%s: name is NULL", __func__);
1831 SetLastError (ERROR_INVALID_NAME);
1835 utf8_dest_name = mono_unicode_to_external (dest_name);
1836 if (utf8_dest_name == NULL) {
1838 g_message ("%s: unicode conversion returned NULL", __func__);
1842 SetLastError (ERROR_INVALID_NAME);
1847 * In C# land we check for the existence of src, but not for dest.
1848 * We check it here and return the failure if dest exists and is not
1849 * the same file as src.
1851 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1852 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1853 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1855 g_free (utf8_dest_name);
1860 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1861 if (stat_dest.st_dev != stat_src.st_dev ||
1862 stat_dest.st_ino != stat_src.st_ino) {
1864 g_free (utf8_dest_name);
1865 SetLastError (ERROR_ALREADY_EXISTS);
1870 /* Check to make sure sharing allows us to open the file for
1871 * writing. See bug 377049.
1873 * Do the checks that don't need an open file descriptor, for
1874 * simplicity's sake. If we really have to do the full checks
1875 * then we can implement that later.
1877 if (share_allows_open (&stat_src, 0, GENERIC_WRITE,
1878 &shareinfo) == FALSE) {
1879 SetLastError (ERROR_SHARING_VIOLATION);
1883 _wapi_handle_share_release (shareinfo);
1885 result = _wapi_rename (utf8_name, utf8_dest_name);
1889 switch(errno_copy) {
1891 SetLastError (ERROR_ALREADY_EXISTS);
1895 /* Ignore here, it is dealt with below */
1899 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1904 g_free (utf8_dest_name);
1906 if (result != 0 && errno_copy == EXDEV) {
1907 if (S_ISDIR (stat_src.st_mode)) {
1908 SetLastError (ERROR_NOT_SAME_DEVICE);
1911 /* Try a copy to the new location, and delete the source */
1912 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1913 /* CopyFile will set the error */
1917 return(DeleteFile (name));
1928 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1932 int buf_size = st_src->st_blksize;
1934 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1935 buf = (char *) malloc (buf_size);
1938 remain = read (src_fd, buf, buf_size);
1940 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1944 _wapi_set_last_error_from_errno ();
1954 while (remain > 0) {
1955 if ((n = write (dest_fd, wbuf, remain)) < 0) {
1956 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1960 _wapi_set_last_error_from_errno ();
1962 g_message ("%s: write failed.", __func__);
1979 * @name: a pointer to a NULL-terminated unicode string, that names
1980 * the file to be copied.
1981 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1982 * new name for the file.
1983 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1985 * Copies file @name to @dest_name
1987 * Return value: %TRUE on success, %FALSE otherwise.
1989 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1990 gboolean fail_if_exists)
1992 gchar *utf8_src, *utf8_dest;
1993 int src_fd, dest_fd;
1994 struct stat st, dest_st;
1995 gboolean ret = TRUE;
1999 g_message("%s: name is NULL", __func__);
2002 SetLastError (ERROR_INVALID_NAME);
2006 utf8_src = mono_unicode_to_external (name);
2007 if (utf8_src == NULL) {
2009 g_message ("%s: unicode conversion of source returned NULL",
2013 SetLastError (ERROR_INVALID_PARAMETER);
2017 if(dest_name==NULL) {
2019 g_message("%s: dest is NULL", __func__);
2023 SetLastError (ERROR_INVALID_NAME);
2027 utf8_dest = mono_unicode_to_external (dest_name);
2028 if (utf8_dest == NULL) {
2030 g_message ("%s: unicode conversion of dest returned NULL",
2034 SetLastError (ERROR_INVALID_PARAMETER);
2041 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2043 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2051 if (fstat (src_fd, &st) < 0) {
2052 _wapi_set_last_error_from_errno ();
2061 /* Before trying to open/create the dest, we need to report a 'file busy'
2062 * error if src and dest are actually the same file. We do the check here to take
2063 * advantage of the IOMAP capability */
2064 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
2065 st.st_ino == dest_st.st_ino) {
2071 SetLastError (ERROR_SHARING_VIOLATION);
2075 if (fail_if_exists) {
2076 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2078 /* FIXME: it kinda sucks that this code path potentially scans
2079 * the directory twice due to the weird SetLastError()
2081 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2083 /* The file does not exist, try creating it */
2084 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2086 /* Apparently this error is set if we
2087 * overwrite the dest file
2089 SetLastError (ERROR_ALREADY_EXISTS);
2093 _wapi_set_last_error_from_errno ();
2102 if (!write_file (src_fd, dest_fd, &st, TRUE))
2114 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2120 g_message ("%s: %s is NULL", __func__, arg_name);
2122 SetLastError (ERROR_INVALID_NAME);
2126 utf8_ret = mono_unicode_to_external (arg);
2127 if (utf8_ret == NULL) {
2129 g_message ("%s: unicode conversion of %s returned NULL",
2130 __func__, arg_name);
2132 SetLastError (ERROR_INVALID_PARAMETER);
2140 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2141 const gunichar2 *backupFileName, guint32 replaceFlags,
2142 gpointer exclude, gpointer reserved)
2144 int result, errno_copy, backup_fd = -1,replaced_fd = -1;
2145 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2146 struct stat stBackup;
2147 gboolean ret = FALSE;
2149 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2151 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2152 goto replace_cleanup;
2153 if (backupFileName != NULL) {
2154 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2155 goto replace_cleanup;
2158 if (utf8_backupFileName) {
2159 // Open the backup file for read so we can restore the file if an error occurs.
2160 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2161 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2164 goto replace_cleanup;
2167 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2170 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2171 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2172 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2173 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2176 if (replaced_fd == -1)
2177 goto replace_cleanup;
2179 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2182 goto replace_cleanup;
2188 g_free (utf8_replacedFileName);
2189 g_free (utf8_replacementFileName);
2190 g_free (utf8_backupFileName);
2191 if (backup_fd != -1)
2193 if (replaced_fd != -1)
2194 close (replaced_fd);
2200 * @stdhandle: specifies the file descriptor
2202 * Returns a handle for stdin, stdout, or stderr. Always returns the
2203 * same handle for the same @stdhandle.
2205 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2208 static mono_mutex_t stdhandle_mutex = MONO_MUTEX_INITIALIZER;
2210 gpointer GetStdHandle(WapiStdHandle stdhandle)
2212 struct _WapiHandle_file *file_handle;
2219 case STD_INPUT_HANDLE:
2224 case STD_OUTPUT_HANDLE:
2229 case STD_ERROR_HANDLE:
2236 g_message("%s: unknown standard handle type", __func__);
2239 SetLastError (ERROR_INVALID_PARAMETER);
2240 return(INVALID_HANDLE_VALUE);
2243 handle = GINT_TO_POINTER (fd);
2245 pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2246 (void *)&stdhandle_mutex);
2247 thr_ret = mono_mutex_lock (&stdhandle_mutex);
2248 g_assert (thr_ret == 0);
2250 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2251 (gpointer *)&file_handle);
2253 /* Need to create this console handle */
2254 handle = _wapi_stdhandle_create (fd, name);
2256 if (handle == INVALID_HANDLE_VALUE) {
2257 SetLastError (ERROR_NO_MORE_FILES);
2261 /* Add a reference to this handle */
2262 _wapi_handle_ref (handle);
2266 thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2267 g_assert (thr_ret == 0);
2268 pthread_cleanup_pop (0);
2275 * @handle: The file handle to read from. The handle must have
2276 * %GENERIC_READ access.
2277 * @buffer: The buffer to store read data in
2278 * @numbytes: The maximum number of bytes to read
2279 * @bytesread: The actual number of bytes read is stored here. This
2280 * value can be zero if the handle is positioned at the end of the
2282 * @overlapped: points to a required %WapiOverlapped structure if
2283 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2286 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2287 * function reads up to @numbytes bytes from the file from the current
2288 * file position, and stores them in @buffer. If there are not enough
2289 * bytes left in the file, just the amount available will be read.
2290 * The actual number of bytes read is stored in @bytesread.
2292 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2293 * file position is ignored and the read position is taken from data
2294 * in the @overlapped structure.
2296 * Return value: %TRUE if the read succeeds (even if no bytes were
2297 * read due to an attempt to read past the end of the file), %FALSE on
2300 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2301 guint32 *bytesread, WapiOverlapped *overlapped)
2303 WapiHandleType type;
2305 type = _wapi_handle_type (handle);
2307 if(io_ops[type].readfile==NULL) {
2308 SetLastError (ERROR_INVALID_HANDLE);
2312 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2318 * @handle: The file handle to write to. The handle must have
2319 * %GENERIC_WRITE access.
2320 * @buffer: The buffer to read data from.
2321 * @numbytes: The maximum number of bytes to write.
2322 * @byteswritten: The actual number of bytes written is stored here.
2323 * If the handle is positioned at the file end, the length of the file
2324 * is extended. This parameter may be %NULL.
2325 * @overlapped: points to a required %WapiOverlapped structure if
2326 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2329 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2330 * function writes up to @numbytes bytes from @buffer to the file at
2331 * the current file position. If @handle is positioned at the end of
2332 * the file, the file is extended. The actual number of bytes written
2333 * is stored in @byteswritten.
2335 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2336 * file position is ignored and the write position is taken from data
2337 * in the @overlapped structure.
2339 * Return value: %TRUE if the write succeeds, %FALSE on error.
2341 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2342 guint32 *byteswritten, WapiOverlapped *overlapped)
2344 WapiHandleType type;
2346 type = _wapi_handle_type (handle);
2348 if(io_ops[type].writefile==NULL) {
2349 SetLastError (ERROR_INVALID_HANDLE);
2353 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2359 * @handle: Handle to open file. The handle must have
2360 * %GENERIC_WRITE access.
2362 * Flushes buffers of the file and causes all unwritten data to
2365 * Return value: %TRUE on success, %FALSE otherwise.
2367 gboolean FlushFileBuffers(gpointer handle)
2369 WapiHandleType type;
2371 type = _wapi_handle_type (handle);
2373 if(io_ops[type].flushfile==NULL) {
2374 SetLastError (ERROR_INVALID_HANDLE);
2378 return(io_ops[type].flushfile (handle));
2383 * @handle: The file handle to set. The handle must have
2384 * %GENERIC_WRITE access.
2386 * Moves the end-of-file position to the current position of the file
2387 * pointer. This function is used to truncate or extend a file.
2389 * Return value: %TRUE on success, %FALSE otherwise.
2391 gboolean SetEndOfFile(gpointer handle)
2393 WapiHandleType type;
2395 type = _wapi_handle_type (handle);
2397 if (io_ops[type].setendoffile == NULL) {
2398 SetLastError (ERROR_INVALID_HANDLE);
2402 return(io_ops[type].setendoffile (handle));
2407 * @handle: The file handle to set. The handle must have
2408 * %GENERIC_READ or %GENERIC_WRITE access.
2409 * @movedistance: Low 32 bits of a signed value that specifies the
2410 * number of bytes to move the file pointer.
2411 * @highmovedistance: Pointer to the high 32 bits of a signed value
2412 * that specifies the number of bytes to move the file pointer, or
2414 * @method: The starting point for the file pointer move.
2416 * Sets the file pointer of an open file.
2418 * The distance to move the file pointer is calculated from
2419 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2420 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2421 * is the low 32 bits and @highmovedistance a pointer to the high 32
2422 * bits of a 64 bit signed value. A positive distance moves the file
2423 * pointer forward from the position specified by @method; a negative
2424 * distance moves the file pointer backward.
2426 * If the library is compiled without large file support,
2427 * @highmovedistance is ignored and its value is set to zero on a
2428 * successful return.
2430 * Return value: On success, the low 32 bits of the new file pointer.
2431 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2432 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2434 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2435 gint32 *highmovedistance, WapiSeekMethod method)
2437 WapiHandleType type;
2439 type = _wapi_handle_type (handle);
2441 if (io_ops[type].seek == NULL) {
2442 SetLastError (ERROR_INVALID_HANDLE);
2443 return(INVALID_SET_FILE_POINTER);
2446 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2452 * @handle: The file handle to test.
2454 * Finds the type of file @handle.
2456 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2457 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2458 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2459 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2461 WapiFileType GetFileType(gpointer handle)
2463 WapiHandleType type;
2465 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2466 SetLastError (ERROR_INVALID_HANDLE);
2467 return(FILE_TYPE_UNKNOWN);
2470 type = _wapi_handle_type (handle);
2472 if (io_ops[type].getfiletype == NULL) {
2473 SetLastError (ERROR_INVALID_HANDLE);
2474 return(FILE_TYPE_UNKNOWN);
2477 return(io_ops[type].getfiletype ());
2482 * @handle: The file handle to query. The handle must have
2483 * %GENERIC_READ or %GENERIC_WRITE access.
2484 * @highsize: If non-%NULL, the high 32 bits of the file size are
2487 * Retrieves the size of the file @handle.
2489 * If the library is compiled without large file support, @highsize
2490 * has its value set to zero on a successful return.
2492 * Return value: On success, the low 32 bits of the file size. If
2493 * @highsize is non-%NULL then the high 32 bits of the file size are
2494 * stored here. On failure %INVALID_FILE_SIZE is returned.
2496 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2498 WapiHandleType type;
2500 type = _wapi_handle_type (handle);
2502 if (io_ops[type].getfilesize == NULL) {
2503 SetLastError (ERROR_INVALID_HANDLE);
2504 return(INVALID_FILE_SIZE);
2507 return(io_ops[type].getfilesize (handle, highsize));
2512 * @handle: The file handle to query. The handle must have
2513 * %GENERIC_READ access.
2514 * @create_time: Points to a %WapiFileTime structure to receive the
2515 * number of ticks since the epoch that file was created. May be
2517 * @last_access: Points to a %WapiFileTime structure to receive the
2518 * number of ticks since the epoch when file was last accessed. May be
2520 * @last_write: Points to a %WapiFileTime structure to receive the
2521 * number of ticks since the epoch when file was last written to. May
2524 * Finds the number of ticks since the epoch that the file referenced
2525 * by @handle was created, last accessed and last modified. A tick is
2526 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2529 * Create time isn't recorded on POSIX file systems or reported by
2530 * stat(2), so that time is guessed by returning the oldest of the
2533 * Return value: %TRUE on success, %FALSE otherwise.
2535 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2536 WapiFileTime *last_access, WapiFileTime *last_write)
2538 WapiHandleType type;
2540 type = _wapi_handle_type (handle);
2542 if (io_ops[type].getfiletime == NULL) {
2543 SetLastError (ERROR_INVALID_HANDLE);
2547 return(io_ops[type].getfiletime (handle, create_time, last_access,
2553 * @handle: The file handle to set. The handle must have
2554 * %GENERIC_WRITE access.
2555 * @create_time: Points to a %WapiFileTime structure that contains the
2556 * number of ticks since the epoch that the file was created. May be
2558 * @last_access: Points to a %WapiFileTime structure that contains the
2559 * number of ticks since the epoch when the file was last accessed.
2561 * @last_write: Points to a %WapiFileTime structure that contains the
2562 * number of ticks since the epoch when the file was last written to.
2565 * Sets the number of ticks since the epoch that the file referenced
2566 * by @handle was created, last accessed or last modified. A tick is
2567 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2570 * Create time isn't recorded on POSIX file systems, and is ignored.
2572 * Return value: %TRUE on success, %FALSE otherwise.
2574 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2575 const WapiFileTime *last_access,
2576 const WapiFileTime *last_write)
2578 WapiHandleType type;
2580 type = _wapi_handle_type (handle);
2582 if (io_ops[type].setfiletime == NULL) {
2583 SetLastError (ERROR_INVALID_HANDLE);
2587 return(io_ops[type].setfiletime (handle, create_time, last_access,
2591 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2592 * January 1 1601 GMT
2595 #define TICKS_PER_MILLISECOND 10000L
2596 #define TICKS_PER_SECOND 10000000L
2597 #define TICKS_PER_MINUTE 600000000L
2598 #define TICKS_PER_HOUR 36000000000LL
2599 #define TICKS_PER_DAY 864000000000LL
2601 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2603 static const guint16 mon_yday[2][13]={
2604 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2605 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2609 * FileTimeToSystemTime:
2610 * @file_time: Points to a %WapiFileTime structure that contains the
2611 * number of ticks to convert.
2612 * @system_time: Points to a %WapiSystemTime structure to receive the
2615 * Converts a tick count into broken-out time values.
2617 * Return value: %TRUE on success, %FALSE otherwise.
2619 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2620 WapiSystemTime *system_time)
2622 gint64 file_ticks, totaldays, rem, y;
2625 if(system_time==NULL) {
2627 g_message("%s: system_time NULL", __func__);
2630 SetLastError (ERROR_INVALID_PARAMETER);
2634 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2635 file_time->dwLowDateTime;
2637 /* Really compares if file_ticks>=0x8000000000000000
2638 * (LLONG_MAX+1) but we're working with a signed value for the
2639 * year and day calculation to work later
2643 g_message("%s: file_time too big", __func__);
2646 SetLastError (ERROR_INVALID_PARAMETER);
2650 totaldays=(file_ticks / TICKS_PER_DAY);
2651 rem = file_ticks % TICKS_PER_DAY;
2653 g_message("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2656 system_time->wHour=rem/TICKS_PER_HOUR;
2657 rem %= TICKS_PER_HOUR;
2659 g_message("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2662 system_time->wMinute = rem / TICKS_PER_MINUTE;
2663 rem %= TICKS_PER_MINUTE;
2665 g_message("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2669 system_time->wSecond = rem / TICKS_PER_SECOND;
2670 rem %= TICKS_PER_SECOND;
2672 g_message("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2676 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2678 g_message("%s: Milliseconds: %d", __func__,
2679 system_time->wMilliseconds);
2682 /* January 1, 1601 was a Monday, according to Emacs calendar */
2683 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2685 g_message("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2688 /* This algorithm to find year and month given days from epoch
2693 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2694 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2696 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2697 /* Guess a corrected year, assuming 365 days per year */
2698 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2700 g_message("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2703 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2704 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2707 /* Adjust days and y to match the guessed year. */
2708 totaldays -= ((yg - y) * 365
2709 + LEAPS_THRU_END_OF (yg - 1)
2710 - LEAPS_THRU_END_OF (y - 1));
2712 g_message("%s: totaldays: %lld", __func__, totaldays);
2716 g_message("%s: y: %lld", __func__, y);
2720 system_time->wYear = y;
2722 g_message("%s: Year: %d", __func__, system_time->wYear);
2725 ip = mon_yday[isleap(y)];
2727 for(y=11; totaldays < ip[y]; --y) {
2732 g_message("%s: totaldays: %lld", __func__, totaldays);
2735 system_time->wMonth = y + 1;
2737 g_message("%s: Month: %d", __func__, system_time->wMonth);
2740 system_time->wDay = totaldays + 1;
2742 g_message("%s: Day: %d", __func__, system_time->wDay);
2748 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2750 struct _WapiHandle_find find_handle = {0};
2752 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2755 if (pattern == NULL) {
2757 g_message ("%s: pattern is NULL", __func__);
2760 SetLastError (ERROR_PATH_NOT_FOUND);
2761 return(INVALID_HANDLE_VALUE);
2764 utf8_pattern = mono_unicode_to_external (pattern);
2765 if (utf8_pattern == NULL) {
2767 g_message ("%s: unicode conversion returned NULL", __func__);
2770 SetLastError (ERROR_INVALID_NAME);
2771 return(INVALID_HANDLE_VALUE);
2775 g_message ("%s: looking for [%s]", __func__, utf8_pattern);
2778 /* Figure out which bit of the pattern is the directory */
2779 dir_part = _wapi_dirname (utf8_pattern);
2780 entry_part = _wapi_basename (utf8_pattern);
2783 /* Don't do this check for now, it breaks if directories
2784 * really do have metachars in their names (see bug 58116).
2785 * FIXME: Figure out a better solution to keep some checks...
2787 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2788 SetLastError (ERROR_INVALID_NAME);
2790 g_free (entry_part);
2791 g_free (utf8_pattern);
2792 return(INVALID_HANDLE_VALUE);
2796 /* The pattern can specify a directory or a set of files.
2798 * The pattern can have wildcard characters ? and *, but only
2799 * in the section after the last directory delimiter. (Return
2800 * ERROR_INVALID_NAME if there are wildcards in earlier path
2801 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2802 * means "match one character", "??" seems to mean "match one
2803 * or two characters", "???" seems to mean "match one, two or
2804 * three characters", etc. Windows will also try and match
2805 * the mangled "short name" of files, so 8 character patterns
2806 * with wildcards will show some surprising results.
2808 * All the written documentation I can find says that '?'
2809 * should only match one character, and doesn't mention '??',
2810 * '???' etc. I'm going to assume that the strict behaviour
2811 * (ie '???' means three and only three characters) is the
2812 * correct one, because that lets me use fnmatch(3) rather
2813 * than mess around with regexes.
2816 find_handle.namelist = NULL;
2817 result = _wapi_io_scandir (dir_part, entry_part,
2818 &find_handle.namelist);
2821 /* No files, which windows seems to call
2824 SetLastError (ERROR_FILE_NOT_FOUND);
2825 g_free (utf8_pattern);
2826 g_free (entry_part);
2828 return (INVALID_HANDLE_VALUE);
2833 gint errnum = errno;
2835 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2837 g_message ("%s: scandir error: %s", __func__,
2838 g_strerror (errnum));
2840 g_free (utf8_pattern);
2841 g_free (entry_part);
2843 return (INVALID_HANDLE_VALUE);
2846 g_free (utf8_pattern);
2847 g_free (entry_part);
2850 g_message ("%s: Got %d matches", __func__, result);
2853 find_handle.dir_part = dir_part;
2854 find_handle.num = result;
2855 find_handle.count = 0;
2857 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2858 if (handle == _WAPI_HANDLE_INVALID) {
2859 g_warning ("%s: error creating find handle", __func__);
2861 g_free (entry_part);
2862 g_free (utf8_pattern);
2863 SetLastError (ERROR_GEN_FAILURE);
2865 return(INVALID_HANDLE_VALUE);
2868 if (handle != INVALID_HANDLE_VALUE &&
2869 !FindNextFile (handle, find_data)) {
2871 SetLastError (ERROR_NO_MORE_FILES);
2872 handle = INVALID_HANDLE_VALUE;
2878 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2880 struct _WapiHandle_find *find_handle;
2882 struct stat buf, linkbuf;
2885 gchar *utf8_filename, *utf8_basename;
2886 gunichar2 *utf16_basename;
2890 gboolean ret = FALSE;
2892 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2893 (gpointer *)&find_handle);
2895 g_warning ("%s: error looking up find handle %p", __func__,
2897 SetLastError (ERROR_INVALID_HANDLE);
2901 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2903 thr_ret = _wapi_handle_lock_handle (handle);
2904 g_assert (thr_ret == 0);
2907 if (find_handle->count >= find_handle->num) {
2908 SetLastError (ERROR_NO_MORE_FILES);
2912 /* stat next match */
2914 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2916 result = _wapi_stat (filename, &buf);
2917 if (result == -1 && errno == ENOENT) {
2918 /* Might be a dangling symlink */
2919 result = _wapi_lstat (filename, &buf);
2924 g_message ("%s: stat failed: %s", __func__, filename);
2931 result = _wapi_lstat (filename, &linkbuf);
2934 g_message ("%s: lstat failed: %s", __func__, filename);
2941 utf8_filename = mono_utf8_from_external (filename);
2942 if (utf8_filename == NULL) {
2943 /* We couldn't turn this filename into utf8 (eg the
2944 * encoding of the name wasn't convertible), so just
2947 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2955 g_message ("%s: Found [%s]", __func__, utf8_filename);
2958 /* fill data block */
2960 if (buf.st_mtime < buf.st_ctime)
2961 create_time = buf.st_mtime;
2963 create_time = buf.st_ctime;
2965 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2967 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2968 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2969 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2971 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2972 find_data->nFileSizeHigh = 0;
2973 find_data->nFileSizeLow = 0;
2975 find_data->nFileSizeHigh = buf.st_size >> 32;
2976 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2979 find_data->dwReserved0 = 0;
2980 find_data->dwReserved1 = 0;
2982 utf8_basename = _wapi_basename (utf8_filename);
2983 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2985 if(utf16_basename==NULL) {
2986 g_free (utf8_basename);
2987 g_free (utf8_filename);
2992 /* utf16 is 2 * utf8 */
2995 memset (find_data->cFileName, '\0', (MAX_PATH*2));
2997 /* Truncating a utf16 string like this might leave the last
3000 memcpy (find_data->cFileName, utf16_basename,
3001 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3003 find_data->cAlternateFileName [0] = 0; /* not used */
3005 g_free (utf8_basename);
3006 g_free (utf8_filename);
3007 g_free (utf16_basename);
3010 thr_ret = _wapi_handle_unlock_handle (handle);
3011 g_assert (thr_ret == 0);
3012 pthread_cleanup_pop (0);
3019 * @wapi_handle: the find handle to close.
3021 * Closes find handle @wapi_handle
3023 * Return value: %TRUE on success, %FALSE otherwise.
3025 gboolean FindClose (gpointer handle)
3027 struct _WapiHandle_find *find_handle;
3031 if (handle == NULL) {
3032 SetLastError (ERROR_INVALID_HANDLE);
3036 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
3037 (gpointer *)&find_handle);
3039 g_warning ("%s: error looking up find handle %p", __func__,
3041 SetLastError (ERROR_INVALID_HANDLE);
3045 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
3047 thr_ret = _wapi_handle_lock_handle (handle);
3048 g_assert (thr_ret == 0);
3050 g_strfreev (find_handle->namelist);
3051 g_free (find_handle->dir_part);
3053 thr_ret = _wapi_handle_unlock_handle (handle);
3054 g_assert (thr_ret == 0);
3055 pthread_cleanup_pop (0);
3057 _wapi_handle_unref (handle);
3064 * @name: a pointer to a NULL-terminated unicode string, that names
3065 * the directory to be created.
3066 * @security: ignored for now
3068 * Creates directory @name
3070 * Return value: %TRUE on success, %FALSE otherwise.
3072 gboolean CreateDirectory (const gunichar2 *name,
3073 WapiSecurityAttributes *security)
3080 g_message("%s: name is NULL", __func__);
3083 SetLastError (ERROR_INVALID_NAME);
3087 utf8_name = mono_unicode_to_external (name);
3088 if (utf8_name == NULL) {
3090 g_message ("%s: unicode conversion returned NULL", __func__);
3093 SetLastError (ERROR_INVALID_NAME);
3097 result = _wapi_mkdir (utf8_name, 0777);
3104 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3111 * @name: a pointer to a NULL-terminated unicode string, that names
3112 * the directory to be removed.
3114 * Removes directory @name
3116 * Return value: %TRUE on success, %FALSE otherwise.
3118 gboolean RemoveDirectory (const gunichar2 *name)
3125 g_message("%s: name is NULL", __func__);
3128 SetLastError (ERROR_INVALID_NAME);
3132 utf8_name = mono_unicode_to_external (name);
3133 if (utf8_name == NULL) {
3135 g_message ("%s: unicode conversion returned NULL", __func__);
3138 SetLastError (ERROR_INVALID_NAME);
3142 result = _wapi_rmdir (utf8_name);
3144 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3155 * GetFileAttributes:
3156 * @name: a pointer to a NULL-terminated unicode filename.
3158 * Gets the attributes for @name;
3160 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3162 guint32 GetFileAttributes (const gunichar2 *name)
3165 struct stat buf, linkbuf;
3171 g_message("%s: name is NULL", __func__);
3174 SetLastError (ERROR_INVALID_NAME);
3178 utf8_name = mono_unicode_to_external (name);
3179 if (utf8_name == NULL) {
3181 g_message ("%s: unicode conversion returned NULL", __func__);
3184 SetLastError (ERROR_INVALID_PARAMETER);
3185 return (INVALID_FILE_ATTRIBUTES);
3188 result = _wapi_stat (utf8_name, &buf);
3189 if (result == -1 && errno == ENOENT) {
3190 /* Might be a dangling symlink... */
3191 result = _wapi_lstat (utf8_name, &buf);
3195 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3197 return (INVALID_FILE_ATTRIBUTES);
3200 result = _wapi_lstat (utf8_name, &linkbuf);
3202 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3204 return (INVALID_FILE_ATTRIBUTES);
3207 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3215 * GetFileAttributesEx:
3216 * @name: a pointer to a NULL-terminated unicode filename.
3217 * @level: must be GetFileExInfoStandard
3218 * @info: pointer to a WapiFileAttributesData structure
3220 * Gets attributes, size and filetimes for @name;
3222 * Return value: %TRUE on success, %FALSE on failure
3224 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3227 WapiFileAttributesData *data;
3229 struct stat buf, linkbuf;
3233 if (level != GetFileExInfoStandard) {
3235 g_message ("%s: info level %d not supported.", __func__,
3239 SetLastError (ERROR_INVALID_PARAMETER);
3245 g_message("%s: name is NULL", __func__);
3248 SetLastError (ERROR_INVALID_NAME);
3252 utf8_name = mono_unicode_to_external (name);
3253 if (utf8_name == NULL) {
3255 g_message ("%s: unicode conversion returned NULL", __func__);
3258 SetLastError (ERROR_INVALID_PARAMETER);
3262 result = _wapi_stat (utf8_name, &buf);
3263 if (result == -1 && errno == ENOENT) {
3264 /* Might be a dangling symlink... */
3265 result = _wapi_lstat (utf8_name, &buf);
3269 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3274 result = _wapi_lstat (utf8_name, &linkbuf);
3276 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3281 /* fill data block */
3283 data = (WapiFileAttributesData *)info;
3285 if (buf.st_mtime < buf.st_ctime)
3286 create_time = buf.st_mtime;
3288 create_time = buf.st_ctime;
3290 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3296 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3297 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3298 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3300 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3301 data->nFileSizeHigh = 0;
3302 data->nFileSizeLow = 0;
3305 data->nFileSizeHigh = buf.st_size >> 32;
3306 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3314 * @name: name of file
3315 * @attrs: attributes to set
3317 * Changes the attributes on a named file.
3319 * Return value: %TRUE on success, %FALSE on failure.
3321 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3323 /* FIXME: think of something clever to do on unix */
3329 * Currently we only handle one *internal* case, with a value that is
3330 * not standard: 0x80000000, which means `set executable bit'
3335 g_message("%s: name is NULL", __func__);
3338 SetLastError (ERROR_INVALID_NAME);
3342 utf8_name = mono_unicode_to_external (name);
3343 if (utf8_name == NULL) {
3345 g_message ("%s: unicode conversion returned NULL", __func__);
3348 SetLastError (ERROR_INVALID_NAME);
3352 result = _wapi_stat (utf8_name, &buf);
3354 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3359 /* Contrary to the documentation, ms allows NORMAL to be
3360 * specified along with other attributes, so dont bother to
3361 * catch that case here.
3363 if (attrs & FILE_ATTRIBUTE_READONLY) {
3364 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3366 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3369 /* Ignore the other attributes for now */
3371 if (attrs & 0x80000000){
3372 mode_t exec_mask = 0;
3374 if ((buf.st_mode & S_IRUSR) != 0)
3375 exec_mask |= S_IXUSR;
3377 if ((buf.st_mode & S_IRGRP) != 0)
3378 exec_mask |= S_IXGRP;
3380 if ((buf.st_mode & S_IROTH) != 0)
3381 exec_mask |= S_IXOTH;
3383 result = chmod (utf8_name, buf.st_mode | exec_mask);
3385 /* Don't bother to reset executable (might need to change this
3395 * GetCurrentDirectory
3396 * @length: size of the buffer
3397 * @buffer: pointer to buffer that recieves path
3399 * Retrieves the current directory for the current process.
3401 * Return value: number of characters in buffer on success, zero on failure
3403 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3405 gunichar2 *utf16_path;
3409 if (getcwd ((char*)buffer, length) == NULL) {
3410 if (errno == ERANGE) { /*buffer length is not big enough */
3411 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*/
3414 utf16_path = mono_unicode_from_external (path, &bytes);
3415 g_free (utf16_path);
3419 _wapi_set_last_error_from_errno ();
3423 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3424 count = (bytes/2)+1;
3425 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3427 /* Add the terminator */
3428 memset (buffer, '\0', bytes+2);
3429 memcpy (buffer, utf16_path, bytes);
3431 g_free (utf16_path);
3437 * SetCurrentDirectory
3438 * @path: path to new directory
3440 * Changes the directory path for the current process.
3442 * Return value: %TRUE on success, %FALSE on failure.
3444 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3450 SetLastError (ERROR_INVALID_PARAMETER);
3454 utf8_path = mono_unicode_to_external (path);
3455 if (_wapi_chdir (utf8_path) != 0) {
3456 _wapi_set_last_error_from_errno ();
3466 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3467 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3469 struct _WapiHandle_file pipe_read_handle = {0};
3470 struct _WapiHandle_file pipe_write_handle = {0};
3471 gpointer read_handle;
3472 gpointer write_handle;
3476 mono_once (&io_ops_once, io_ops_init);
3479 g_message ("%s: Creating pipe", __func__);
3485 g_message ("%s: Error creating pipe: %s", __func__,
3489 _wapi_set_last_error_from_errno ();
3493 if (filedes[0] >= _wapi_fd_reserve ||
3494 filedes[1] >= _wapi_fd_reserve) {
3496 g_message ("%s: File descriptor is too big", __func__);
3499 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3507 /* filedes[0] is open for reading, filedes[1] for writing */
3509 pipe_read_handle.fileaccess = GENERIC_READ;
3510 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3512 if (read_handle == _WAPI_HANDLE_INVALID) {
3513 g_warning ("%s: error creating pipe read handle", __func__);
3516 SetLastError (ERROR_GEN_FAILURE);
3521 pipe_write_handle.fileaccess = GENERIC_WRITE;
3522 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3523 &pipe_write_handle);
3524 if (write_handle == _WAPI_HANDLE_INVALID) {
3525 g_warning ("%s: error creating pipe write handle", __func__);
3526 _wapi_handle_unref (read_handle);
3530 SetLastError (ERROR_GEN_FAILURE);
3535 *readpipe = read_handle;
3536 *writepipe = write_handle;
3539 g_message ("%s: Returning pipe: read handle %p, write handle %p",
3540 __func__, read_handle, write_handle);
3546 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3548 gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3549 gunichar2 *tmpdir16=NULL;
3554 if(tmpdir[strlen (tmpdir)]!='/') {
3556 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3559 tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3560 if(tmpdir16==NULL) {
3568 g_message ("%s: Size %d smaller than needed (%ld)",
3569 __func__, len, dirlen+1);
3574 /* Add the terminator */
3575 memset (buf, '\0', bytes+2);
3576 memcpy (buf, tmpdir16, bytes);
3582 if(tmpdir16!=NULL) {
3590 /* In-place octal sequence replacement */
3592 unescape_octal (gchar *str)
3601 while (*rptr != '\0') {
3602 if (*rptr == '\\') {
3605 c = (*(rptr++) - '0') << 6;
3606 c += (*(rptr++) - '0') << 3;
3607 c += *(rptr++) - '0';
3609 } else if (wptr != rptr) {
3619 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3622 gunichar2 *ptr, *dir;
3623 glong length, total = 0;
3627 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3632 /* Sigh, mntent and friends don't work well.
3633 * It stops on the first line that doesn't begin with a '/'.
3634 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3635 fp = fopen ("/etc/mtab", "rt");
3637 fp = fopen ("/etc/mnttab", "rt");
3643 while (fgets (buffer, 512, fp) != NULL) {
3647 splitted = g_strsplit (buffer, " ", 0);
3648 if (!*splitted || !*(splitted + 1)) {
3649 g_strfreev (splitted);
3653 unescape_octal (*(splitted + 1));
3654 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3655 g_strfreev (splitted);
3656 if (total + length + 1 > len) {
3659 return len * 2; /* guess */
3662 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3664 total += length + 1;
3669 /* Commented out, does not work with my mtab!!! - Gonz */
3670 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3674 gunichar2 *ptr, *dir;
3675 glong len, total = 0;
3678 fp = setmntent ("/etc/mtab", "rt");
3680 fp = setmntent ("/etc/mnttab", "rt");
3686 while ((mnt = getmntent (fp)) != NULL) {
3687 g_print ("GOT %s\n", mnt->mnt_dir);
3688 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3689 if (total + len + 1 > len) {
3690 return len * 2; /* guess */
3693 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3704 #if (defined(HAVE_STATVFS) || defined(HAVE_STATFS)) && !defined(PLATFORM_ANDROID)
3705 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3706 WapiULargeInteger *total_number_of_bytes,
3707 WapiULargeInteger *total_number_of_free_bytes)
3710 struct statvfs fsstat;
3711 #elif defined(HAVE_STATFS)
3712 struct statfs fsstat;
3714 gboolean isreadonly;
3715 gchar *utf8_path_name;
3717 unsigned long block_size;
3719 if (path_name == NULL) {
3720 utf8_path_name = g_strdup (g_get_current_dir());
3721 if (utf8_path_name == NULL) {
3722 SetLastError (ERROR_DIRECTORY);
3727 utf8_path_name = mono_unicode_to_external (path_name);
3728 if (utf8_path_name == NULL) {
3730 g_message("%s: unicode conversion returned NULL", __func__);
3733 SetLastError (ERROR_INVALID_NAME);
3740 ret = statvfs (utf8_path_name, &fsstat);
3741 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
3742 block_size = fsstat.f_frsize;
3743 #elif defined(HAVE_STATFS)
3744 ret = statfs (utf8_path_name, &fsstat);
3745 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
3746 block_size = fsstat.f_bsize;
3748 } while(ret == -1 && errno == EINTR);
3750 g_free(utf8_path_name);
3753 _wapi_set_last_error_from_errno ();
3755 g_message ("%s: statvfs failed: %s", __func__, strerror (errno));
3760 /* total number of free bytes for non-root */
3761 if (free_bytes_avail != NULL) {
3763 free_bytes_avail->QuadPart = 0;
3766 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
3770 /* total number of bytes available for non-root */
3771 if (total_number_of_bytes != NULL) {
3772 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
3775 /* total number of bytes available for root */
3776 if (total_number_of_free_bytes != NULL) {
3778 total_number_of_free_bytes->QuadPart = 0;
3781 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
3788 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3789 WapiULargeInteger *total_number_of_bytes,
3790 WapiULargeInteger *total_number_of_free_bytes)
3792 if (free_bytes_avail != NULL) {
3793 free_bytes_avail->QuadPart = (guint64) -1;
3796 if (total_number_of_bytes != NULL) {
3797 total_number_of_bytes->QuadPart = (guint64) -1;
3800 if (total_number_of_free_bytes != NULL) {
3801 total_number_of_free_bytes->QuadPart = (guint64) -1;
3810 const gchar* fstype;
3813 static _wapi_drive_type _wapi_drive_types[] = {
3814 { DRIVE_RAMDISK, "ramfs" },
3815 { DRIVE_RAMDISK, "tmpfs" },
3816 { DRIVE_RAMDISK, "proc" },
3817 { DRIVE_RAMDISK, "sysfs" },
3818 { DRIVE_RAMDISK, "debugfs" },
3819 { DRIVE_RAMDISK, "devpts" },
3820 { DRIVE_RAMDISK, "securityfs" },
3821 { DRIVE_CDROM, "iso9660" },
3822 { DRIVE_FIXED, "ext2" },
3823 { DRIVE_FIXED, "ext3" },
3824 { DRIVE_FIXED, "ext4" },
3825 { DRIVE_FIXED, "sysv" },
3826 { DRIVE_FIXED, "reiserfs" },
3827 { DRIVE_FIXED, "ufs" },
3828 { DRIVE_FIXED, "vfat" },
3829 { DRIVE_FIXED, "msdos" },
3830 { DRIVE_FIXED, "udf" },
3831 { DRIVE_FIXED, "hfs" },
3832 { DRIVE_FIXED, "hpfs" },
3833 { DRIVE_FIXED, "qnx4" },
3834 { DRIVE_FIXED, "ntfs" },
3835 { DRIVE_FIXED, "ntfs-3g" },
3836 { DRIVE_REMOTE, "smbfs" },
3837 { DRIVE_REMOTE, "fuse" },
3838 { DRIVE_REMOTE, "nfs" },
3839 { DRIVE_REMOTE, "nfs4" },
3840 { DRIVE_REMOTE, "cifs" },
3841 { DRIVE_REMOTE, "ncpfs" },
3842 { DRIVE_REMOTE, "coda" },
3843 { DRIVE_REMOTE, "afs" },
3844 { DRIVE_UNKNOWN, NULL }
3847 static guint32 _wapi_get_drive_type(const gchar* fstype)
3849 _wapi_drive_type *current;
3851 current = &_wapi_drive_types[0];
3852 while (current->drive_type != DRIVE_UNKNOWN) {
3853 if (strcmp (current->fstype, fstype) == 0)
3859 return current->drive_type;
3862 guint32 GetDriveType(const gunichar2 *root_path_name)
3867 gchar *utf8_root_path_name;
3870 if (root_path_name == NULL) {
3871 utf8_root_path_name = g_strdup (g_get_current_dir());
3872 if (utf8_root_path_name == NULL) {
3873 return(DRIVE_NO_ROOT_DIR);
3877 utf8_root_path_name = mono_unicode_to_external (root_path_name);
3878 if (utf8_root_path_name == NULL) {
3880 g_message("%s: unicode conversion returned NULL", __func__);
3882 return(DRIVE_NO_ROOT_DIR);
3885 /* strip trailing slash for compare below */
3886 if (g_str_has_suffix(utf8_root_path_name, "/")) {
3887 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
3891 fp = fopen ("/etc/mtab", "rt");
3893 fp = fopen ("/etc/mnttab", "rt");
3895 g_free (utf8_root_path_name);
3896 return(DRIVE_UNKNOWN);
3900 drive_type = DRIVE_NO_ROOT_DIR;
3901 while (fgets (buffer, 512, fp) != NULL) {
3902 splitted = g_strsplit (buffer, " ", 0);
3903 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
3904 g_strfreev (splitted);
3908 /* compare given root_path_name with the one from mtab,
3909 if length of utf8_root_path_name is zero it must be the root dir */
3910 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
3911 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
3912 drive_type = _wapi_get_drive_type (*(splitted + 2));
3913 g_strfreev (splitted);
3917 g_strfreev (splitted);
3921 g_free (utf8_root_path_name);
3923 return (drive_type);