2 * io.c: File, console and find handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002 Ximian, Inc.
8 * Copyright (c) 2002-2006 Novell, Inc.
18 #ifdef HAVE_SYS_STATVFS_H
19 #include <sys/statvfs.h>
20 #elif defined(HAVE_SYS_STATFS_H)
21 #include <sys/statfs.h>
22 #elif defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H)
23 #include <sys/param.h>
24 #include <sys/mount.h>
26 #include <sys/types.h>
32 #include <mono/io-layer/wapi.h>
33 #include <mono/io-layer/wapi-private.h>
34 #include <mono/io-layer/handles-private.h>
35 #include <mono/io-layer/io-private.h>
36 #include <mono/io-layer/timefuncs-private.h>
37 #include <mono/io-layer/thread-private.h>
38 #include <mono/io-layer/io-portability.h>
39 #include <mono/utils/strenc.h>
43 static gboolean _wapi_lock_file_region (int fd, off_t offset, off_t length);
44 static gboolean _wapi_unlock_file_region (int fd, off_t offset, off_t length);
46 static void file_close (gpointer handle, gpointer data);
47 static WapiFileType file_getfiletype(void);
48 static gboolean file_read(gpointer handle, gpointer buffer,
49 guint32 numbytes, guint32 *bytesread,
50 WapiOverlapped *overlapped);
51 static gboolean file_write(gpointer handle, gconstpointer buffer,
52 guint32 numbytes, guint32 *byteswritten,
53 WapiOverlapped *overlapped);
54 static gboolean file_flush(gpointer handle);
55 static guint32 file_seek(gpointer handle, gint32 movedistance,
56 gint32 *highmovedistance, WapiSeekMethod method);
57 static gboolean file_setendoffile(gpointer handle);
58 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
59 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
60 WapiFileTime *last_access,
61 WapiFileTime *last_write);
62 static gboolean file_setfiletime(gpointer handle,
63 const WapiFileTime *create_time,
64 const WapiFileTime *last_access,
65 const WapiFileTime *last_write);
67 /* File handle is only signalled for overlapped IO */
68 struct _WapiHandleOps _wapi_file_ops = {
69 file_close, /* close */
73 NULL, /* special_wait */
77 void _wapi_file_details (gpointer handle_info)
79 struct _WapiHandle_file *file = (struct _WapiHandle_file *)handle_info;
81 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
83 file->fileaccess&GENERIC_READ?'R':'.',
84 file->fileaccess&GENERIC_WRITE?'W':'.',
85 file->fileaccess&GENERIC_EXECUTE?'X':'.',
86 file->sharemode&FILE_SHARE_READ?'R':'.',
87 file->sharemode&FILE_SHARE_WRITE?'W':'.',
88 file->sharemode&FILE_SHARE_DELETE?'D':'.',
92 static void console_close (gpointer handle, gpointer data);
93 static WapiFileType console_getfiletype(void);
94 static gboolean console_read(gpointer handle, gpointer buffer,
95 guint32 numbytes, guint32 *bytesread,
96 WapiOverlapped *overlapped);
97 static gboolean console_write(gpointer handle, gconstpointer buffer,
98 guint32 numbytes, guint32 *byteswritten,
99 WapiOverlapped *overlapped);
101 /* Console is mostly the same as file, except it can block waiting for
104 struct _WapiHandleOps _wapi_console_ops = {
105 console_close, /* close */
109 NULL, /* special_wait */
113 void _wapi_console_details (gpointer handle_info)
115 _wapi_file_details (handle_info);
118 /* Find handle has no ops.
120 struct _WapiHandleOps _wapi_find_ops = {
125 NULL, /* special_wait */
129 static void pipe_close (gpointer handle, gpointer data);
130 static WapiFileType pipe_getfiletype (void);
131 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
132 guint32 *bytesread, WapiOverlapped *overlapped);
133 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
134 guint32 numbytes, guint32 *byteswritten,
135 WapiOverlapped *overlapped);
139 struct _WapiHandleOps _wapi_pipe_ops = {
140 pipe_close, /* close */
144 NULL, /* special_wait */
148 void _wapi_pipe_details (gpointer handle_info)
150 _wapi_file_details (handle_info);
153 static const struct {
154 /* File, console and pipe handles */
155 WapiFileType (*getfiletype)(void);
157 /* File, console and pipe handles */
158 gboolean (*readfile)(gpointer handle, gpointer buffer,
159 guint32 numbytes, guint32 *bytesread,
160 WapiOverlapped *overlapped);
161 gboolean (*writefile)(gpointer handle, gconstpointer buffer,
162 guint32 numbytes, guint32 *byteswritten,
163 WapiOverlapped *overlapped);
164 gboolean (*flushfile)(gpointer handle);
167 guint32 (*seek)(gpointer handle, gint32 movedistance,
168 gint32 *highmovedistance, WapiSeekMethod method);
169 gboolean (*setendoffile)(gpointer handle);
170 guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
171 gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
172 WapiFileTime *last_access,
173 WapiFileTime *last_write);
174 gboolean (*setfiletime)(gpointer handle,
175 const WapiFileTime *create_time,
176 const WapiFileTime *last_access,
177 const WapiFileTime *last_write);
178 } io_ops[WAPI_HANDLE_COUNT]={
179 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
182 file_read, file_write,
183 file_flush, file_seek,
189 {console_getfiletype,
192 NULL, NULL, NULL, NULL, NULL, NULL},
194 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
196 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
198 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
200 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
201 /* socket (will need at least read and write) */
202 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
204 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
206 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
211 NULL, NULL, NULL, NULL, NULL, NULL},
214 static mono_once_t io_ops_once=MONO_ONCE_INIT;
215 static gboolean lock_while_writing = FALSE;
217 static void io_ops_init (void)
219 /* _wapi_handle_register_capabilities (WAPI_HANDLE_FILE, */
220 /* WAPI_HANDLE_CAP_WAIT); */
221 /* _wapi_handle_register_capabilities (WAPI_HANDLE_CONSOLE, */
222 /* WAPI_HANDLE_CAP_WAIT); */
224 if (g_getenv ("MONO_STRICT_IO_EMULATION") != NULL) {
225 lock_while_writing = TRUE;
229 /* Some utility functions.
232 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
239 /* FIXME: this could definitely be better, but there seems to
240 * be no pattern to the attributes that are set
243 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
244 if (S_ISSOCK (buf->st_mode))
245 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
247 filename = _wapi_basename (pathname);
249 if (S_ISDIR (buf->st_mode)) {
250 attrs = FILE_ATTRIBUTE_DIRECTORY;
251 if (!(buf->st_mode & S_IWUSR)) {
252 attrs |= FILE_ATTRIBUTE_READONLY;
254 if (filename[0] == '.') {
255 attrs |= FILE_ATTRIBUTE_HIDDEN;
258 if (!(buf->st_mode & S_IWUSR)) {
259 attrs = FILE_ATTRIBUTE_READONLY;
261 if (filename[0] == '.') {
262 attrs |= FILE_ATTRIBUTE_HIDDEN;
264 } else if (filename[0] == '.') {
265 attrs = FILE_ATTRIBUTE_HIDDEN;
267 attrs = FILE_ATTRIBUTE_NORMAL;
272 if (S_ISLNK (lbuf->st_mode)) {
273 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
283 _wapi_set_last_error_from_errno (void)
285 SetLastError (_wapi_get_win32_file_error (errno));
288 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
291 if (errno == ENOENT) {
292 /* Check the path - if it's a missing directory then
293 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
299 dirname = _wapi_dirname (path);
301 dirname = g_strdup (dir);
304 if (_wapi_access (dirname, F_OK) == 0) {
305 SetLastError (ERROR_FILE_NOT_FOUND);
307 SetLastError (ERROR_PATH_NOT_FOUND);
312 _wapi_set_last_error_from_errno ();
318 static void file_close (gpointer handle, gpointer data)
320 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
323 g_message("%s: closing file handle %p [%s]", __func__, handle,
324 file_handle->filename);
327 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
328 _wapi_unlink (file_handle->filename);
330 g_free (file_handle->filename);
332 _wapi_handle_share_release (file_handle->share_info);
334 close (GPOINTER_TO_UINT(handle));
337 static WapiFileType file_getfiletype(void)
339 return(FILE_TYPE_DISK);
342 static gboolean file_read(gpointer handle, gpointer buffer,
343 guint32 numbytes, guint32 *bytesread,
344 WapiOverlapped *overlapped)
346 struct _WapiHandle_file *file_handle;
348 int fd = GPOINTER_TO_UINT(handle);
351 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
352 (gpointer *)&file_handle);
354 g_warning ("%s: error looking up file handle %p", __func__,
356 SetLastError (ERROR_INVALID_HANDLE);
360 if(bytesread!=NULL) {
364 if(!(file_handle->fileaccess & GENERIC_READ) &&
365 !(file_handle->fileaccess & GENERIC_ALL)) {
367 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
368 __func__, handle, file_handle->fileaccess);
371 SetLastError (ERROR_ACCESS_DENIED);
376 ret = read (fd, buffer, numbytes);
377 } while (ret == -1 && errno == EINTR &&
378 !_wapi_thread_cur_apc_pending());
384 g_message("%s: read of handle %p error: %s", __func__,
385 handle, strerror(err));
387 SetLastError (_wapi_get_win32_file_error (err));
391 if (bytesread != NULL) {
398 static gboolean file_write(gpointer handle, gconstpointer buffer,
399 guint32 numbytes, guint32 *byteswritten,
400 WapiOverlapped *overlapped G_GNUC_UNUSED)
402 struct _WapiHandle_file *file_handle;
405 off_t current_pos = 0;
406 int fd = GPOINTER_TO_UINT(handle);
408 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
409 (gpointer *)&file_handle);
411 g_warning ("%s: error looking up file handle %p", __func__,
413 SetLastError (ERROR_INVALID_HANDLE);
417 if(byteswritten!=NULL) {
421 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
422 !(file_handle->fileaccess & GENERIC_ALL)) {
424 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
427 SetLastError (ERROR_ACCESS_DENIED);
431 if (lock_while_writing) {
432 /* Need to lock the region we're about to write to,
433 * because we only do advisory locking on POSIX
436 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
437 if (current_pos == -1) {
439 g_message ("%s: handle %p lseek failed: %s", __func__,
440 handle, strerror (errno));
442 _wapi_set_last_error_from_errno ();
446 if (_wapi_lock_file_region (fd, current_pos,
447 numbytes) == FALSE) {
448 /* The error has already been set */
454 ret = write (fd, buffer, numbytes);
455 } while (ret == -1 && errno == EINTR &&
456 !_wapi_thread_cur_apc_pending());
458 if (lock_while_writing) {
459 _wapi_unlock_file_region (fd, current_pos, numbytes);
463 if (errno == EINTR) {
466 _wapi_set_last_error_from_errno ();
469 g_message("%s: write of handle %p error: %s",
470 __func__, handle, strerror(errno));
476 if (byteswritten != NULL) {
482 static gboolean file_flush(gpointer handle)
484 struct _WapiHandle_file *file_handle;
487 int fd = GPOINTER_TO_UINT(handle);
489 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
490 (gpointer *)&file_handle);
492 g_warning ("%s: error looking up file handle %p", __func__,
494 SetLastError (ERROR_INVALID_HANDLE);
498 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
499 !(file_handle->fileaccess & GENERIC_ALL)) {
501 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
504 SetLastError (ERROR_ACCESS_DENIED);
511 g_message("%s: fsync of handle %p error: %s", __func__, handle,
515 _wapi_set_last_error_from_errno ();
522 static guint32 file_seek(gpointer handle, gint32 movedistance,
523 gint32 *highmovedistance, WapiSeekMethod method)
525 struct _WapiHandle_file *file_handle;
527 off_t offset, newpos;
530 int fd = GPOINTER_TO_UINT(handle);
532 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
533 (gpointer *)&file_handle);
535 g_warning ("%s: error looking up file handle %p", __func__,
537 SetLastError (ERROR_INVALID_HANDLE);
538 return(INVALID_SET_FILE_POINTER);
541 if(!(file_handle->fileaccess & GENERIC_READ) &&
542 !(file_handle->fileaccess & GENERIC_WRITE) &&
543 !(file_handle->fileaccess & GENERIC_ALL)) {
545 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
548 SetLastError (ERROR_ACCESS_DENIED);
549 return(INVALID_SET_FILE_POINTER);
564 g_message("%s: invalid seek type %d", __func__, method);
567 SetLastError (ERROR_INVALID_PARAMETER);
568 return(INVALID_SET_FILE_POINTER);
571 #ifdef HAVE_LARGE_FILE_SUPPORT
572 if(highmovedistance==NULL) {
575 g_message("%s: setting offset to %lld (low %d)", __func__,
576 offset, movedistance);
579 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
582 g_message("%s: setting offset to %lld 0x%llx (high %d 0x%x, low %d 0x%x)", __func__, offset, offset, *highmovedistance, *highmovedistance, movedistance, movedistance);
590 #ifdef HAVE_LARGE_FILE_SUPPORT
591 g_message("%s: moving handle %p by %lld bytes from %d", __func__,
592 handle, offset, whence);
594 g_message("%s: moving handle %p fd %d by %ld bytes from %d", __func__,
595 handle, offset, whence);
599 newpos=lseek(fd, offset, whence);
602 g_message("%s: lseek on handle %p returned error %s",
603 __func__, handle, strerror(errno));
606 _wapi_set_last_error_from_errno ();
607 return(INVALID_SET_FILE_POINTER);
611 #ifdef HAVE_LARGE_FILE_SUPPORT
612 g_message("%s: lseek returns %lld", __func__, newpos);
614 g_message ("%s: lseek returns %ld", __func__, newpos);
618 #ifdef HAVE_LARGE_FILE_SUPPORT
619 ret=newpos & 0xFFFFFFFF;
620 if(highmovedistance!=NULL) {
621 *highmovedistance=newpos>>32;
625 if(highmovedistance!=NULL) {
626 /* Accurate, but potentially dodgy :-) */
632 g_message ("%s: move of handle %p returning %d/%d", __func__,
633 handle, ret, highmovedistance==NULL?0:*highmovedistance);
639 static gboolean file_setendoffile(gpointer handle)
641 struct _WapiHandle_file *file_handle;
646 int fd = GPOINTER_TO_UINT(handle);
648 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
649 (gpointer *)&file_handle);
651 g_warning ("%s: error looking up file handle %p", __func__,
653 SetLastError (ERROR_INVALID_HANDLE);
657 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
658 !(file_handle->fileaccess & GENERIC_ALL)) {
660 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
663 SetLastError (ERROR_ACCESS_DENIED);
667 /* Find the current file position, and the file length. If
668 * the file position is greater than the length, write to
669 * extend the file with a hole. If the file position is less
670 * than the length, truncate the file.
673 ret=fstat(fd, &statbuf);
676 g_message ("%s: handle %p fstat failed: %s", __func__,
677 handle, strerror(errno));
680 _wapi_set_last_error_from_errno ();
683 size=statbuf.st_size;
685 pos=lseek(fd, (off_t)0, SEEK_CUR);
688 g_message("%s: handle %p lseek failed: %s", __func__,
689 handle, strerror(errno));
692 _wapi_set_last_error_from_errno ();
696 #ifdef FTRUNCATE_DOESNT_EXTEND
697 /* I haven't bothered to write the configure.in stuff for this
698 * because I don't know if any platform needs it. I'm leaving
699 * this code just in case though
702 /* Extend the file. Use write() here, because some
703 * manuals say that ftruncate() behaviour is undefined
704 * when the file needs extending. The POSIX spec says
705 * that on XSI-conformant systems it extends, so if
706 * every system we care about conforms, then we can
710 ret = write (fd, "", 1);
711 } while (ret == -1 && errno == EINTR &&
712 !_wapi_thread_cur_apc_pending());
716 g_message("%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
719 _wapi_set_last_error_from_errno ();
723 /* And put the file position back after the write */
724 ret = lseek (fd, pos, SEEK_SET);
727 g_message ("%s: handle %p second lseek failed: %s",
728 __func__, handle, strerror(errno));
731 _wapi_set_last_error_from_errno ();
737 /* always truncate, because the extend write() adds an extra
738 * byte to the end of the file
741 ret=ftruncate(fd, pos);
743 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
746 g_message("%s: handle %p ftruncate failed: %s", __func__,
747 handle, strerror(errno));
750 _wapi_set_last_error_from_errno ();
757 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
759 struct _WapiHandle_file *file_handle;
764 int fd = GPOINTER_TO_UINT(handle);
766 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
767 (gpointer *)&file_handle);
769 g_warning ("%s: error looking up file handle %p", __func__,
771 SetLastError (ERROR_INVALID_HANDLE);
772 return(INVALID_FILE_SIZE);
775 if(!(file_handle->fileaccess & GENERIC_READ) &&
776 !(file_handle->fileaccess & GENERIC_WRITE) &&
777 !(file_handle->fileaccess & GENERIC_ALL)) {
779 g_message("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
782 SetLastError (ERROR_ACCESS_DENIED);
783 return(INVALID_FILE_SIZE);
786 /* If the file has a size with the low bits 0xFFFFFFFF the
787 * caller can't tell if this is an error, so clear the error
790 SetLastError (ERROR_SUCCESS);
792 ret = fstat(fd, &statbuf);
795 g_message ("%s: handle %p fstat failed: %s", __func__,
796 handle, strerror(errno));
799 _wapi_set_last_error_from_errno ();
800 return(INVALID_FILE_SIZE);
803 #ifdef HAVE_LARGE_FILE_SUPPORT
804 size = statbuf.st_size & 0xFFFFFFFF;
805 if (highsize != NULL) {
806 *highsize = statbuf.st_size>>32;
809 if (highsize != NULL) {
810 /* Accurate, but potentially dodgy :-) */
813 size = statbuf.st_size;
817 g_message ("%s: Returning size %d/%d", __func__, size, *highsize);
823 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
824 WapiFileTime *last_access,
825 WapiFileTime *last_write)
827 struct _WapiHandle_file *file_handle;
830 guint64 create_ticks, access_ticks, write_ticks;
832 int fd = GPOINTER_TO_UINT(handle);
834 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
835 (gpointer *)&file_handle);
837 g_warning ("%s: error looking up file handle %p", __func__,
839 SetLastError (ERROR_INVALID_HANDLE);
843 if(!(file_handle->fileaccess & GENERIC_READ) &&
844 !(file_handle->fileaccess & GENERIC_ALL)) {
846 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
847 __func__, handle, file_handle->fileaccess);
850 SetLastError (ERROR_ACCESS_DENIED);
854 ret=fstat(fd, &statbuf);
857 g_message("%s: handle %p fstat failed: %s", __func__, handle,
861 _wapi_set_last_error_from_errno ();
866 g_message("%s: atime: %ld ctime: %ld mtime: %ld", __func__,
867 statbuf.st_atime, statbuf.st_ctime,
871 /* Try and guess a meaningful create time by using the older
874 /* The magic constant comes from msdn documentation
875 * "Converting a time_t Value to a File Time"
877 if(statbuf.st_atime < statbuf.st_ctime) {
878 create_ticks=((guint64)statbuf.st_atime*10000000)
879 + 116444736000000000ULL;
881 create_ticks=((guint64)statbuf.st_ctime*10000000)
882 + 116444736000000000ULL;
885 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
886 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
889 g_message("%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
890 access_ticks, create_ticks, write_ticks);
893 if(create_time!=NULL) {
894 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
895 create_time->dwHighDateTime = create_ticks >> 32;
898 if(last_access!=NULL) {
899 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
900 last_access->dwHighDateTime = access_ticks >> 32;
903 if(last_write!=NULL) {
904 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
905 last_write->dwHighDateTime = write_ticks >> 32;
911 static gboolean file_setfiletime(gpointer handle,
912 const WapiFileTime *create_time G_GNUC_UNUSED,
913 const WapiFileTime *last_access,
914 const WapiFileTime *last_write)
916 struct _WapiHandle_file *file_handle;
918 struct utimbuf utbuf;
920 guint64 access_ticks, write_ticks;
922 int fd = GPOINTER_TO_UINT(handle);
924 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
925 (gpointer *)&file_handle);
927 g_warning ("%s: error looking up file handle %p", __func__,
929 SetLastError (ERROR_INVALID_HANDLE);
933 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
934 !(file_handle->fileaccess & GENERIC_ALL)) {
936 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
939 SetLastError (ERROR_ACCESS_DENIED);
943 if(file_handle->filename == NULL) {
945 g_message("%s: handle %p unknown filename", __func__, handle);
948 SetLastError (ERROR_INVALID_HANDLE);
952 /* Get the current times, so we can put the same times back in
953 * the event that one of the FileTime structs is NULL
955 ret=fstat (fd, &statbuf);
958 g_message("%s: handle %p fstat failed: %s", __func__, handle,
962 SetLastError (ERROR_INVALID_PARAMETER);
966 if(last_access!=NULL) {
967 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
968 last_access->dwLowDateTime;
969 /* This is (time_t)0. We can actually go to INT_MIN,
970 * but this will do for now.
972 if (access_ticks < 116444736000000000ULL) {
974 g_message ("%s: attempt to set access time too early",
977 SetLastError (ERROR_INVALID_PARAMETER);
981 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
983 utbuf.actime=statbuf.st_atime;
986 if(last_write!=NULL) {
987 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
988 last_write->dwLowDateTime;
989 /* This is (time_t)0. We can actually go to INT_MIN,
990 * but this will do for now.
992 if (write_ticks < 116444736000000000ULL) {
994 g_message ("%s: attempt to set write time too early",
997 SetLastError (ERROR_INVALID_PARAMETER);
1001 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1003 utbuf.modtime=statbuf.st_mtime;
1007 g_message ("%s: setting handle %p access %ld write %ld", __func__,
1008 handle, utbuf.actime, utbuf.modtime);
1011 ret = _wapi_utime (file_handle->filename, &utbuf);
1014 g_message ("%s: handle %p [%s] utime failed: %s", __func__,
1015 handle, file_handle->filename, strerror(errno));
1018 SetLastError (ERROR_INVALID_PARAMETER);
1025 static void console_close (gpointer handle, gpointer data)
1027 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1030 g_message("%s: closing console handle %p", __func__, handle);
1033 g_free (console_handle->filename);
1035 close (GPOINTER_TO_UINT(handle));
1038 static WapiFileType console_getfiletype(void)
1040 return(FILE_TYPE_CHAR);
1043 static gboolean console_read(gpointer handle, gpointer buffer,
1044 guint32 numbytes, guint32 *bytesread,
1045 WapiOverlapped *overlapped G_GNUC_UNUSED)
1047 struct _WapiHandle_file *console_handle;
1050 int fd = GPOINTER_TO_UINT(handle);
1052 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1053 (gpointer *)&console_handle);
1055 g_warning ("%s: error looking up console handle %p", __func__,
1057 SetLastError (ERROR_INVALID_HANDLE);
1061 if(bytesread!=NULL) {
1065 if(!(console_handle->fileaccess & GENERIC_READ) &&
1066 !(console_handle->fileaccess & GENERIC_ALL)) {
1068 g_message ("%s: handle %p doesn't have GENERIC_READ access: %u",
1069 __func__, handle, console_handle->fileaccess);
1072 SetLastError (ERROR_ACCESS_DENIED);
1077 ret=read(fd, buffer, numbytes);
1078 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1082 g_message("%s: read of handle %p error: %s", __func__, handle,
1086 _wapi_set_last_error_from_errno ();
1090 if(bytesread!=NULL) {
1097 static gboolean console_write(gpointer handle, gconstpointer buffer,
1098 guint32 numbytes, guint32 *byteswritten,
1099 WapiOverlapped *overlapped G_GNUC_UNUSED)
1101 struct _WapiHandle_file *console_handle;
1104 int fd = GPOINTER_TO_UINT(handle);
1106 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1107 (gpointer *)&console_handle);
1109 g_warning ("%s: error looking up console handle %p", __func__,
1111 SetLastError (ERROR_INVALID_HANDLE);
1115 if(byteswritten!=NULL) {
1119 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1120 !(console_handle->fileaccess & GENERIC_ALL)) {
1122 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, console_handle->fileaccess);
1125 SetLastError (ERROR_ACCESS_DENIED);
1130 ret = write(fd, buffer, numbytes);
1131 } while (ret == -1 && errno == EINTR &&
1132 !_wapi_thread_cur_apc_pending());
1135 if (errno == EINTR) {
1138 _wapi_set_last_error_from_errno ();
1141 g_message ("%s: write of handle %p error: %s",
1142 __func__, handle, strerror(errno));
1148 if(byteswritten!=NULL) {
1155 static void pipe_close (gpointer handle, gpointer data G_GNUC_UNUSED)
1158 g_message("%s: closing pipe handle %p", __func__, handle);
1161 /* No filename with pipe handles */
1163 close(GPOINTER_TO_UINT(handle));
1166 static WapiFileType pipe_getfiletype(void)
1168 return(FILE_TYPE_PIPE);
1171 static gboolean pipe_read (gpointer handle, gpointer buffer,
1172 guint32 numbytes, guint32 *bytesread,
1173 WapiOverlapped *overlapped G_GNUC_UNUSED)
1175 struct _WapiHandle_file *pipe_handle;
1178 int fd = GPOINTER_TO_UINT(handle);
1180 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1181 (gpointer *)&pipe_handle);
1183 g_warning ("%s: error looking up pipe handle %p", __func__,
1185 SetLastError (ERROR_INVALID_HANDLE);
1189 if(bytesread!=NULL) {
1193 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1194 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1196 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
1197 __func__, handle, pipe_handle->fileaccess);
1200 SetLastError (ERROR_ACCESS_DENIED);
1205 g_message ("%s: reading up to %d bytes from pipe %p", __func__,
1210 ret=read(fd, buffer, numbytes);
1211 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1214 if (errno == EINTR) {
1217 _wapi_set_last_error_from_errno ();
1220 g_message("%s: read of handle %p error: %s", __func__,
1221 handle, strerror(errno));
1229 g_message ("%s: read %d bytes from pipe", __func__, ret);
1232 if(bytesread!=NULL) {
1239 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1240 guint32 numbytes, guint32 *byteswritten,
1241 WapiOverlapped *overlapped G_GNUC_UNUSED)
1243 struct _WapiHandle_file *pipe_handle;
1246 int fd = GPOINTER_TO_UINT(handle);
1248 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1249 (gpointer *)&pipe_handle);
1251 g_warning ("%s: error looking up pipe handle %p", __func__,
1253 SetLastError (ERROR_INVALID_HANDLE);
1257 if(byteswritten!=NULL) {
1261 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1262 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1264 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, pipe_handle->fileaccess);
1267 SetLastError (ERROR_ACCESS_DENIED);
1272 g_message ("%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1277 ret = write (fd, buffer, numbytes);
1278 } while (ret == -1 && errno == EINTR &&
1279 !_wapi_thread_cur_apc_pending());
1282 if (errno == EINTR) {
1285 _wapi_set_last_error_from_errno ();
1288 g_message("%s: write of handle %p error: %s", __func__,
1289 handle, strerror(errno));
1295 if(byteswritten!=NULL) {
1302 static int convert_flags(guint32 fileaccess, guint32 createmode)
1306 switch(fileaccess) {
1313 case GENERIC_READ|GENERIC_WRITE:
1318 g_message("%s: Unknown access type 0x%x", __func__,
1324 switch(createmode) {
1326 flags|=O_CREAT|O_EXCL;
1329 flags|=O_CREAT|O_TRUNC;
1336 case TRUNCATE_EXISTING:
1341 g_message("%s: Unknown create mode 0x%x", __func__,
1350 static guint32 convert_from_flags(int flags)
1352 guint32 fileaccess=0;
1355 #define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR)
1358 if((flags & O_ACCMODE) == O_RDONLY) {
1359 fileaccess=GENERIC_READ;
1360 } else if ((flags & O_ACCMODE) == O_WRONLY) {
1361 fileaccess=GENERIC_WRITE;
1362 } else if ((flags & O_ACCMODE) == O_RDWR) {
1363 fileaccess=GENERIC_READ|GENERIC_WRITE;
1366 g_message("%s: Can't figure out flags 0x%x", __func__, flags);
1370 /* Maybe sort out create mode too */
1376 static mode_t convert_perms(guint32 sharemode)
1380 if(sharemode&FILE_SHARE_READ) {
1383 if(sharemode&FILE_SHARE_WRITE) {
1391 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1393 struct _WapiFileShare **share_info)
1395 gboolean file_already_shared;
1396 guint32 file_existing_share, file_existing_access;
1398 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);
1400 if (file_already_shared) {
1401 /* The reference to this share info was incremented
1402 * when we looked it up, so be careful to put it back
1403 * if we conclude we can't use this file.
1405 if (file_existing_share == 0) {
1406 /* Quick and easy, no possibility to share */
1408 g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
1411 _wapi_handle_share_release (*share_info);
1416 if (((file_existing_share == FILE_SHARE_READ) &&
1417 (fileaccess != GENERIC_READ)) ||
1418 ((file_existing_share == FILE_SHARE_WRITE) &&
1419 (fileaccess != GENERIC_WRITE))) {
1420 /* New access mode doesn't match up */
1422 g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
1425 _wapi_handle_share_release (*share_info);
1430 if (((file_existing_access & GENERIC_READ) &&
1431 !(sharemode & FILE_SHARE_READ)) ||
1432 ((file_existing_access & GENERIC_WRITE) &&
1433 !(sharemode & FILE_SHARE_WRITE))) {
1434 /* New share mode doesn't match up */
1436 g_message ("%s: Access mode prevents open: requested share: 0x%x, file has access: 0x%x", __func__, sharemode, file_existing_access);
1439 _wapi_handle_share_release (*share_info);
1445 g_message ("%s: New file!", __func__);
1452 static gboolean share_check (struct stat *statbuf, guint32 sharemode,
1454 struct _WapiFileShare **share_info, int fd)
1456 if (share_allows_open (statbuf, sharemode, fileaccess,
1457 share_info) == TRUE) {
1461 /* Got a share violation. Double check that the file is still
1462 * open by someone, in case a process crashed while still
1463 * holding a file handle. This will also cope with someone
1464 * using Mono.Posix to close the file. This is cheaper and
1465 * less intrusive to other processes than initiating a handle
1469 _wapi_handle_check_share (*share_info, fd);
1470 if (share_allows_open (statbuf, sharemode, fileaccess,
1471 share_info) == TRUE) {
1475 /* Still violating. It's possible that a process crashed
1476 * while still holding a file handle, and that a non-mono
1477 * process has the file open. (For example, C-c mcs while
1478 * editing a source file.) As a last resort, run a handle
1479 * collection, which will remove stale share entries.
1481 _wapi_handle_collect ();
1483 return(share_allows_open (statbuf, sharemode, fileaccess, share_info));
1488 * @name: a pointer to a NULL-terminated unicode string, that names
1489 * the file or other object to create.
1490 * @fileaccess: specifies the file access mode
1491 * @sharemode: whether the file should be shared. This parameter is
1492 * currently ignored.
1493 * @security: Ignored for now.
1494 * @createmode: specifies whether to create a new file, whether to
1495 * overwrite an existing file, whether to truncate the file, etc.
1496 * @attrs: specifies file attributes and flags. On win32 attributes
1497 * are characteristics of the file, not the handle, and are ignored
1498 * when an existing file is opened. Flags give the library hints on
1499 * how to process a file to optimise performance.
1500 * @template: the handle of an open %GENERIC_READ file that specifies
1501 * attributes to apply to a newly created file, ignoring @attrs.
1502 * Normally this parameter is NULL. This parameter is ignored when an
1503 * existing file is opened.
1505 * Creates a new file handle. This only applies to normal files:
1506 * pipes are handled by CreatePipe(), and console handles are created
1507 * with GetStdHandle().
1509 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1511 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1512 guint32 sharemode, WapiSecurityAttributes *security,
1513 guint32 createmode, guint32 attrs,
1514 gpointer template G_GNUC_UNUSED)
1516 struct _WapiHandle_file file_handle = {0};
1518 int flags=convert_flags(fileaccess, createmode);
1519 /*mode_t perms=convert_perms(sharemode);*/
1520 /* we don't use sharemode, because that relates to sharing of
1521 * the file when the file is open and is already handled by
1522 * other code, perms instead are the on-disk permissions and
1523 * this is a sane default.
1529 struct stat statbuf;
1531 mono_once (&io_ops_once, io_ops_init);
1533 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1536 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1537 SetLastError (ERROR_ENCRYPTION_FAILED);
1538 return INVALID_HANDLE_VALUE;
1543 g_message ("%s: name is NULL", __func__);
1546 SetLastError (ERROR_INVALID_NAME);
1547 return(INVALID_HANDLE_VALUE);
1550 filename = mono_unicode_to_external (name);
1551 if (filename == NULL) {
1553 g_message("%s: unicode conversion returned NULL", __func__);
1556 SetLastError (ERROR_INVALID_NAME);
1557 return(INVALID_HANDLE_VALUE);
1561 g_message ("%s: Opening %s with share 0x%x and access 0x%x", __func__,
1562 filename, sharemode, fileaccess);
1565 fd = _wapi_open (filename, flags, perms);
1567 /* If we were trying to open a directory with write permissions
1568 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1569 * EISDIR. However, this is a bit bogus because calls to
1570 * manipulate the directory (e.g. SetFileTime) will still work on
1571 * the directory because they use other API calls
1572 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1573 * to open the directory again without write permission.
1575 if (fd == -1 && errno == EISDIR)
1577 /* Try again but don't try to make it writable */
1578 fd = open(filename, flags & ~(O_RDWR|O_WRONLY), perms);
1583 g_message("%s: Error opening file %s: %s", __func__, filename,
1586 _wapi_set_last_path_error_from_errno (NULL, filename);
1589 return(INVALID_HANDLE_VALUE);
1592 if (fd >= _wapi_fd_reserve) {
1594 g_message ("%s: File descriptor is too big", __func__);
1597 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1602 return(INVALID_HANDLE_VALUE);
1605 ret = fstat (fd, &statbuf);
1608 g_message ("%s: fstat error of file %s: %s", __func__,
1609 filename, strerror (errno));
1611 _wapi_set_last_error_from_errno ();
1615 return(INVALID_HANDLE_VALUE);
1618 if (share_check (&statbuf, sharemode, fileaccess,
1619 &file_handle.share_info, fd) == FALSE) {
1620 SetLastError (ERROR_SHARING_VIOLATION);
1624 return (INVALID_HANDLE_VALUE);
1626 if (file_handle.share_info == NULL) {
1627 /* No space, so no more files can be opened */
1629 g_message ("%s: No space in the share table", __func__);
1632 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1636 return(INVALID_HANDLE_VALUE);
1639 file_handle.filename = filename;
1641 if(security!=NULL) {
1642 //file_handle->security_attributes=_wapi_handle_scratch_store (
1643 //security, sizeof(WapiSecurityAttributes));
1646 file_handle.fileaccess=fileaccess;
1647 file_handle.sharemode=sharemode;
1648 file_handle.attrs=attrs;
1650 #ifdef HAVE_POSIX_FADVISE
1651 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1652 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1653 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1654 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1658 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1660 if (S_ISFIFO (statbuf.st_mode)) {
1661 handle_type = WAPI_HANDLE_PIPE;
1662 } else if (S_ISCHR (statbuf.st_mode)) {
1663 handle_type = WAPI_HANDLE_CONSOLE;
1665 handle_type = WAPI_HANDLE_FILE;
1668 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1669 if (handle == _WAPI_HANDLE_INVALID) {
1670 g_warning ("%s: error creating file handle", __func__);
1674 SetLastError (ERROR_GEN_FAILURE);
1675 return(INVALID_HANDLE_VALUE);
1679 g_message("%s: returning handle %p", __func__, handle);
1687 * @name: a pointer to a NULL-terminated unicode string, that names
1688 * the file to be deleted.
1690 * Deletes file @name.
1692 * Return value: %TRUE on success, %FALSE otherwise.
1694 gboolean DeleteFile(const gunichar2 *name)
1698 gboolean ret = FALSE;
1701 struct stat statbuf;
1702 struct _WapiFileShare *shareinfo;
1707 g_message("%s: name is NULL", __func__);
1710 SetLastError (ERROR_INVALID_NAME);
1714 filename=mono_unicode_to_external(name);
1715 if(filename==NULL) {
1717 g_message("%s: unicode conversion returned NULL", __func__);
1720 SetLastError (ERROR_INVALID_NAME);
1724 attrs = GetFileAttributes (name);
1725 if (attrs == INVALID_FILE_ATTRIBUTES) {
1727 g_message ("%s: file attributes error", __func__);
1729 /* Error set by GetFileAttributes() */
1734 if (attrs & FILE_ATTRIBUTE_READONLY) {
1736 g_message ("%s: file %s is readonly", __func__, filename);
1738 SetLastError (ERROR_ACCESS_DENIED);
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);
1763 _wapi_handle_share_release (shareinfo);
1766 retval = _wapi_unlink (filename);
1769 _wapi_set_last_path_error_from_errno (NULL, filename);
1781 * @name: a pointer to a NULL-terminated unicode string, that names
1782 * the file to be moved.
1783 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1784 * new name for the file.
1786 * Renames file @name to @dest_name.
1787 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1788 * when it is the same file as the source. In that case it silently succeeds.
1790 * Return value: %TRUE on success, %FALSE otherwise.
1792 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1794 gchar *utf8_name, *utf8_dest_name;
1795 int result, errno_copy;
1796 struct stat stat_src, stat_dest;
1797 gboolean ret = FALSE;
1798 struct _WapiFileShare *shareinfo;
1802 g_message("%s: name is NULL", __func__);
1805 SetLastError (ERROR_INVALID_NAME);
1809 utf8_name = mono_unicode_to_external (name);
1810 if (utf8_name == NULL) {
1812 g_message ("%s: unicode conversion returned NULL", __func__);
1815 SetLastError (ERROR_INVALID_NAME);
1819 if(dest_name==NULL) {
1821 g_message("%s: name is NULL", __func__);
1825 SetLastError (ERROR_INVALID_NAME);
1829 utf8_dest_name = mono_unicode_to_external (dest_name);
1830 if (utf8_dest_name == NULL) {
1832 g_message ("%s: unicode conversion returned NULL", __func__);
1836 SetLastError (ERROR_INVALID_NAME);
1841 * In C# land we check for the existence of src, but not for dest.
1842 * We check it here and return the failure if dest exists and is not
1843 * the same file as src.
1845 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1846 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1848 g_free (utf8_dest_name);
1852 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1853 if (stat_dest.st_dev != stat_src.st_dev ||
1854 stat_dest.st_ino != stat_src.st_ino) {
1856 g_free (utf8_dest_name);
1857 SetLastError (ERROR_ALREADY_EXISTS);
1862 /* Check to make sure sharing allows us to open the file for
1863 * writing. See bug 377049.
1865 * Do the checks that don't need an open file descriptor, for
1866 * simplicity's sake. If we really have to do the full checks
1867 * then we can implement that later.
1869 if (share_allows_open (&stat_src, 0, GENERIC_WRITE,
1870 &shareinfo) == FALSE) {
1871 SetLastError (ERROR_SHARING_VIOLATION);
1874 _wapi_handle_share_release (shareinfo);
1876 result = _wapi_rename (utf8_name, utf8_dest_name);
1880 switch(errno_copy) {
1882 SetLastError (ERROR_ALREADY_EXISTS);
1886 /* Ignore here, it is dealt with below */
1890 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1895 g_free (utf8_dest_name);
1897 if (result != 0 && errno_copy == EXDEV) {
1898 /* Try a copy to the new location, and delete the source */
1899 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1900 /* CopyFile will set the error */
1904 return(DeleteFile (name));
1915 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1919 int buf_size = st_src->st_blksize;
1921 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1922 buf = (char *) malloc (buf_size);
1925 remain = read (src_fd, buf, buf_size);
1927 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1931 _wapi_set_last_error_from_errno ();
1941 while (remain > 0) {
1942 if ((n = write (dest_fd, wbuf, remain)) < 0) {
1943 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1947 _wapi_set_last_error_from_errno ();
1949 g_message ("%s: write failed.", __func__);
1966 * @name: a pointer to a NULL-terminated unicode string, that names
1967 * the file to be copied.
1968 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1969 * new name for the file.
1970 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1972 * Copies file @name to @dest_name
1974 * Return value: %TRUE on success, %FALSE otherwise.
1976 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1977 gboolean fail_if_exists)
1979 gchar *utf8_src, *utf8_dest;
1980 int src_fd, dest_fd;
1982 gboolean ret = TRUE;
1986 g_message("%s: name is NULL", __func__);
1989 SetLastError (ERROR_INVALID_NAME);
1993 utf8_src = mono_unicode_to_external (name);
1994 if (utf8_src == NULL) {
1996 g_message ("%s: unicode conversion of source returned NULL",
2000 SetLastError (ERROR_INVALID_PARAMETER);
2004 if(dest_name==NULL) {
2006 g_message("%s: name is NULL", __func__);
2010 SetLastError (ERROR_INVALID_NAME);
2014 utf8_dest = mono_unicode_to_external (dest_name);
2015 if (utf8_dest == NULL) {
2017 g_message ("%s: unicode conversion of dest returned NULL",
2021 SetLastError (ERROR_INVALID_PARAMETER);
2028 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2030 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2038 if (fstat (src_fd, &st) < 0) {
2039 _wapi_set_last_error_from_errno ();
2048 if (fail_if_exists) {
2049 dest_fd = open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL,
2052 dest_fd = open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2054 /* O_TRUNC might cause a fail if the file
2057 dest_fd = open (utf8_dest, O_WRONLY | O_CREAT,
2060 /* Apparently this error is set if we
2061 * overwrite the dest file
2063 SetLastError (ERROR_ALREADY_EXISTS);
2067 _wapi_set_last_error_from_errno ();
2076 if (!write_file (src_fd, dest_fd, &st, TRUE))
2088 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2094 g_message ("%s: %s is NULL", __func__, arg_name);
2096 SetLastError (ERROR_INVALID_NAME);
2100 utf8_ret = mono_unicode_to_external (arg);
2101 if (utf8_ret == NULL) {
2103 g_message ("%s: unicode conversion of %s returned NULL",
2104 __func__, arg_name);
2106 SetLastError (ERROR_INVALID_PARAMETER);
2114 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2115 const gunichar2 *backupFileName, guint32 replaceFlags,
2116 gpointer exclude, gpointer reserved)
2118 int result, errno_copy, backup_fd = -1,replaced_fd = -1;
2119 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2120 struct stat stBackup;
2121 gboolean ret = FALSE;
2123 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2125 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2126 goto replace_cleanup;
2127 if (backupFileName != NULL) {
2128 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2129 goto replace_cleanup;
2132 if (utf8_backupFileName) {
2133 // Open the backup file for read so we can restore the file if an error occurs.
2134 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2135 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2138 goto replace_cleanup;
2141 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2144 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2145 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2146 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2147 replaced_fd = open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2149 if (replaced_fd == -1) {
2150 replaced_fd = open (utf8_backupFileName, O_WRONLY | O_CREAT,
2153 if (replaced_fd == -1)
2154 goto replace_cleanup;
2156 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2159 goto replace_cleanup;
2165 g_free (utf8_replacedFileName);
2166 g_free (utf8_replacementFileName);
2167 g_free (utf8_backupFileName);
2168 if (backup_fd != -1)
2170 if (replaced_fd != -1)
2171 close (replaced_fd);
2175 static gpointer stdhandle_create (int fd, const gchar *name)
2177 struct _WapiHandle_file file_handle = {0};
2182 g_message("%s: creating standard handle type %s, fd %d", __func__,
2186 /* Check if fd is valid */
2188 flags=fcntl(fd, F_GETFL);
2189 } while (flags == -1 && errno == EINTR);
2192 /* Invalid fd. Not really much point checking for EBADF
2196 g_message("%s: fcntl error on fd %d: %s", __func__, fd,
2200 _wapi_set_last_error_from_errno ();
2201 return(INVALID_HANDLE_VALUE);
2204 file_handle.filename = g_strdup(name);
2205 /* some default security attributes might be needed */
2206 file_handle.security_attributes=0;
2207 file_handle.fileaccess=convert_from_flags(flags);
2209 /* Apparently input handles can't be written to. (I don't
2210 * know if output or error handles can't be read from.)
2213 file_handle.fileaccess &= ~GENERIC_WRITE;
2216 file_handle.sharemode=0;
2217 file_handle.attrs=0;
2219 handle = _wapi_handle_new_fd (WAPI_HANDLE_CONSOLE, fd, &file_handle);
2220 if (handle == _WAPI_HANDLE_INVALID) {
2221 g_warning ("%s: error creating file handle", __func__);
2222 SetLastError (ERROR_GEN_FAILURE);
2223 return(INVALID_HANDLE_VALUE);
2227 g_message("%s: returning handle %p", __func__, handle);
2235 * @stdhandle: specifies the file descriptor
2237 * Returns a handle for stdin, stdout, or stderr. Always returns the
2238 * same handle for the same @stdhandle.
2240 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2243 static mono_mutex_t stdhandle_mutex = MONO_MUTEX_INITIALIZER;
2245 gpointer GetStdHandle(WapiStdHandle stdhandle)
2247 struct _WapiHandle_file *file_handle;
2254 case STD_INPUT_HANDLE:
2259 case STD_OUTPUT_HANDLE:
2264 case STD_ERROR_HANDLE:
2271 g_message("%s: unknown standard handle type", __func__);
2274 SetLastError (ERROR_INVALID_PARAMETER);
2275 return(INVALID_HANDLE_VALUE);
2278 handle = GINT_TO_POINTER (fd);
2280 pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2281 (void *)&stdhandle_mutex);
2282 thr_ret = mono_mutex_lock (&stdhandle_mutex);
2283 g_assert (thr_ret == 0);
2285 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2286 (gpointer *)&file_handle);
2288 /* Need to create this console handle */
2289 handle = stdhandle_create (fd, name);
2291 if (handle == INVALID_HANDLE_VALUE) {
2292 SetLastError (ERROR_NO_MORE_FILES);
2296 /* Add a reference to this handle */
2297 _wapi_handle_ref (handle);
2301 thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2302 g_assert (thr_ret == 0);
2303 pthread_cleanup_pop (0);
2310 * @handle: The file handle to read from. The handle must have
2311 * %GENERIC_READ access.
2312 * @buffer: The buffer to store read data in
2313 * @numbytes: The maximum number of bytes to read
2314 * @bytesread: The actual number of bytes read is stored here. This
2315 * value can be zero if the handle is positioned at the end of the
2317 * @overlapped: points to a required %WapiOverlapped structure if
2318 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2321 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2322 * function reads up to @numbytes bytes from the file from the current
2323 * file position, and stores them in @buffer. If there are not enough
2324 * bytes left in the file, just the amount available will be read.
2325 * The actual number of bytes read is stored in @bytesread.
2327 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2328 * file position is ignored and the read position is taken from data
2329 * in the @overlapped structure.
2331 * Return value: %TRUE if the read succeeds (even if no bytes were
2332 * read due to an attempt to read past the end of the file), %FALSE on
2335 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2336 guint32 *bytesread, WapiOverlapped *overlapped)
2338 WapiHandleType type;
2340 type = _wapi_handle_type (handle);
2342 if(io_ops[type].readfile==NULL) {
2343 SetLastError (ERROR_INVALID_HANDLE);
2347 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2353 * @handle: The file handle to write to. The handle must have
2354 * %GENERIC_WRITE access.
2355 * @buffer: The buffer to read data from.
2356 * @numbytes: The maximum number of bytes to write.
2357 * @byteswritten: The actual number of bytes written is stored here.
2358 * If the handle is positioned at the file end, the length of the file
2359 * is extended. This parameter may be %NULL.
2360 * @overlapped: points to a required %WapiOverlapped structure if
2361 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2364 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2365 * function writes up to @numbytes bytes from @buffer to the file at
2366 * the current file position. If @handle is positioned at the end of
2367 * the file, the file is extended. The actual number of bytes written
2368 * is stored in @byteswritten.
2370 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2371 * file position is ignored and the write position is taken from data
2372 * in the @overlapped structure.
2374 * Return value: %TRUE if the write succeeds, %FALSE on error.
2376 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2377 guint32 *byteswritten, WapiOverlapped *overlapped)
2379 WapiHandleType type;
2381 type = _wapi_handle_type (handle);
2383 if(io_ops[type].writefile==NULL) {
2384 SetLastError (ERROR_INVALID_HANDLE);
2388 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2394 * @handle: Handle to open file. The handle must have
2395 * %GENERIC_WRITE access.
2397 * Flushes buffers of the file and causes all unwritten data to
2400 * Return value: %TRUE on success, %FALSE otherwise.
2402 gboolean FlushFileBuffers(gpointer handle)
2404 WapiHandleType type;
2406 type = _wapi_handle_type (handle);
2408 if(io_ops[type].flushfile==NULL) {
2409 SetLastError (ERROR_INVALID_HANDLE);
2413 return(io_ops[type].flushfile (handle));
2418 * @handle: The file handle to set. The handle must have
2419 * %GENERIC_WRITE access.
2421 * Moves the end-of-file position to the current position of the file
2422 * pointer. This function is used to truncate or extend a file.
2424 * Return value: %TRUE on success, %FALSE otherwise.
2426 gboolean SetEndOfFile(gpointer handle)
2428 WapiHandleType type;
2430 type = _wapi_handle_type (handle);
2432 if (io_ops[type].setendoffile == NULL) {
2433 SetLastError (ERROR_INVALID_HANDLE);
2437 return(io_ops[type].setendoffile (handle));
2442 * @handle: The file handle to set. The handle must have
2443 * %GENERIC_READ or %GENERIC_WRITE access.
2444 * @movedistance: Low 32 bits of a signed value that specifies the
2445 * number of bytes to move the file pointer.
2446 * @highmovedistance: Pointer to the high 32 bits of a signed value
2447 * that specifies the number of bytes to move the file pointer, or
2449 * @method: The starting point for the file pointer move.
2451 * Sets the file pointer of an open file.
2453 * The distance to move the file pointer is calculated from
2454 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2455 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2456 * is the low 32 bits and @highmovedistance a pointer to the high 32
2457 * bits of a 64 bit signed value. A positive distance moves the file
2458 * pointer forward from the position specified by @method; a negative
2459 * distance moves the file pointer backward.
2461 * If the library is compiled without large file support,
2462 * @highmovedistance is ignored and its value is set to zero on a
2463 * successful return.
2465 * Return value: On success, the low 32 bits of the new file pointer.
2466 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2467 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2469 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2470 gint32 *highmovedistance, WapiSeekMethod method)
2472 WapiHandleType type;
2474 type = _wapi_handle_type (handle);
2476 if (io_ops[type].seek == NULL) {
2477 SetLastError (ERROR_INVALID_HANDLE);
2478 return(INVALID_SET_FILE_POINTER);
2481 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2487 * @handle: The file handle to test.
2489 * Finds the type of file @handle.
2491 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2492 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2493 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2494 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2496 WapiFileType GetFileType(gpointer handle)
2498 WapiHandleType type;
2500 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2501 SetLastError (ERROR_INVALID_HANDLE);
2502 return(FILE_TYPE_UNKNOWN);
2505 type = _wapi_handle_type (handle);
2507 if (io_ops[type].getfiletype == NULL) {
2508 SetLastError (ERROR_INVALID_HANDLE);
2509 return(FILE_TYPE_UNKNOWN);
2512 return(io_ops[type].getfiletype ());
2517 * @handle: The file handle to query. The handle must have
2518 * %GENERIC_READ or %GENERIC_WRITE access.
2519 * @highsize: If non-%NULL, the high 32 bits of the file size are
2522 * Retrieves the size of the file @handle.
2524 * If the library is compiled without large file support, @highsize
2525 * has its value set to zero on a successful return.
2527 * Return value: On success, the low 32 bits of the file size. If
2528 * @highsize is non-%NULL then the high 32 bits of the file size are
2529 * stored here. On failure %INVALID_FILE_SIZE is returned.
2531 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2533 WapiHandleType type;
2535 type = _wapi_handle_type (handle);
2537 if (io_ops[type].getfilesize == NULL) {
2538 SetLastError (ERROR_INVALID_HANDLE);
2539 return(INVALID_FILE_SIZE);
2542 return(io_ops[type].getfilesize (handle, highsize));
2547 * @handle: The file handle to query. The handle must have
2548 * %GENERIC_READ access.
2549 * @create_time: Points to a %WapiFileTime structure to receive the
2550 * number of ticks since the epoch that file was created. May be
2552 * @last_access: Points to a %WapiFileTime structure to receive the
2553 * number of ticks since the epoch when file was last accessed. May be
2555 * @last_write: Points to a %WapiFileTime structure to receive the
2556 * number of ticks since the epoch when file was last written to. May
2559 * Finds the number of ticks since the epoch that the file referenced
2560 * by @handle was created, last accessed and last modified. A tick is
2561 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2564 * Create time isn't recorded on POSIX file systems or reported by
2565 * stat(2), so that time is guessed by returning the oldest of the
2568 * Return value: %TRUE on success, %FALSE otherwise.
2570 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2571 WapiFileTime *last_access, WapiFileTime *last_write)
2573 WapiHandleType type;
2575 type = _wapi_handle_type (handle);
2577 if (io_ops[type].getfiletime == NULL) {
2578 SetLastError (ERROR_INVALID_HANDLE);
2582 return(io_ops[type].getfiletime (handle, create_time, last_access,
2588 * @handle: The file handle to set. The handle must have
2589 * %GENERIC_WRITE access.
2590 * @create_time: Points to a %WapiFileTime structure that contains the
2591 * number of ticks since the epoch that the file was created. May be
2593 * @last_access: Points to a %WapiFileTime structure that contains the
2594 * number of ticks since the epoch when the file was last accessed.
2596 * @last_write: Points to a %WapiFileTime structure that contains the
2597 * number of ticks since the epoch when the file was last written to.
2600 * Sets the number of ticks since the epoch that the file referenced
2601 * by @handle was created, last accessed or last modified. A tick is
2602 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2605 * Create time isn't recorded on POSIX file systems, and is ignored.
2607 * Return value: %TRUE on success, %FALSE otherwise.
2609 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2610 const WapiFileTime *last_access,
2611 const WapiFileTime *last_write)
2613 WapiHandleType type;
2615 type = _wapi_handle_type (handle);
2617 if (io_ops[type].setfiletime == NULL) {
2618 SetLastError (ERROR_INVALID_HANDLE);
2622 return(io_ops[type].setfiletime (handle, create_time, last_access,
2626 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2627 * January 1 1601 GMT
2630 #define TICKS_PER_MILLISECOND 10000L
2631 #define TICKS_PER_SECOND 10000000L
2632 #define TICKS_PER_MINUTE 600000000L
2633 #define TICKS_PER_HOUR 36000000000LL
2634 #define TICKS_PER_DAY 864000000000LL
2636 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2638 static const guint16 mon_yday[2][13]={
2639 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2640 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2644 * FileTimeToSystemTime:
2645 * @file_time: Points to a %WapiFileTime structure that contains the
2646 * number of ticks to convert.
2647 * @system_time: Points to a %WapiSystemTime structure to receive the
2650 * Converts a tick count into broken-out time values.
2652 * Return value: %TRUE on success, %FALSE otherwise.
2654 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2655 WapiSystemTime *system_time)
2657 gint64 file_ticks, totaldays, rem, y;
2660 if(system_time==NULL) {
2662 g_message("%s: system_time NULL", __func__);
2665 SetLastError (ERROR_INVALID_PARAMETER);
2669 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2670 file_time->dwLowDateTime;
2672 /* Really compares if file_ticks>=0x8000000000000000
2673 * (LLONG_MAX+1) but we're working with a signed value for the
2674 * year and day calculation to work later
2678 g_message("%s: file_time too big", __func__);
2681 SetLastError (ERROR_INVALID_PARAMETER);
2685 totaldays=(file_ticks / TICKS_PER_DAY);
2686 rem = file_ticks % TICKS_PER_DAY;
2688 g_message("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2691 system_time->wHour=rem/TICKS_PER_HOUR;
2692 rem %= TICKS_PER_HOUR;
2694 g_message("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2697 system_time->wMinute = rem / TICKS_PER_MINUTE;
2698 rem %= TICKS_PER_MINUTE;
2700 g_message("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2704 system_time->wSecond = rem / TICKS_PER_SECOND;
2705 rem %= TICKS_PER_SECOND;
2707 g_message("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2711 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2713 g_message("%s: Milliseconds: %d", __func__,
2714 system_time->wMilliseconds);
2717 /* January 1, 1601 was a Monday, according to Emacs calendar */
2718 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2720 g_message("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2723 /* This algorithm to find year and month given days from epoch
2728 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2729 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2731 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2732 /* Guess a corrected year, assuming 365 days per year */
2733 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2735 g_message("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2738 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2739 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2742 /* Adjust days and y to match the guessed year. */
2743 totaldays -= ((yg - y) * 365
2744 + LEAPS_THRU_END_OF (yg - 1)
2745 - LEAPS_THRU_END_OF (y - 1));
2747 g_message("%s: totaldays: %lld", __func__, totaldays);
2751 g_message("%s: y: %lld", __func__, y);
2755 system_time->wYear = y;
2757 g_message("%s: Year: %d", __func__, system_time->wYear);
2760 ip = mon_yday[isleap(y)];
2762 for(y=11; totaldays < ip[y]; --y) {
2767 g_message("%s: totaldays: %lld", __func__, totaldays);
2770 system_time->wMonth = y + 1;
2772 g_message("%s: Month: %d", __func__, system_time->wMonth);
2775 system_time->wDay = totaldays + 1;
2777 g_message("%s: Day: %d", __func__, system_time->wDay);
2783 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2785 struct _WapiHandle_find find_handle = {0};
2787 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2790 if (pattern == NULL) {
2792 g_message ("%s: pattern is NULL", __func__);
2795 SetLastError (ERROR_PATH_NOT_FOUND);
2796 return(INVALID_HANDLE_VALUE);
2799 utf8_pattern = mono_unicode_to_external (pattern);
2800 if (utf8_pattern == NULL) {
2802 g_message ("%s: unicode conversion returned NULL", __func__);
2805 SetLastError (ERROR_INVALID_NAME);
2806 return(INVALID_HANDLE_VALUE);
2810 g_message ("%s: looking for [%s]", __func__, utf8_pattern);
2813 /* Figure out which bit of the pattern is the directory */
2814 dir_part = _wapi_dirname (utf8_pattern);
2815 entry_part = _wapi_basename (utf8_pattern);
2818 /* Don't do this check for now, it breaks if directories
2819 * really do have metachars in their names (see bug 58116).
2820 * FIXME: Figure out a better solution to keep some checks...
2822 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2823 SetLastError (ERROR_INVALID_NAME);
2825 g_free (entry_part);
2826 g_free (utf8_pattern);
2827 return(INVALID_HANDLE_VALUE);
2831 /* The pattern can specify a directory or a set of files.
2833 * The pattern can have wildcard characters ? and *, but only
2834 * in the section after the last directory delimiter. (Return
2835 * ERROR_INVALID_NAME if there are wildcards in earlier path
2836 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2837 * means "match one character", "??" seems to mean "match one
2838 * or two characters", "???" seems to mean "match one, two or
2839 * three characters", etc. Windows will also try and match
2840 * the mangled "short name" of files, so 8 character patterns
2841 * with wildcards will show some surprising results.
2843 * All the written documentation I can find says that '?'
2844 * should only match one character, and doesn't mention '??',
2845 * '???' etc. I'm going to assume that the strict behaviour
2846 * (ie '???' means three and only three characters) is the
2847 * correct one, because that lets me use fnmatch(3) rather
2848 * than mess around with regexes.
2851 find_handle.namelist = NULL;
2852 result = _wapi_io_scandir (dir_part, entry_part,
2853 &find_handle.namelist);
2856 /* No files, which windows seems to call
2859 SetLastError (ERROR_FILE_NOT_FOUND);
2860 g_free (utf8_pattern);
2861 g_free (entry_part);
2863 return (INVALID_HANDLE_VALUE);
2868 gint errnum = errno;
2870 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2872 g_message ("%s: scandir error: %s", __func__,
2873 g_strerror (errnum));
2875 g_free (utf8_pattern);
2876 g_free (entry_part);
2878 return (INVALID_HANDLE_VALUE);
2881 g_free (utf8_pattern);
2882 g_free (entry_part);
2885 g_message ("%s: Got %d matches", __func__, result);
2888 find_handle.dir_part = dir_part;
2889 find_handle.num = result;
2890 find_handle.count = 0;
2892 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2893 if (handle == _WAPI_HANDLE_INVALID) {
2894 g_warning ("%s: error creating find handle", __func__);
2896 g_free (entry_part);
2897 g_free (utf8_pattern);
2898 SetLastError (ERROR_GEN_FAILURE);
2900 return(INVALID_HANDLE_VALUE);
2903 if (handle != INVALID_HANDLE_VALUE &&
2904 !FindNextFile (handle, find_data)) {
2906 SetLastError (ERROR_NO_MORE_FILES);
2907 handle = INVALID_HANDLE_VALUE;
2913 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2915 struct _WapiHandle_find *find_handle;
2917 struct stat buf, linkbuf;
2920 gchar *utf8_filename, *utf8_basename;
2921 gunichar2 *utf16_basename;
2925 gboolean ret = FALSE;
2927 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2928 (gpointer *)&find_handle);
2930 g_warning ("%s: error looking up find handle %p", __func__,
2932 SetLastError (ERROR_INVALID_HANDLE);
2936 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2938 thr_ret = _wapi_handle_lock_handle (handle);
2939 g_assert (thr_ret == 0);
2942 if (find_handle->count >= find_handle->num) {
2943 SetLastError (ERROR_NO_MORE_FILES);
2947 /* stat next match */
2949 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2951 result = _wapi_stat (filename, &buf);
2952 if (result == -1 && errno == ENOENT) {
2953 /* Might be a dangling symlink */
2954 result = _wapi_lstat (filename, &buf);
2959 g_message ("%s: stat failed: %s", __func__, filename);
2966 result = _wapi_lstat (filename, &linkbuf);
2969 g_message ("%s: lstat failed: %s", __func__, filename);
2976 utf8_filename = mono_utf8_from_external (filename);
2977 if (utf8_filename == NULL) {
2978 /* We couldn't turn this filename into utf8 (eg the
2979 * encoding of the name wasn't convertible), so just
2982 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2990 g_message ("%s: Found [%s]", __func__, utf8_filename);
2993 /* fill data block */
2995 if (buf.st_mtime < buf.st_ctime)
2996 create_time = buf.st_mtime;
2998 create_time = buf.st_ctime;
3000 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
3002 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
3003 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
3004 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
3006 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3007 find_data->nFileSizeHigh = 0;
3008 find_data->nFileSizeLow = 0;
3010 find_data->nFileSizeHigh = buf.st_size >> 32;
3011 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3014 find_data->dwReserved0 = 0;
3015 find_data->dwReserved1 = 0;
3017 utf8_basename = _wapi_basename (utf8_filename);
3018 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
3020 if(utf16_basename==NULL) {
3021 g_free (utf8_basename);
3022 g_free (utf8_filename);
3027 /* utf16 is 2 * utf8 */
3030 memset (find_data->cFileName, '\0', (MAX_PATH*2));
3032 /* Truncating a utf16 string like this might leave the last
3035 memcpy (find_data->cFileName, utf16_basename,
3036 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3038 find_data->cAlternateFileName [0] = 0; /* not used */
3040 g_free (utf8_basename);
3041 g_free (utf8_filename);
3042 g_free (utf16_basename);
3045 thr_ret = _wapi_handle_unlock_handle (handle);
3046 g_assert (thr_ret == 0);
3047 pthread_cleanup_pop (0);
3054 * @wapi_handle: the find handle to close.
3056 * Closes find handle @wapi_handle
3058 * Return value: %TRUE on success, %FALSE otherwise.
3060 gboolean FindClose (gpointer handle)
3062 struct _WapiHandle_find *find_handle;
3066 if (handle == NULL) {
3067 SetLastError (ERROR_INVALID_HANDLE);
3071 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
3072 (gpointer *)&find_handle);
3074 g_warning ("%s: error looking up find handle %p", __func__,
3076 SetLastError (ERROR_INVALID_HANDLE);
3080 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
3082 thr_ret = _wapi_handle_lock_handle (handle);
3083 g_assert (thr_ret == 0);
3085 g_strfreev (find_handle->namelist);
3086 g_free (find_handle->dir_part);
3088 thr_ret = _wapi_handle_unlock_handle (handle);
3089 g_assert (thr_ret == 0);
3090 pthread_cleanup_pop (0);
3092 _wapi_handle_unref (handle);
3099 * @name: a pointer to a NULL-terminated unicode string, that names
3100 * the directory to be created.
3101 * @security: ignored for now
3103 * Creates directory @name
3105 * Return value: %TRUE on success, %FALSE otherwise.
3107 gboolean CreateDirectory (const gunichar2 *name,
3108 WapiSecurityAttributes *security)
3115 g_message("%s: name is NULL", __func__);
3118 SetLastError (ERROR_INVALID_NAME);
3122 utf8_name = mono_unicode_to_external (name);
3123 if (utf8_name == NULL) {
3125 g_message ("%s: unicode conversion returned NULL", __func__);
3128 SetLastError (ERROR_INVALID_NAME);
3132 result = _wapi_mkdir (utf8_name, 0777);
3139 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3146 * @name: a pointer to a NULL-terminated unicode string, that names
3147 * the directory to be removed.
3149 * Removes directory @name
3151 * Return value: %TRUE on success, %FALSE otherwise.
3153 gboolean RemoveDirectory (const gunichar2 *name)
3160 g_message("%s: name is NULL", __func__);
3163 SetLastError (ERROR_INVALID_NAME);
3167 utf8_name = mono_unicode_to_external (name);
3168 if (utf8_name == NULL) {
3170 g_message ("%s: unicode conversion returned NULL", __func__);
3173 SetLastError (ERROR_INVALID_NAME);
3177 result = _wapi_rmdir (utf8_name);
3179 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3190 * GetFileAttributes:
3191 * @name: a pointer to a NULL-terminated unicode filename.
3193 * Gets the attributes for @name;
3195 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3197 guint32 GetFileAttributes (const gunichar2 *name)
3200 struct stat buf, linkbuf;
3206 g_message("%s: name is NULL", __func__);
3209 SetLastError (ERROR_INVALID_NAME);
3213 utf8_name = mono_unicode_to_external (name);
3214 if (utf8_name == NULL) {
3216 g_message ("%s: unicode conversion returned NULL", __func__);
3219 SetLastError (ERROR_INVALID_PARAMETER);
3220 return (INVALID_FILE_ATTRIBUTES);
3223 result = _wapi_stat (utf8_name, &buf);
3224 if (result == -1 && errno == ENOENT) {
3225 /* Might be a dangling symlink... */
3226 result = _wapi_lstat (utf8_name, &buf);
3230 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3232 return (INVALID_FILE_ATTRIBUTES);
3235 result = _wapi_lstat (utf8_name, &linkbuf);
3237 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3239 return (INVALID_FILE_ATTRIBUTES);
3242 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3250 * GetFileAttributesEx:
3251 * @name: a pointer to a NULL-terminated unicode filename.
3252 * @level: must be GetFileExInfoStandard
3253 * @info: pointer to a WapiFileAttributesData structure
3255 * Gets attributes, size and filetimes for @name;
3257 * Return value: %TRUE on success, %FALSE on failure
3259 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3262 WapiFileAttributesData *data;
3264 struct stat buf, linkbuf;
3268 if (level != GetFileExInfoStandard) {
3270 g_message ("%s: info level %d not supported.", __func__,
3274 SetLastError (ERROR_INVALID_PARAMETER);
3280 g_message("%s: name is NULL", __func__);
3283 SetLastError (ERROR_INVALID_NAME);
3287 utf8_name = mono_unicode_to_external (name);
3288 if (utf8_name == NULL) {
3290 g_message ("%s: unicode conversion returned NULL", __func__);
3293 SetLastError (ERROR_INVALID_PARAMETER);
3297 result = _wapi_stat (utf8_name, &buf);
3298 if (result == -1 && errno == ENOENT) {
3299 /* Might be a dangling symlink... */
3300 result = _wapi_lstat (utf8_name, &buf);
3304 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3309 result = _wapi_lstat (utf8_name, &linkbuf);
3311 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3316 /* fill data block */
3318 data = (WapiFileAttributesData *)info;
3320 if (buf.st_mtime < buf.st_ctime)
3321 create_time = buf.st_mtime;
3323 create_time = buf.st_ctime;
3325 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3331 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3332 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3333 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3335 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3336 data->nFileSizeHigh = 0;
3337 data->nFileSizeLow = 0;
3340 data->nFileSizeHigh = buf.st_size >> 32;
3341 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3349 * @name: name of file
3350 * @attrs: attributes to set
3352 * Changes the attributes on a named file.
3354 * Return value: %TRUE on success, %FALSE on failure.
3356 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3358 /* FIXME: think of something clever to do on unix */
3364 * Currently we only handle one *internal* case, with a value that is
3365 * not standard: 0x80000000, which means `set executable bit'
3370 g_message("%s: name is NULL", __func__);
3373 SetLastError (ERROR_INVALID_NAME);
3377 utf8_name = mono_unicode_to_external (name);
3378 if (utf8_name == NULL) {
3380 g_message ("%s: unicode conversion returned NULL", __func__);
3383 SetLastError (ERROR_INVALID_NAME);
3387 result = _wapi_stat (utf8_name, &buf);
3389 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3394 /* Contrary to the documentation, ms allows NORMAL to be
3395 * specified along with other attributes, so dont bother to
3396 * catch that case here.
3398 if (attrs & FILE_ATTRIBUTE_READONLY) {
3399 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3401 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3404 /* Ignore the other attributes for now */
3406 if (attrs & 0x80000000){
3407 mode_t exec_mask = 0;
3409 if ((buf.st_mode & S_IRUSR) != 0)
3410 exec_mask |= S_IXUSR;
3412 if ((buf.st_mode & S_IRGRP) != 0)
3413 exec_mask |= S_IXGRP;
3415 if ((buf.st_mode & S_IROTH) != 0)
3416 exec_mask |= S_IXOTH;
3418 result = chmod (utf8_name, buf.st_mode | exec_mask);
3420 /* Don't bother to reset executable (might need to change this
3430 * GetCurrentDirectory
3431 * @length: size of the buffer
3432 * @buffer: pointer to buffer that recieves path
3434 * Retrieves the current directory for the current process.
3436 * Return value: number of characters in buffer on success, zero on failure
3438 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3440 gunichar2 *utf16_path;
3444 if (getcwd ((char*)buffer, length) == NULL) {
3445 if (errno == ERANGE) { /*buffer length is not big enough */
3446 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*/
3449 utf16_path = mono_unicode_from_external (path, &bytes);
3450 g_free (utf16_path);
3454 _wapi_set_last_error_from_errno ();
3458 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3459 count = (bytes/2)+1;
3460 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3462 /* Add the terminator */
3463 memset (buffer, '\0', bytes+2);
3464 memcpy (buffer, utf16_path, bytes);
3466 g_free (utf16_path);
3472 * SetCurrentDirectory
3473 * @path: path to new directory
3475 * Changes the directory path for the current process.
3477 * Return value: %TRUE on success, %FALSE on failure.
3479 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3485 SetLastError (ERROR_INVALID_PARAMETER);
3489 utf8_path = mono_unicode_to_external (path);
3490 if (_wapi_chdir (utf8_path) != 0) {
3491 _wapi_set_last_error_from_errno ();
3501 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3502 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3504 struct _WapiHandle_file pipe_read_handle = {0};
3505 struct _WapiHandle_file pipe_write_handle = {0};
3506 gpointer read_handle;
3507 gpointer write_handle;
3511 mono_once (&io_ops_once, io_ops_init);
3514 g_message ("%s: Creating pipe", __func__);
3520 g_message ("%s: Error creating pipe: %s", __func__,
3524 _wapi_set_last_error_from_errno ();
3528 if (filedes[0] >= _wapi_fd_reserve ||
3529 filedes[1] >= _wapi_fd_reserve) {
3531 g_message ("%s: File descriptor is too big", __func__);
3534 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3542 /* filedes[0] is open for reading, filedes[1] for writing */
3544 pipe_read_handle.fileaccess = GENERIC_READ;
3545 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3547 if (read_handle == _WAPI_HANDLE_INVALID) {
3548 g_warning ("%s: error creating pipe read handle", __func__);
3551 SetLastError (ERROR_GEN_FAILURE);
3556 pipe_write_handle.fileaccess = GENERIC_WRITE;
3557 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3558 &pipe_write_handle);
3559 if (write_handle == _WAPI_HANDLE_INVALID) {
3560 g_warning ("%s: error creating pipe write handle", __func__);
3561 _wapi_handle_unref (read_handle);
3565 SetLastError (ERROR_GEN_FAILURE);
3570 *readpipe = read_handle;
3571 *writepipe = write_handle;
3574 g_message ("%s: Returning pipe: read handle %p, write handle %p",
3575 __func__, read_handle, write_handle);
3581 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3583 gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3584 gunichar2 *tmpdir16=NULL;
3589 if(tmpdir[strlen (tmpdir)]!='/') {
3591 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3594 tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3595 if(tmpdir16==NULL) {
3603 g_message ("%s: Size %d smaller than needed (%ld)",
3604 __func__, len, dirlen+1);
3609 /* Add the terminator */
3610 memset (buf, '\0', bytes+2);
3611 memcpy (buf, tmpdir16, bytes);
3617 if(tmpdir16!=NULL) {
3626 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3629 gunichar2 *ptr, *dir;
3630 glong length, total = 0;
3634 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3639 /* Sigh, mntent and friends don't work well.
3640 * It stops on the first line that doesn't begin with a '/'.
3641 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3642 fp = fopen ("/etc/mtab", "rt");
3644 fp = fopen ("/etc/mnttab", "rt");
3650 while (fgets (buffer, 512, fp) != NULL) {
3654 splitted = g_strsplit (buffer, " ", 0);
3655 if (!*splitted || !*(splitted + 1)) {
3656 g_strfreev (splitted);
3660 dir = g_utf8_to_utf16 (*(splitted + 1), -1, &length, NULL, NULL);
3661 g_strfreev (splitted);
3662 if (total + length + 1 > len) {
3664 return len * 2; /* guess */
3667 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3669 total += length + 1;
3674 /* Commented out, does not work with my mtab!!! - Gonz */
3675 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3679 gunichar2 *ptr, *dir;
3680 glong len, total = 0;
3683 fp = setmntent ("/etc/mtab", "rt");
3685 fp = setmntent ("/etc/mnttab", "rt");
3691 while ((mnt = getmntent (fp)) != NULL) {
3692 g_print ("GOT %s\n", mnt->mnt_dir);
3693 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3694 if (total + len + 1 > len) {
3695 return len * 2; /* guess */
3698 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3709 #if (defined(HAVE_STATVFS) || defined(HAVE_STATFS)) && !defined(PLATFORM_ANDROID)
3710 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3711 WapiULargeInteger *total_number_of_bytes,
3712 WapiULargeInteger *total_number_of_free_bytes)
3715 struct statvfs fsstat;
3716 #elif defined(HAVE_STATFS)
3717 struct statfs fsstat;
3719 gboolean isreadonly;
3720 gchar *utf8_path_name;
3723 if (path_name == NULL) {
3724 utf8_path_name = g_strdup (g_get_current_dir());
3725 if (utf8_path_name == NULL) {
3726 SetLastError (ERROR_DIRECTORY);
3731 utf8_path_name = mono_unicode_to_external (path_name);
3732 if (utf8_path_name == NULL) {
3734 g_message("%s: unicode conversion returned NULL", __func__);
3737 SetLastError (ERROR_INVALID_NAME);
3744 ret = statvfs (utf8_path_name, &fsstat);
3745 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
3746 #elif defined(HAVE_STATFS)
3747 ret = statfs (utf8_path_name, &fsstat);
3748 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
3750 } while(ret == -1 && errno == EINTR);
3752 g_free(utf8_path_name);
3755 _wapi_set_last_error_from_errno ();
3757 g_message ("%s: statvfs failed: %s", __func__, strerror (errno));
3762 /* total number of free bytes for non-root */
3763 if (free_bytes_avail != NULL) {
3765 free_bytes_avail->QuadPart = 0;
3768 free_bytes_avail->QuadPart = fsstat.f_bsize * fsstat.f_bavail;
3772 /* total number of bytes available for non-root */
3773 if (total_number_of_bytes != NULL) {
3774 total_number_of_bytes->QuadPart = fsstat.f_bsize * fsstat.f_blocks;
3777 /* total number of bytes available for root */
3778 if (total_number_of_free_bytes != NULL) {
3780 total_number_of_free_bytes->QuadPart = 0;
3783 total_number_of_free_bytes->QuadPart = fsstat.f_bsize * fsstat.f_bfree;
3790 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3791 WapiULargeInteger *total_number_of_bytes,
3792 WapiULargeInteger *total_number_of_free_bytes)
3794 if (free_bytes_avail != NULL) {
3795 free_bytes_avail->QuadPart = (guint64) -1;
3798 if (total_number_of_bytes != NULL) {
3799 total_number_of_bytes->QuadPart = (guint64) -1;
3802 if (total_number_of_free_bytes != NULL) {
3803 total_number_of_free_bytes->QuadPart = (guint64) -1;
3812 const gchar* fstype;
3815 static _wapi_drive_type _wapi_drive_types[] = {
3816 { DRIVE_RAMDISK, "ramfs" },
3817 { DRIVE_RAMDISK, "tmpfs" },
3818 { DRIVE_RAMDISK, "proc" },
3819 { DRIVE_RAMDISK, "sysfs" },
3820 { DRIVE_RAMDISK, "debugfs" },
3821 { DRIVE_RAMDISK, "devpts" },
3822 { DRIVE_RAMDISK, "securityfs" },
3823 { DRIVE_CDROM, "iso9660" },
3824 { DRIVE_FIXED, "ext2" },
3825 { DRIVE_FIXED, "ext3" },
3826 { DRIVE_FIXED, "ext4" },
3827 { DRIVE_FIXED, "sysv" },
3828 { DRIVE_FIXED, "reiserfs" },
3829 { DRIVE_FIXED, "ufs" },
3830 { DRIVE_FIXED, "vfat" },
3831 { DRIVE_FIXED, "msdos" },
3832 { DRIVE_FIXED, "udf" },
3833 { DRIVE_FIXED, "hfs" },
3834 { DRIVE_FIXED, "hpfs" },
3835 { DRIVE_FIXED, "qnx4" },
3836 { DRIVE_FIXED, "ntfs" },
3837 { DRIVE_FIXED, "ntfs-3g" },
3838 { DRIVE_REMOTE, "smbfs" },
3839 { DRIVE_REMOTE, "fuse" },
3840 { DRIVE_REMOTE, "nfs" },
3841 { DRIVE_REMOTE, "nfs4" },
3842 { DRIVE_REMOTE, "cifs" },
3843 { DRIVE_REMOTE, "ncpfs" },
3844 { DRIVE_REMOTE, "coda" },
3845 { DRIVE_REMOTE, "afs" },
3846 { DRIVE_UNKNOWN, NULL }
3849 static guint32 _wapi_get_drive_type(const gchar* fstype)
3851 _wapi_drive_type *current;
3853 current = &_wapi_drive_types[0];
3854 while (current->drive_type != DRIVE_UNKNOWN) {
3855 if (strcmp (current->fstype, fstype) == 0)
3861 return current->drive_type;
3864 guint32 GetDriveType(const gunichar2 *root_path_name)
3869 gchar *utf8_root_path_name;
3872 if (root_path_name == NULL) {
3873 utf8_root_path_name = g_strdup (g_get_current_dir());
3874 if (utf8_root_path_name == NULL) {
3875 return(DRIVE_NO_ROOT_DIR);
3879 utf8_root_path_name = mono_unicode_to_external (root_path_name);
3880 if (utf8_root_path_name == NULL) {
3882 g_message("%s: unicode conversion returned NULL", __func__);
3884 return(DRIVE_NO_ROOT_DIR);
3887 /* strip trailing slash for compare below */
3888 if (g_str_has_suffix(utf8_root_path_name, "/")) {
3889 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
3893 fp = fopen ("/etc/mtab", "rt");
3895 fp = fopen ("/etc/mnttab", "rt");
3897 g_free (utf8_root_path_name);
3898 return(DRIVE_UNKNOWN);
3902 drive_type = DRIVE_NO_ROOT_DIR;
3903 while (fgets (buffer, 512, fp) != NULL) {
3904 splitted = g_strsplit (buffer, " ", 0);
3905 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
3906 g_strfreev (splitted);
3910 /* compare given root_path_name with the one from mtab,
3911 if length of utf8_root_path_name is zero it must be the root dir */
3912 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
3913 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
3914 drive_type = _wapi_get_drive_type (*(splitted + 2));
3915 g_strfreev (splitted);
3919 g_strfreev (splitted);
3923 g_free (utf8_root_path_name);
3925 return (drive_type);
3928 static gboolean _wapi_lock_file_region (int fd, off_t offset, off_t length)
3930 struct flock lock_data;
3933 lock_data.l_type = F_WRLCK;
3934 lock_data.l_whence = SEEK_SET;
3935 lock_data.l_start = offset;
3936 lock_data.l_len = length;
3939 ret = fcntl (fd, F_SETLK, &lock_data);
3940 } while(ret == -1 && errno == EINTR);
3943 g_message ("%s: fcntl returns %d", __func__, ret);
3948 * if locks are not available (NFS for example),
3953 || errno == EOPNOTSUPP
3962 SetLastError (ERROR_LOCK_VIOLATION);
3969 static gboolean _wapi_unlock_file_region (int fd, off_t offset, off_t length)
3971 struct flock lock_data;
3974 lock_data.l_type = F_UNLCK;
3975 lock_data.l_whence = SEEK_SET;
3976 lock_data.l_start = offset;
3977 lock_data.l_len = length;
3980 ret = fcntl (fd, F_SETLK, &lock_data);
3981 } while(ret == -1 && errno == EINTR);
3984 g_message ("%s: fcntl returns %d", __func__, ret);
3989 * if locks are not available (NFS for example),
3994 || errno == EOPNOTSUPP
4003 SetLastError (ERROR_LOCK_VIOLATION);
4010 gboolean LockFile (gpointer handle, guint32 offset_low, guint32 offset_high,
4011 guint32 length_low, guint32 length_high)
4013 struct _WapiHandle_file *file_handle;
4015 off_t offset, length;
4016 int fd = GPOINTER_TO_UINT(handle);
4018 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
4019 (gpointer *)&file_handle);
4021 g_warning ("%s: error looking up file handle %p", __func__,
4023 SetLastError (ERROR_INVALID_HANDLE);
4027 if (!(file_handle->fileaccess & GENERIC_READ) &&
4028 !(file_handle->fileaccess & GENERIC_WRITE) &&
4029 !(file_handle->fileaccess & GENERIC_ALL)) {
4031 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
4033 SetLastError (ERROR_ACCESS_DENIED);
4037 #ifdef HAVE_LARGE_FILE_SUPPORT
4038 offset = ((gint64)offset_high << 32) | offset_low;
4039 length = ((gint64)length_high << 32) | length_low;
4042 g_message ("%s: Locking handle %p, offset %lld, length %lld", __func__,
4043 handle, offset, length);
4046 offset = offset_low;
4047 length = length_low;
4050 g_message ("%s: Locking handle %p, offset %ld, length %ld", __func__,
4051 handle, offset, length);
4055 return(_wapi_lock_file_region (fd, offset, length));
4058 gboolean UnlockFile (gpointer handle, guint32 offset_low,
4059 guint32 offset_high, guint32 length_low,
4060 guint32 length_high)
4062 struct _WapiHandle_file *file_handle;
4064 off_t offset, length;
4065 int fd = GPOINTER_TO_UINT(handle);
4067 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
4068 (gpointer *)&file_handle);
4070 g_warning ("%s: error looking up file handle %p", __func__,
4072 SetLastError (ERROR_INVALID_HANDLE);
4076 if (!(file_handle->fileaccess & GENERIC_READ) &&
4077 !(file_handle->fileaccess & GENERIC_WRITE) &&
4078 !(file_handle->fileaccess & GENERIC_ALL)) {
4080 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
4082 SetLastError (ERROR_ACCESS_DENIED);
4086 #ifdef HAVE_LARGE_FILE_SUPPORT
4087 offset = ((gint64)offset_high << 32) | offset_low;
4088 length = ((gint64)length_high << 32) | length_low;
4091 g_message ("%s: Unlocking handle %p, offset %lld, length %lld",
4092 __func__, handle, offset, length);
4095 offset = offset_low;
4096 length = length_low;
4099 g_message ("%s: Unlocking handle %p, offset %ld, length %ld", __func__,
4100 handle, offset, length);
4104 return(_wapi_unlock_file_region (fd, offset, length));