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 if (S_ISDIR (stat_src.st_mode)) {
1899 SetLastError (ERROR_NOT_SAME_DEVICE);
1902 /* Try a copy to the new location, and delete the source */
1903 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1904 /* CopyFile will set the error */
1908 return(DeleteFile (name));
1919 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1923 int buf_size = st_src->st_blksize;
1925 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1926 buf = (char *) malloc (buf_size);
1929 remain = read (src_fd, buf, buf_size);
1931 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1935 _wapi_set_last_error_from_errno ();
1945 while (remain > 0) {
1946 if ((n = write (dest_fd, wbuf, remain)) < 0) {
1947 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1951 _wapi_set_last_error_from_errno ();
1953 g_message ("%s: write failed.", __func__);
1970 * @name: a pointer to a NULL-terminated unicode string, that names
1971 * the file to be copied.
1972 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1973 * new name for the file.
1974 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1976 * Copies file @name to @dest_name
1978 * Return value: %TRUE on success, %FALSE otherwise.
1980 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1981 gboolean fail_if_exists)
1983 gchar *utf8_src, *utf8_dest;
1984 int src_fd, dest_fd;
1986 gboolean ret = TRUE;
1990 g_message("%s: name is NULL", __func__);
1993 SetLastError (ERROR_INVALID_NAME);
1997 utf8_src = mono_unicode_to_external (name);
1998 if (utf8_src == NULL) {
2000 g_message ("%s: unicode conversion of source returned NULL",
2004 SetLastError (ERROR_INVALID_PARAMETER);
2008 if(dest_name==NULL) {
2010 g_message("%s: name is NULL", __func__);
2014 SetLastError (ERROR_INVALID_NAME);
2018 utf8_dest = mono_unicode_to_external (dest_name);
2019 if (utf8_dest == NULL) {
2021 g_message ("%s: unicode conversion of dest returned NULL",
2025 SetLastError (ERROR_INVALID_PARAMETER);
2032 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2034 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2042 if (fstat (src_fd, &st) < 0) {
2043 _wapi_set_last_error_from_errno ();
2052 if (fail_if_exists) {
2053 dest_fd = open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL,
2056 dest_fd = open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2058 /* O_TRUNC might cause a fail if the file
2061 dest_fd = open (utf8_dest, O_WRONLY | O_CREAT,
2064 /* Apparently this error is set if we
2065 * overwrite the dest file
2067 SetLastError (ERROR_ALREADY_EXISTS);
2071 _wapi_set_last_error_from_errno ();
2080 if (!write_file (src_fd, dest_fd, &st, TRUE))
2092 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2098 g_message ("%s: %s is NULL", __func__, arg_name);
2100 SetLastError (ERROR_INVALID_NAME);
2104 utf8_ret = mono_unicode_to_external (arg);
2105 if (utf8_ret == NULL) {
2107 g_message ("%s: unicode conversion of %s returned NULL",
2108 __func__, arg_name);
2110 SetLastError (ERROR_INVALID_PARAMETER);
2118 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2119 const gunichar2 *backupFileName, guint32 replaceFlags,
2120 gpointer exclude, gpointer reserved)
2122 int result, errno_copy, backup_fd = -1,replaced_fd = -1;
2123 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2124 struct stat stBackup;
2125 gboolean ret = FALSE;
2127 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2129 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2130 goto replace_cleanup;
2131 if (backupFileName != NULL) {
2132 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2133 goto replace_cleanup;
2136 if (utf8_backupFileName) {
2137 // Open the backup file for read so we can restore the file if an error occurs.
2138 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2139 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2142 goto replace_cleanup;
2145 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2148 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2149 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2150 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2151 replaced_fd = open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2153 if (replaced_fd == -1) {
2154 replaced_fd = open (utf8_backupFileName, O_WRONLY | O_CREAT,
2157 if (replaced_fd == -1)
2158 goto replace_cleanup;
2160 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2163 goto replace_cleanup;
2169 g_free (utf8_replacedFileName);
2170 g_free (utf8_replacementFileName);
2171 g_free (utf8_backupFileName);
2172 if (backup_fd != -1)
2174 if (replaced_fd != -1)
2175 close (replaced_fd);
2179 static gpointer stdhandle_create (int fd, const gchar *name)
2181 struct _WapiHandle_file file_handle = {0};
2186 g_message("%s: creating standard handle type %s, fd %d", __func__,
2190 /* Check if fd is valid */
2192 flags=fcntl(fd, F_GETFL);
2193 } while (flags == -1 && errno == EINTR);
2196 /* Invalid fd. Not really much point checking for EBADF
2200 g_message("%s: fcntl error on fd %d: %s", __func__, fd,
2204 _wapi_set_last_error_from_errno ();
2205 return(INVALID_HANDLE_VALUE);
2208 file_handle.filename = g_strdup(name);
2209 /* some default security attributes might be needed */
2210 file_handle.security_attributes=0;
2211 file_handle.fileaccess=convert_from_flags(flags);
2213 /* Apparently input handles can't be written to. (I don't
2214 * know if output or error handles can't be read from.)
2217 file_handle.fileaccess &= ~GENERIC_WRITE;
2220 file_handle.sharemode=0;
2221 file_handle.attrs=0;
2223 handle = _wapi_handle_new_fd (WAPI_HANDLE_CONSOLE, fd, &file_handle);
2224 if (handle == _WAPI_HANDLE_INVALID) {
2225 g_warning ("%s: error creating file handle", __func__);
2226 SetLastError (ERROR_GEN_FAILURE);
2227 return(INVALID_HANDLE_VALUE);
2231 g_message("%s: returning handle %p", __func__, handle);
2239 * @stdhandle: specifies the file descriptor
2241 * Returns a handle for stdin, stdout, or stderr. Always returns the
2242 * same handle for the same @stdhandle.
2244 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2247 static mono_mutex_t stdhandle_mutex = MONO_MUTEX_INITIALIZER;
2249 gpointer GetStdHandle(WapiStdHandle stdhandle)
2251 struct _WapiHandle_file *file_handle;
2258 case STD_INPUT_HANDLE:
2263 case STD_OUTPUT_HANDLE:
2268 case STD_ERROR_HANDLE:
2275 g_message("%s: unknown standard handle type", __func__);
2278 SetLastError (ERROR_INVALID_PARAMETER);
2279 return(INVALID_HANDLE_VALUE);
2282 handle = GINT_TO_POINTER (fd);
2284 pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2285 (void *)&stdhandle_mutex);
2286 thr_ret = mono_mutex_lock (&stdhandle_mutex);
2287 g_assert (thr_ret == 0);
2289 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2290 (gpointer *)&file_handle);
2292 /* Need to create this console handle */
2293 handle = stdhandle_create (fd, name);
2295 if (handle == INVALID_HANDLE_VALUE) {
2296 SetLastError (ERROR_NO_MORE_FILES);
2300 /* Add a reference to this handle */
2301 _wapi_handle_ref (handle);
2305 thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2306 g_assert (thr_ret == 0);
2307 pthread_cleanup_pop (0);
2314 * @handle: The file handle to read from. The handle must have
2315 * %GENERIC_READ access.
2316 * @buffer: The buffer to store read data in
2317 * @numbytes: The maximum number of bytes to read
2318 * @bytesread: The actual number of bytes read is stored here. This
2319 * value can be zero if the handle is positioned at the end of the
2321 * @overlapped: points to a required %WapiOverlapped structure if
2322 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2325 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2326 * function reads up to @numbytes bytes from the file from the current
2327 * file position, and stores them in @buffer. If there are not enough
2328 * bytes left in the file, just the amount available will be read.
2329 * The actual number of bytes read is stored in @bytesread.
2331 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2332 * file position is ignored and the read position is taken from data
2333 * in the @overlapped structure.
2335 * Return value: %TRUE if the read succeeds (even if no bytes were
2336 * read due to an attempt to read past the end of the file), %FALSE on
2339 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2340 guint32 *bytesread, WapiOverlapped *overlapped)
2342 WapiHandleType type;
2344 type = _wapi_handle_type (handle);
2346 if(io_ops[type].readfile==NULL) {
2347 SetLastError (ERROR_INVALID_HANDLE);
2351 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2357 * @handle: The file handle to write to. The handle must have
2358 * %GENERIC_WRITE access.
2359 * @buffer: The buffer to read data from.
2360 * @numbytes: The maximum number of bytes to write.
2361 * @byteswritten: The actual number of bytes written is stored here.
2362 * If the handle is positioned at the file end, the length of the file
2363 * is extended. This parameter may be %NULL.
2364 * @overlapped: points to a required %WapiOverlapped structure if
2365 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2368 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2369 * function writes up to @numbytes bytes from @buffer to the file at
2370 * the current file position. If @handle is positioned at the end of
2371 * the file, the file is extended. The actual number of bytes written
2372 * is stored in @byteswritten.
2374 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2375 * file position is ignored and the write position is taken from data
2376 * in the @overlapped structure.
2378 * Return value: %TRUE if the write succeeds, %FALSE on error.
2380 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2381 guint32 *byteswritten, WapiOverlapped *overlapped)
2383 WapiHandleType type;
2385 type = _wapi_handle_type (handle);
2387 if(io_ops[type].writefile==NULL) {
2388 SetLastError (ERROR_INVALID_HANDLE);
2392 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2398 * @handle: Handle to open file. The handle must have
2399 * %GENERIC_WRITE access.
2401 * Flushes buffers of the file and causes all unwritten data to
2404 * Return value: %TRUE on success, %FALSE otherwise.
2406 gboolean FlushFileBuffers(gpointer handle)
2408 WapiHandleType type;
2410 type = _wapi_handle_type (handle);
2412 if(io_ops[type].flushfile==NULL) {
2413 SetLastError (ERROR_INVALID_HANDLE);
2417 return(io_ops[type].flushfile (handle));
2422 * @handle: The file handle to set. The handle must have
2423 * %GENERIC_WRITE access.
2425 * Moves the end-of-file position to the current position of the file
2426 * pointer. This function is used to truncate or extend a file.
2428 * Return value: %TRUE on success, %FALSE otherwise.
2430 gboolean SetEndOfFile(gpointer handle)
2432 WapiHandleType type;
2434 type = _wapi_handle_type (handle);
2436 if (io_ops[type].setendoffile == NULL) {
2437 SetLastError (ERROR_INVALID_HANDLE);
2441 return(io_ops[type].setendoffile (handle));
2446 * @handle: The file handle to set. The handle must have
2447 * %GENERIC_READ or %GENERIC_WRITE access.
2448 * @movedistance: Low 32 bits of a signed value that specifies the
2449 * number of bytes to move the file pointer.
2450 * @highmovedistance: Pointer to the high 32 bits of a signed value
2451 * that specifies the number of bytes to move the file pointer, or
2453 * @method: The starting point for the file pointer move.
2455 * Sets the file pointer of an open file.
2457 * The distance to move the file pointer is calculated from
2458 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2459 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2460 * is the low 32 bits and @highmovedistance a pointer to the high 32
2461 * bits of a 64 bit signed value. A positive distance moves the file
2462 * pointer forward from the position specified by @method; a negative
2463 * distance moves the file pointer backward.
2465 * If the library is compiled without large file support,
2466 * @highmovedistance is ignored and its value is set to zero on a
2467 * successful return.
2469 * Return value: On success, the low 32 bits of the new file pointer.
2470 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2471 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2473 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2474 gint32 *highmovedistance, WapiSeekMethod method)
2476 WapiHandleType type;
2478 type = _wapi_handle_type (handle);
2480 if (io_ops[type].seek == NULL) {
2481 SetLastError (ERROR_INVALID_HANDLE);
2482 return(INVALID_SET_FILE_POINTER);
2485 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2491 * @handle: The file handle to test.
2493 * Finds the type of file @handle.
2495 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2496 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2497 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2498 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2500 WapiFileType GetFileType(gpointer handle)
2502 WapiHandleType type;
2504 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2505 SetLastError (ERROR_INVALID_HANDLE);
2506 return(FILE_TYPE_UNKNOWN);
2509 type = _wapi_handle_type (handle);
2511 if (io_ops[type].getfiletype == NULL) {
2512 SetLastError (ERROR_INVALID_HANDLE);
2513 return(FILE_TYPE_UNKNOWN);
2516 return(io_ops[type].getfiletype ());
2521 * @handle: The file handle to query. The handle must have
2522 * %GENERIC_READ or %GENERIC_WRITE access.
2523 * @highsize: If non-%NULL, the high 32 bits of the file size are
2526 * Retrieves the size of the file @handle.
2528 * If the library is compiled without large file support, @highsize
2529 * has its value set to zero on a successful return.
2531 * Return value: On success, the low 32 bits of the file size. If
2532 * @highsize is non-%NULL then the high 32 bits of the file size are
2533 * stored here. On failure %INVALID_FILE_SIZE is returned.
2535 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2537 WapiHandleType type;
2539 type = _wapi_handle_type (handle);
2541 if (io_ops[type].getfilesize == NULL) {
2542 SetLastError (ERROR_INVALID_HANDLE);
2543 return(INVALID_FILE_SIZE);
2546 return(io_ops[type].getfilesize (handle, highsize));
2551 * @handle: The file handle to query. The handle must have
2552 * %GENERIC_READ access.
2553 * @create_time: Points to a %WapiFileTime structure to receive the
2554 * number of ticks since the epoch that file was created. May be
2556 * @last_access: Points to a %WapiFileTime structure to receive the
2557 * number of ticks since the epoch when file was last accessed. May be
2559 * @last_write: Points to a %WapiFileTime structure to receive the
2560 * number of ticks since the epoch when file was last written to. May
2563 * Finds the number of ticks since the epoch that the file referenced
2564 * by @handle was created, last accessed and last modified. A tick is
2565 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2568 * Create time isn't recorded on POSIX file systems or reported by
2569 * stat(2), so that time is guessed by returning the oldest of the
2572 * Return value: %TRUE on success, %FALSE otherwise.
2574 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2575 WapiFileTime *last_access, WapiFileTime *last_write)
2577 WapiHandleType type;
2579 type = _wapi_handle_type (handle);
2581 if (io_ops[type].getfiletime == NULL) {
2582 SetLastError (ERROR_INVALID_HANDLE);
2586 return(io_ops[type].getfiletime (handle, create_time, last_access,
2592 * @handle: The file handle to set. The handle must have
2593 * %GENERIC_WRITE access.
2594 * @create_time: Points to a %WapiFileTime structure that contains the
2595 * number of ticks since the epoch that the file was created. May be
2597 * @last_access: Points to a %WapiFileTime structure that contains the
2598 * number of ticks since the epoch when the file was last accessed.
2600 * @last_write: Points to a %WapiFileTime structure that contains the
2601 * number of ticks since the epoch when the file was last written to.
2604 * Sets the number of ticks since the epoch that the file referenced
2605 * by @handle was created, last accessed or last modified. A tick is
2606 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2609 * Create time isn't recorded on POSIX file systems, and is ignored.
2611 * Return value: %TRUE on success, %FALSE otherwise.
2613 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2614 const WapiFileTime *last_access,
2615 const WapiFileTime *last_write)
2617 WapiHandleType type;
2619 type = _wapi_handle_type (handle);
2621 if (io_ops[type].setfiletime == NULL) {
2622 SetLastError (ERROR_INVALID_HANDLE);
2626 return(io_ops[type].setfiletime (handle, create_time, last_access,
2630 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2631 * January 1 1601 GMT
2634 #define TICKS_PER_MILLISECOND 10000L
2635 #define TICKS_PER_SECOND 10000000L
2636 #define TICKS_PER_MINUTE 600000000L
2637 #define TICKS_PER_HOUR 36000000000LL
2638 #define TICKS_PER_DAY 864000000000LL
2640 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2642 static const guint16 mon_yday[2][13]={
2643 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2644 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2648 * FileTimeToSystemTime:
2649 * @file_time: Points to a %WapiFileTime structure that contains the
2650 * number of ticks to convert.
2651 * @system_time: Points to a %WapiSystemTime structure to receive the
2654 * Converts a tick count into broken-out time values.
2656 * Return value: %TRUE on success, %FALSE otherwise.
2658 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2659 WapiSystemTime *system_time)
2661 gint64 file_ticks, totaldays, rem, y;
2664 if(system_time==NULL) {
2666 g_message("%s: system_time NULL", __func__);
2669 SetLastError (ERROR_INVALID_PARAMETER);
2673 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2674 file_time->dwLowDateTime;
2676 /* Really compares if file_ticks>=0x8000000000000000
2677 * (LLONG_MAX+1) but we're working with a signed value for the
2678 * year and day calculation to work later
2682 g_message("%s: file_time too big", __func__);
2685 SetLastError (ERROR_INVALID_PARAMETER);
2689 totaldays=(file_ticks / TICKS_PER_DAY);
2690 rem = file_ticks % TICKS_PER_DAY;
2692 g_message("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2695 system_time->wHour=rem/TICKS_PER_HOUR;
2696 rem %= TICKS_PER_HOUR;
2698 g_message("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2701 system_time->wMinute = rem / TICKS_PER_MINUTE;
2702 rem %= TICKS_PER_MINUTE;
2704 g_message("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2708 system_time->wSecond = rem / TICKS_PER_SECOND;
2709 rem %= TICKS_PER_SECOND;
2711 g_message("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2715 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2717 g_message("%s: Milliseconds: %d", __func__,
2718 system_time->wMilliseconds);
2721 /* January 1, 1601 was a Monday, according to Emacs calendar */
2722 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2724 g_message("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2727 /* This algorithm to find year and month given days from epoch
2732 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2733 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2735 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2736 /* Guess a corrected year, assuming 365 days per year */
2737 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2739 g_message("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2742 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2743 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2746 /* Adjust days and y to match the guessed year. */
2747 totaldays -= ((yg - y) * 365
2748 + LEAPS_THRU_END_OF (yg - 1)
2749 - LEAPS_THRU_END_OF (y - 1));
2751 g_message("%s: totaldays: %lld", __func__, totaldays);
2755 g_message("%s: y: %lld", __func__, y);
2759 system_time->wYear = y;
2761 g_message("%s: Year: %d", __func__, system_time->wYear);
2764 ip = mon_yday[isleap(y)];
2766 for(y=11; totaldays < ip[y]; --y) {
2771 g_message("%s: totaldays: %lld", __func__, totaldays);
2774 system_time->wMonth = y + 1;
2776 g_message("%s: Month: %d", __func__, system_time->wMonth);
2779 system_time->wDay = totaldays + 1;
2781 g_message("%s: Day: %d", __func__, system_time->wDay);
2787 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2789 struct _WapiHandle_find find_handle = {0};
2791 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2794 if (pattern == NULL) {
2796 g_message ("%s: pattern is NULL", __func__);
2799 SetLastError (ERROR_PATH_NOT_FOUND);
2800 return(INVALID_HANDLE_VALUE);
2803 utf8_pattern = mono_unicode_to_external (pattern);
2804 if (utf8_pattern == NULL) {
2806 g_message ("%s: unicode conversion returned NULL", __func__);
2809 SetLastError (ERROR_INVALID_NAME);
2810 return(INVALID_HANDLE_VALUE);
2814 g_message ("%s: looking for [%s]", __func__, utf8_pattern);
2817 /* Figure out which bit of the pattern is the directory */
2818 dir_part = _wapi_dirname (utf8_pattern);
2819 entry_part = _wapi_basename (utf8_pattern);
2822 /* Don't do this check for now, it breaks if directories
2823 * really do have metachars in their names (see bug 58116).
2824 * FIXME: Figure out a better solution to keep some checks...
2826 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2827 SetLastError (ERROR_INVALID_NAME);
2829 g_free (entry_part);
2830 g_free (utf8_pattern);
2831 return(INVALID_HANDLE_VALUE);
2835 /* The pattern can specify a directory or a set of files.
2837 * The pattern can have wildcard characters ? and *, but only
2838 * in the section after the last directory delimiter. (Return
2839 * ERROR_INVALID_NAME if there are wildcards in earlier path
2840 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2841 * means "match one character", "??" seems to mean "match one
2842 * or two characters", "???" seems to mean "match one, two or
2843 * three characters", etc. Windows will also try and match
2844 * the mangled "short name" of files, so 8 character patterns
2845 * with wildcards will show some surprising results.
2847 * All the written documentation I can find says that '?'
2848 * should only match one character, and doesn't mention '??',
2849 * '???' etc. I'm going to assume that the strict behaviour
2850 * (ie '???' means three and only three characters) is the
2851 * correct one, because that lets me use fnmatch(3) rather
2852 * than mess around with regexes.
2855 find_handle.namelist = NULL;
2856 result = _wapi_io_scandir (dir_part, entry_part,
2857 &find_handle.namelist);
2860 /* No files, which windows seems to call
2863 SetLastError (ERROR_FILE_NOT_FOUND);
2864 g_free (utf8_pattern);
2865 g_free (entry_part);
2867 return (INVALID_HANDLE_VALUE);
2872 gint errnum = errno;
2874 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2876 g_message ("%s: scandir error: %s", __func__,
2877 g_strerror (errnum));
2879 g_free (utf8_pattern);
2880 g_free (entry_part);
2882 return (INVALID_HANDLE_VALUE);
2885 g_free (utf8_pattern);
2886 g_free (entry_part);
2889 g_message ("%s: Got %d matches", __func__, result);
2892 find_handle.dir_part = dir_part;
2893 find_handle.num = result;
2894 find_handle.count = 0;
2896 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2897 if (handle == _WAPI_HANDLE_INVALID) {
2898 g_warning ("%s: error creating find handle", __func__);
2900 g_free (entry_part);
2901 g_free (utf8_pattern);
2902 SetLastError (ERROR_GEN_FAILURE);
2904 return(INVALID_HANDLE_VALUE);
2907 if (handle != INVALID_HANDLE_VALUE &&
2908 !FindNextFile (handle, find_data)) {
2910 SetLastError (ERROR_NO_MORE_FILES);
2911 handle = INVALID_HANDLE_VALUE;
2917 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2919 struct _WapiHandle_find *find_handle;
2921 struct stat buf, linkbuf;
2924 gchar *utf8_filename, *utf8_basename;
2925 gunichar2 *utf16_basename;
2929 gboolean ret = FALSE;
2931 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2932 (gpointer *)&find_handle);
2934 g_warning ("%s: error looking up find handle %p", __func__,
2936 SetLastError (ERROR_INVALID_HANDLE);
2940 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2942 thr_ret = _wapi_handle_lock_handle (handle);
2943 g_assert (thr_ret == 0);
2946 if (find_handle->count >= find_handle->num) {
2947 SetLastError (ERROR_NO_MORE_FILES);
2951 /* stat next match */
2953 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2955 result = _wapi_stat (filename, &buf);
2956 if (result == -1 && errno == ENOENT) {
2957 /* Might be a dangling symlink */
2958 result = _wapi_lstat (filename, &buf);
2963 g_message ("%s: stat failed: %s", __func__, filename);
2970 result = _wapi_lstat (filename, &linkbuf);
2973 g_message ("%s: lstat failed: %s", __func__, filename);
2980 utf8_filename = mono_utf8_from_external (filename);
2981 if (utf8_filename == NULL) {
2982 /* We couldn't turn this filename into utf8 (eg the
2983 * encoding of the name wasn't convertible), so just
2986 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2994 g_message ("%s: Found [%s]", __func__, utf8_filename);
2997 /* fill data block */
2999 if (buf.st_mtime < buf.st_ctime)
3000 create_time = buf.st_mtime;
3002 create_time = buf.st_ctime;
3004 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
3006 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
3007 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
3008 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
3010 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3011 find_data->nFileSizeHigh = 0;
3012 find_data->nFileSizeLow = 0;
3014 find_data->nFileSizeHigh = buf.st_size >> 32;
3015 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3018 find_data->dwReserved0 = 0;
3019 find_data->dwReserved1 = 0;
3021 utf8_basename = _wapi_basename (utf8_filename);
3022 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
3024 if(utf16_basename==NULL) {
3025 g_free (utf8_basename);
3026 g_free (utf8_filename);
3031 /* utf16 is 2 * utf8 */
3034 memset (find_data->cFileName, '\0', (MAX_PATH*2));
3036 /* Truncating a utf16 string like this might leave the last
3039 memcpy (find_data->cFileName, utf16_basename,
3040 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3042 find_data->cAlternateFileName [0] = 0; /* not used */
3044 g_free (utf8_basename);
3045 g_free (utf8_filename);
3046 g_free (utf16_basename);
3049 thr_ret = _wapi_handle_unlock_handle (handle);
3050 g_assert (thr_ret == 0);
3051 pthread_cleanup_pop (0);
3058 * @wapi_handle: the find handle to close.
3060 * Closes find handle @wapi_handle
3062 * Return value: %TRUE on success, %FALSE otherwise.
3064 gboolean FindClose (gpointer handle)
3066 struct _WapiHandle_find *find_handle;
3070 if (handle == NULL) {
3071 SetLastError (ERROR_INVALID_HANDLE);
3075 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
3076 (gpointer *)&find_handle);
3078 g_warning ("%s: error looking up find handle %p", __func__,
3080 SetLastError (ERROR_INVALID_HANDLE);
3084 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
3086 thr_ret = _wapi_handle_lock_handle (handle);
3087 g_assert (thr_ret == 0);
3089 g_strfreev (find_handle->namelist);
3090 g_free (find_handle->dir_part);
3092 thr_ret = _wapi_handle_unlock_handle (handle);
3093 g_assert (thr_ret == 0);
3094 pthread_cleanup_pop (0);
3096 _wapi_handle_unref (handle);
3103 * @name: a pointer to a NULL-terminated unicode string, that names
3104 * the directory to be created.
3105 * @security: ignored for now
3107 * Creates directory @name
3109 * Return value: %TRUE on success, %FALSE otherwise.
3111 gboolean CreateDirectory (const gunichar2 *name,
3112 WapiSecurityAttributes *security)
3119 g_message("%s: name is NULL", __func__);
3122 SetLastError (ERROR_INVALID_NAME);
3126 utf8_name = mono_unicode_to_external (name);
3127 if (utf8_name == NULL) {
3129 g_message ("%s: unicode conversion returned NULL", __func__);
3132 SetLastError (ERROR_INVALID_NAME);
3136 result = _wapi_mkdir (utf8_name, 0777);
3143 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3150 * @name: a pointer to a NULL-terminated unicode string, that names
3151 * the directory to be removed.
3153 * Removes directory @name
3155 * Return value: %TRUE on success, %FALSE otherwise.
3157 gboolean RemoveDirectory (const gunichar2 *name)
3164 g_message("%s: name is NULL", __func__);
3167 SetLastError (ERROR_INVALID_NAME);
3171 utf8_name = mono_unicode_to_external (name);
3172 if (utf8_name == NULL) {
3174 g_message ("%s: unicode conversion returned NULL", __func__);
3177 SetLastError (ERROR_INVALID_NAME);
3181 result = _wapi_rmdir (utf8_name);
3183 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3194 * GetFileAttributes:
3195 * @name: a pointer to a NULL-terminated unicode filename.
3197 * Gets the attributes for @name;
3199 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3201 guint32 GetFileAttributes (const gunichar2 *name)
3204 struct stat buf, linkbuf;
3210 g_message("%s: name is NULL", __func__);
3213 SetLastError (ERROR_INVALID_NAME);
3217 utf8_name = mono_unicode_to_external (name);
3218 if (utf8_name == NULL) {
3220 g_message ("%s: unicode conversion returned NULL", __func__);
3223 SetLastError (ERROR_INVALID_PARAMETER);
3224 return (INVALID_FILE_ATTRIBUTES);
3227 result = _wapi_stat (utf8_name, &buf);
3228 if (result == -1 && errno == ENOENT) {
3229 /* Might be a dangling symlink... */
3230 result = _wapi_lstat (utf8_name, &buf);
3234 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3236 return (INVALID_FILE_ATTRIBUTES);
3239 result = _wapi_lstat (utf8_name, &linkbuf);
3241 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3243 return (INVALID_FILE_ATTRIBUTES);
3246 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3254 * GetFileAttributesEx:
3255 * @name: a pointer to a NULL-terminated unicode filename.
3256 * @level: must be GetFileExInfoStandard
3257 * @info: pointer to a WapiFileAttributesData structure
3259 * Gets attributes, size and filetimes for @name;
3261 * Return value: %TRUE on success, %FALSE on failure
3263 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3266 WapiFileAttributesData *data;
3268 struct stat buf, linkbuf;
3272 if (level != GetFileExInfoStandard) {
3274 g_message ("%s: info level %d not supported.", __func__,
3278 SetLastError (ERROR_INVALID_PARAMETER);
3284 g_message("%s: name is NULL", __func__);
3287 SetLastError (ERROR_INVALID_NAME);
3291 utf8_name = mono_unicode_to_external (name);
3292 if (utf8_name == NULL) {
3294 g_message ("%s: unicode conversion returned NULL", __func__);
3297 SetLastError (ERROR_INVALID_PARAMETER);
3301 result = _wapi_stat (utf8_name, &buf);
3302 if (result == -1 && errno == ENOENT) {
3303 /* Might be a dangling symlink... */
3304 result = _wapi_lstat (utf8_name, &buf);
3308 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3313 result = _wapi_lstat (utf8_name, &linkbuf);
3315 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3320 /* fill data block */
3322 data = (WapiFileAttributesData *)info;
3324 if (buf.st_mtime < buf.st_ctime)
3325 create_time = buf.st_mtime;
3327 create_time = buf.st_ctime;
3329 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3335 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3336 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3337 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3339 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3340 data->nFileSizeHigh = 0;
3341 data->nFileSizeLow = 0;
3344 data->nFileSizeHigh = buf.st_size >> 32;
3345 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3353 * @name: name of file
3354 * @attrs: attributes to set
3356 * Changes the attributes on a named file.
3358 * Return value: %TRUE on success, %FALSE on failure.
3360 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3362 /* FIXME: think of something clever to do on unix */
3368 * Currently we only handle one *internal* case, with a value that is
3369 * not standard: 0x80000000, which means `set executable bit'
3374 g_message("%s: name is NULL", __func__);
3377 SetLastError (ERROR_INVALID_NAME);
3381 utf8_name = mono_unicode_to_external (name);
3382 if (utf8_name == NULL) {
3384 g_message ("%s: unicode conversion returned NULL", __func__);
3387 SetLastError (ERROR_INVALID_NAME);
3391 result = _wapi_stat (utf8_name, &buf);
3393 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3398 /* Contrary to the documentation, ms allows NORMAL to be
3399 * specified along with other attributes, so dont bother to
3400 * catch that case here.
3402 if (attrs & FILE_ATTRIBUTE_READONLY) {
3403 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3405 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3408 /* Ignore the other attributes for now */
3410 if (attrs & 0x80000000){
3411 mode_t exec_mask = 0;
3413 if ((buf.st_mode & S_IRUSR) != 0)
3414 exec_mask |= S_IXUSR;
3416 if ((buf.st_mode & S_IRGRP) != 0)
3417 exec_mask |= S_IXGRP;
3419 if ((buf.st_mode & S_IROTH) != 0)
3420 exec_mask |= S_IXOTH;
3422 result = chmod (utf8_name, buf.st_mode | exec_mask);
3424 /* Don't bother to reset executable (might need to change this
3434 * GetCurrentDirectory
3435 * @length: size of the buffer
3436 * @buffer: pointer to buffer that recieves path
3438 * Retrieves the current directory for the current process.
3440 * Return value: number of characters in buffer on success, zero on failure
3442 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3444 gunichar2 *utf16_path;
3448 if (getcwd ((char*)buffer, length) == NULL) {
3449 if (errno == ERANGE) { /*buffer length is not big enough */
3450 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*/
3453 utf16_path = mono_unicode_from_external (path, &bytes);
3454 g_free (utf16_path);
3458 _wapi_set_last_error_from_errno ();
3462 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3463 count = (bytes/2)+1;
3464 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3466 /* Add the terminator */
3467 memset (buffer, '\0', bytes+2);
3468 memcpy (buffer, utf16_path, bytes);
3470 g_free (utf16_path);
3476 * SetCurrentDirectory
3477 * @path: path to new directory
3479 * Changes the directory path for the current process.
3481 * Return value: %TRUE on success, %FALSE on failure.
3483 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3489 SetLastError (ERROR_INVALID_PARAMETER);
3493 utf8_path = mono_unicode_to_external (path);
3494 if (_wapi_chdir (utf8_path) != 0) {
3495 _wapi_set_last_error_from_errno ();
3505 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3506 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3508 struct _WapiHandle_file pipe_read_handle = {0};
3509 struct _WapiHandle_file pipe_write_handle = {0};
3510 gpointer read_handle;
3511 gpointer write_handle;
3515 mono_once (&io_ops_once, io_ops_init);
3518 g_message ("%s: Creating pipe", __func__);
3524 g_message ("%s: Error creating pipe: %s", __func__,
3528 _wapi_set_last_error_from_errno ();
3532 if (filedes[0] >= _wapi_fd_reserve ||
3533 filedes[1] >= _wapi_fd_reserve) {
3535 g_message ("%s: File descriptor is too big", __func__);
3538 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3546 /* filedes[0] is open for reading, filedes[1] for writing */
3548 pipe_read_handle.fileaccess = GENERIC_READ;
3549 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3551 if (read_handle == _WAPI_HANDLE_INVALID) {
3552 g_warning ("%s: error creating pipe read handle", __func__);
3555 SetLastError (ERROR_GEN_FAILURE);
3560 pipe_write_handle.fileaccess = GENERIC_WRITE;
3561 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3562 &pipe_write_handle);
3563 if (write_handle == _WAPI_HANDLE_INVALID) {
3564 g_warning ("%s: error creating pipe write handle", __func__);
3565 _wapi_handle_unref (read_handle);
3569 SetLastError (ERROR_GEN_FAILURE);
3574 *readpipe = read_handle;
3575 *writepipe = write_handle;
3578 g_message ("%s: Returning pipe: read handle %p, write handle %p",
3579 __func__, read_handle, write_handle);
3585 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3587 gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3588 gunichar2 *tmpdir16=NULL;
3593 if(tmpdir[strlen (tmpdir)]!='/') {
3595 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3598 tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3599 if(tmpdir16==NULL) {
3607 g_message ("%s: Size %d smaller than needed (%ld)",
3608 __func__, len, dirlen+1);
3613 /* Add the terminator */
3614 memset (buf, '\0', bytes+2);
3615 memcpy (buf, tmpdir16, bytes);
3621 if(tmpdir16!=NULL) {
3630 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3633 gunichar2 *ptr, *dir;
3634 glong length, total = 0;
3638 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3643 /* Sigh, mntent and friends don't work well.
3644 * It stops on the first line that doesn't begin with a '/'.
3645 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3646 fp = fopen ("/etc/mtab", "rt");
3648 fp = fopen ("/etc/mnttab", "rt");
3654 while (fgets (buffer, 512, fp) != NULL) {
3658 splitted = g_strsplit (buffer, " ", 0);
3659 if (!*splitted || !*(splitted + 1)) {
3660 g_strfreev (splitted);
3664 dir = g_utf8_to_utf16 (*(splitted + 1), -1, &length, NULL, NULL);
3665 g_strfreev (splitted);
3666 if (total + length + 1 > len) {
3668 return len * 2; /* guess */
3671 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3673 total += length + 1;
3678 /* Commented out, does not work with my mtab!!! - Gonz */
3679 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3683 gunichar2 *ptr, *dir;
3684 glong len, total = 0;
3687 fp = setmntent ("/etc/mtab", "rt");
3689 fp = setmntent ("/etc/mnttab", "rt");
3695 while ((mnt = getmntent (fp)) != NULL) {
3696 g_print ("GOT %s\n", mnt->mnt_dir);
3697 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3698 if (total + len + 1 > len) {
3699 return len * 2; /* guess */
3702 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3713 #if (defined(HAVE_STATVFS) || defined(HAVE_STATFS)) && !defined(PLATFORM_ANDROID)
3714 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3715 WapiULargeInteger *total_number_of_bytes,
3716 WapiULargeInteger *total_number_of_free_bytes)
3719 struct statvfs fsstat;
3720 #elif defined(HAVE_STATFS)
3721 struct statfs fsstat;
3723 gboolean isreadonly;
3724 gchar *utf8_path_name;
3727 if (path_name == NULL) {
3728 utf8_path_name = g_strdup (g_get_current_dir());
3729 if (utf8_path_name == NULL) {
3730 SetLastError (ERROR_DIRECTORY);
3735 utf8_path_name = mono_unicode_to_external (path_name);
3736 if (utf8_path_name == NULL) {
3738 g_message("%s: unicode conversion returned NULL", __func__);
3741 SetLastError (ERROR_INVALID_NAME);
3748 ret = statvfs (utf8_path_name, &fsstat);
3749 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
3750 #elif defined(HAVE_STATFS)
3751 ret = statfs (utf8_path_name, &fsstat);
3752 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
3754 } while(ret == -1 && errno == EINTR);
3756 g_free(utf8_path_name);
3759 _wapi_set_last_error_from_errno ();
3761 g_message ("%s: statvfs failed: %s", __func__, strerror (errno));
3766 /* total number of free bytes for non-root */
3767 if (free_bytes_avail != NULL) {
3769 free_bytes_avail->QuadPart = 0;
3772 free_bytes_avail->QuadPart = fsstat.f_bsize * fsstat.f_bavail;
3776 /* total number of bytes available for non-root */
3777 if (total_number_of_bytes != NULL) {
3778 total_number_of_bytes->QuadPart = fsstat.f_bsize * fsstat.f_blocks;
3781 /* total number of bytes available for root */
3782 if (total_number_of_free_bytes != NULL) {
3784 total_number_of_free_bytes->QuadPart = 0;
3787 total_number_of_free_bytes->QuadPart = fsstat.f_bsize * fsstat.f_bfree;
3794 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3795 WapiULargeInteger *total_number_of_bytes,
3796 WapiULargeInteger *total_number_of_free_bytes)
3798 if (free_bytes_avail != NULL) {
3799 free_bytes_avail->QuadPart = (guint64) -1;
3802 if (total_number_of_bytes != NULL) {
3803 total_number_of_bytes->QuadPart = (guint64) -1;
3806 if (total_number_of_free_bytes != NULL) {
3807 total_number_of_free_bytes->QuadPart = (guint64) -1;
3816 const gchar* fstype;
3819 static _wapi_drive_type _wapi_drive_types[] = {
3820 { DRIVE_RAMDISK, "ramfs" },
3821 { DRIVE_RAMDISK, "tmpfs" },
3822 { DRIVE_RAMDISK, "proc" },
3823 { DRIVE_RAMDISK, "sysfs" },
3824 { DRIVE_RAMDISK, "debugfs" },
3825 { DRIVE_RAMDISK, "devpts" },
3826 { DRIVE_RAMDISK, "securityfs" },
3827 { DRIVE_CDROM, "iso9660" },
3828 { DRIVE_FIXED, "ext2" },
3829 { DRIVE_FIXED, "ext3" },
3830 { DRIVE_FIXED, "ext4" },
3831 { DRIVE_FIXED, "sysv" },
3832 { DRIVE_FIXED, "reiserfs" },
3833 { DRIVE_FIXED, "ufs" },
3834 { DRIVE_FIXED, "vfat" },
3835 { DRIVE_FIXED, "msdos" },
3836 { DRIVE_FIXED, "udf" },
3837 { DRIVE_FIXED, "hfs" },
3838 { DRIVE_FIXED, "hpfs" },
3839 { DRIVE_FIXED, "qnx4" },
3840 { DRIVE_FIXED, "ntfs" },
3841 { DRIVE_FIXED, "ntfs-3g" },
3842 { DRIVE_REMOTE, "smbfs" },
3843 { DRIVE_REMOTE, "fuse" },
3844 { DRIVE_REMOTE, "nfs" },
3845 { DRIVE_REMOTE, "nfs4" },
3846 { DRIVE_REMOTE, "cifs" },
3847 { DRIVE_REMOTE, "ncpfs" },
3848 { DRIVE_REMOTE, "coda" },
3849 { DRIVE_REMOTE, "afs" },
3850 { DRIVE_UNKNOWN, NULL }
3853 static guint32 _wapi_get_drive_type(const gchar* fstype)
3855 _wapi_drive_type *current;
3857 current = &_wapi_drive_types[0];
3858 while (current->drive_type != DRIVE_UNKNOWN) {
3859 if (strcmp (current->fstype, fstype) == 0)
3865 return current->drive_type;
3868 guint32 GetDriveType(const gunichar2 *root_path_name)
3873 gchar *utf8_root_path_name;
3876 if (root_path_name == NULL) {
3877 utf8_root_path_name = g_strdup (g_get_current_dir());
3878 if (utf8_root_path_name == NULL) {
3879 return(DRIVE_NO_ROOT_DIR);
3883 utf8_root_path_name = mono_unicode_to_external (root_path_name);
3884 if (utf8_root_path_name == NULL) {
3886 g_message("%s: unicode conversion returned NULL", __func__);
3888 return(DRIVE_NO_ROOT_DIR);
3891 /* strip trailing slash for compare below */
3892 if (g_str_has_suffix(utf8_root_path_name, "/")) {
3893 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
3897 fp = fopen ("/etc/mtab", "rt");
3899 fp = fopen ("/etc/mnttab", "rt");
3901 g_free (utf8_root_path_name);
3902 return(DRIVE_UNKNOWN);
3906 drive_type = DRIVE_NO_ROOT_DIR;
3907 while (fgets (buffer, 512, fp) != NULL) {
3908 splitted = g_strsplit (buffer, " ", 0);
3909 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
3910 g_strfreev (splitted);
3914 /* compare given root_path_name with the one from mtab,
3915 if length of utf8_root_path_name is zero it must be the root dir */
3916 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
3917 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
3918 drive_type = _wapi_get_drive_type (*(splitted + 2));
3919 g_strfreev (splitted);
3923 g_strfreev (splitted);
3927 g_free (utf8_root_path_name);
3929 return (drive_type);
3932 static gboolean _wapi_lock_file_region (int fd, off_t offset, off_t length)
3934 struct flock lock_data;
3937 lock_data.l_type = F_WRLCK;
3938 lock_data.l_whence = SEEK_SET;
3939 lock_data.l_start = offset;
3940 lock_data.l_len = length;
3943 ret = fcntl (fd, F_SETLK, &lock_data);
3944 } while(ret == -1 && errno == EINTR);
3947 g_message ("%s: fcntl returns %d", __func__, ret);
3952 * if locks are not available (NFS for example),
3957 || errno == EOPNOTSUPP
3966 SetLastError (ERROR_LOCK_VIOLATION);
3973 static gboolean _wapi_unlock_file_region (int fd, off_t offset, off_t length)
3975 struct flock lock_data;
3978 lock_data.l_type = F_UNLCK;
3979 lock_data.l_whence = SEEK_SET;
3980 lock_data.l_start = offset;
3981 lock_data.l_len = length;
3984 ret = fcntl (fd, F_SETLK, &lock_data);
3985 } while(ret == -1 && errno == EINTR);
3988 g_message ("%s: fcntl returns %d", __func__, ret);
3993 * if locks are not available (NFS for example),
3998 || errno == EOPNOTSUPP
4007 SetLastError (ERROR_LOCK_VIOLATION);
4014 gboolean LockFile (gpointer handle, guint32 offset_low, guint32 offset_high,
4015 guint32 length_low, guint32 length_high)
4017 struct _WapiHandle_file *file_handle;
4019 off_t offset, length;
4020 int fd = GPOINTER_TO_UINT(handle);
4022 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
4023 (gpointer *)&file_handle);
4025 g_warning ("%s: error looking up file handle %p", __func__,
4027 SetLastError (ERROR_INVALID_HANDLE);
4031 if (!(file_handle->fileaccess & GENERIC_READ) &&
4032 !(file_handle->fileaccess & GENERIC_WRITE) &&
4033 !(file_handle->fileaccess & GENERIC_ALL)) {
4035 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
4037 SetLastError (ERROR_ACCESS_DENIED);
4041 #ifdef HAVE_LARGE_FILE_SUPPORT
4042 offset = ((gint64)offset_high << 32) | offset_low;
4043 length = ((gint64)length_high << 32) | length_low;
4046 g_message ("%s: Locking handle %p, offset %lld, length %lld", __func__,
4047 handle, offset, length);
4050 offset = offset_low;
4051 length = length_low;
4054 g_message ("%s: Locking handle %p, offset %ld, length %ld", __func__,
4055 handle, offset, length);
4059 return(_wapi_lock_file_region (fd, offset, length));
4062 gboolean UnlockFile (gpointer handle, guint32 offset_low,
4063 guint32 offset_high, guint32 length_low,
4064 guint32 length_high)
4066 struct _WapiHandle_file *file_handle;
4068 off_t offset, length;
4069 int fd = GPOINTER_TO_UINT(handle);
4071 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
4072 (gpointer *)&file_handle);
4074 g_warning ("%s: error looking up file handle %p", __func__,
4076 SetLastError (ERROR_INVALID_HANDLE);
4080 if (!(file_handle->fileaccess & GENERIC_READ) &&
4081 !(file_handle->fileaccess & GENERIC_WRITE) &&
4082 !(file_handle->fileaccess & GENERIC_ALL)) {
4084 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
4086 SetLastError (ERROR_ACCESS_DENIED);
4090 #ifdef HAVE_LARGE_FILE_SUPPORT
4091 offset = ((gint64)offset_high << 32) | offset_low;
4092 length = ((gint64)length_high << 32) | length_low;
4095 g_message ("%s: Unlocking handle %p, offset %lld, length %lld",
4096 __func__, handle, offset, length);
4099 offset = offset_low;
4100 length = length_low;
4103 g_message ("%s: Unlocking handle %p, offset %ld, length %ld", __func__,
4104 handle, offset, length);
4108 return(_wapi_unlock_file_region (fd, offset, length));