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.
9 * Copyright 2011 Xamarin Inc (http://www.xamarin.com).
19 #ifdef HAVE_SYS_STATVFS_H
20 #include <sys/statvfs.h>
22 #if defined(HAVE_SYS_STATFS_H)
23 #include <sys/statfs.h>
25 #if defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H)
26 #include <sys/param.h>
27 #include <sys/mount.h>
29 #include <sys/types.h>
35 #include <sys/ioctl.h>
37 #include <mono/utils/linux_magic.h>
40 #include <mono/io-layer/wapi.h>
41 #include <mono/io-layer/wapi-private.h>
42 #include <mono/io-layer/handles-private.h>
43 #include <mono/io-layer/io-private.h>
44 #include <mono/io-layer/timefuncs-private.h>
45 #include <mono/io-layer/thread-private.h>
46 #include <mono/io-layer/io-portability.h>
47 #include <mono/utils/strenc.h>
50 #define DEBUG(...) g_message(__VA_ARGS__)
51 #define DEBUG_ENABLED 1
56 static void file_close (gpointer handle, gpointer data);
57 static WapiFileType file_getfiletype(void);
58 static gboolean file_read(gpointer handle, gpointer buffer,
59 guint32 numbytes, guint32 *bytesread,
60 WapiOverlapped *overlapped);
61 static gboolean file_write(gpointer handle, gconstpointer buffer,
62 guint32 numbytes, guint32 *byteswritten,
63 WapiOverlapped *overlapped);
64 static gboolean file_flush(gpointer handle);
65 static guint32 file_seek(gpointer handle, gint32 movedistance,
66 gint32 *highmovedistance, WapiSeekMethod method);
67 static gboolean file_setendoffile(gpointer handle);
68 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
69 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
70 WapiFileTime *last_access,
71 WapiFileTime *last_write);
72 static gboolean file_setfiletime(gpointer handle,
73 const WapiFileTime *create_time,
74 const WapiFileTime *last_access,
75 const WapiFileTime *last_write);
76 static guint32 GetDriveTypeFromPath (const gchar *utf8_root_path_name);
78 /* File handle is only signalled for overlapped IO */
79 struct _WapiHandleOps _wapi_file_ops = {
80 file_close, /* close */
84 NULL, /* special_wait */
88 void _wapi_file_details (gpointer handle_info)
90 struct _WapiHandle_file *file = (struct _WapiHandle_file *)handle_info;
92 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
94 file->fileaccess&GENERIC_READ?'R':'.',
95 file->fileaccess&GENERIC_WRITE?'W':'.',
96 file->fileaccess&GENERIC_EXECUTE?'X':'.',
97 file->sharemode&FILE_SHARE_READ?'R':'.',
98 file->sharemode&FILE_SHARE_WRITE?'W':'.',
99 file->sharemode&FILE_SHARE_DELETE?'D':'.',
103 static void console_close (gpointer handle, gpointer data);
104 static WapiFileType console_getfiletype(void);
105 static gboolean console_read(gpointer handle, gpointer buffer,
106 guint32 numbytes, guint32 *bytesread,
107 WapiOverlapped *overlapped);
108 static gboolean console_write(gpointer handle, gconstpointer buffer,
109 guint32 numbytes, guint32 *byteswritten,
110 WapiOverlapped *overlapped);
112 /* Console is mostly the same as file, except it can block waiting for
115 struct _WapiHandleOps _wapi_console_ops = {
116 console_close, /* close */
120 NULL, /* special_wait */
124 void _wapi_console_details (gpointer handle_info)
126 _wapi_file_details (handle_info);
129 /* Find handle has no ops.
131 struct _WapiHandleOps _wapi_find_ops = {
136 NULL, /* special_wait */
140 static void pipe_close (gpointer handle, gpointer data);
141 static WapiFileType pipe_getfiletype (void);
142 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
143 guint32 *bytesread, WapiOverlapped *overlapped);
144 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
145 guint32 numbytes, guint32 *byteswritten,
146 WapiOverlapped *overlapped);
150 struct _WapiHandleOps _wapi_pipe_ops = {
151 pipe_close, /* close */
155 NULL, /* special_wait */
159 void _wapi_pipe_details (gpointer handle_info)
161 _wapi_file_details (handle_info);
164 static const struct {
165 /* File, console and pipe handles */
166 WapiFileType (*getfiletype)(void);
168 /* File, console and pipe handles */
169 gboolean (*readfile)(gpointer handle, gpointer buffer,
170 guint32 numbytes, guint32 *bytesread,
171 WapiOverlapped *overlapped);
172 gboolean (*writefile)(gpointer handle, gconstpointer buffer,
173 guint32 numbytes, guint32 *byteswritten,
174 WapiOverlapped *overlapped);
175 gboolean (*flushfile)(gpointer handle);
178 guint32 (*seek)(gpointer handle, gint32 movedistance,
179 gint32 *highmovedistance, WapiSeekMethod method);
180 gboolean (*setendoffile)(gpointer handle);
181 guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
182 gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
183 WapiFileTime *last_access,
184 WapiFileTime *last_write);
185 gboolean (*setfiletime)(gpointer handle,
186 const WapiFileTime *create_time,
187 const WapiFileTime *last_access,
188 const WapiFileTime *last_write);
189 } io_ops[WAPI_HANDLE_COUNT]={
190 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
193 file_read, file_write,
194 file_flush, file_seek,
200 {console_getfiletype,
203 NULL, NULL, NULL, NULL, NULL, NULL},
205 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
207 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
209 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
211 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
212 /* socket (will need at least read and write) */
213 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
215 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
217 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
222 NULL, NULL, NULL, NULL, NULL, NULL},
225 static mono_once_t io_ops_once=MONO_ONCE_INIT;
226 static gboolean lock_while_writing = FALSE;
228 static void io_ops_init (void)
230 /* _wapi_handle_register_capabilities (WAPI_HANDLE_FILE, */
231 /* WAPI_HANDLE_CAP_WAIT); */
232 /* _wapi_handle_register_capabilities (WAPI_HANDLE_CONSOLE, */
233 /* WAPI_HANDLE_CAP_WAIT); */
235 if (g_getenv ("MONO_STRICT_IO_EMULATION") != NULL) {
236 lock_while_writing = TRUE;
240 /* Some utility functions.
243 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
250 /* FIXME: this could definitely be better, but there seems to
251 * be no pattern to the attributes that are set
254 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
255 if (S_ISSOCK (buf->st_mode))
256 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
258 filename = _wapi_basename (pathname);
260 if (S_ISDIR (buf->st_mode)) {
261 attrs = FILE_ATTRIBUTE_DIRECTORY;
262 if (!(buf->st_mode & S_IWUSR)) {
263 attrs |= FILE_ATTRIBUTE_READONLY;
265 if (filename[0] == '.') {
266 attrs |= FILE_ATTRIBUTE_HIDDEN;
269 if (!(buf->st_mode & S_IWUSR)) {
270 attrs = FILE_ATTRIBUTE_READONLY;
272 if (filename[0] == '.') {
273 attrs |= FILE_ATTRIBUTE_HIDDEN;
275 } else if (filename[0] == '.') {
276 attrs = FILE_ATTRIBUTE_HIDDEN;
278 attrs = FILE_ATTRIBUTE_NORMAL;
283 if (S_ISLNK (lbuf->st_mode)) {
284 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
294 _wapi_set_last_error_from_errno (void)
296 SetLastError (_wapi_get_win32_file_error (errno));
299 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
302 if (errno == ENOENT) {
303 /* Check the path - if it's a missing directory then
304 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
310 dirname = _wapi_dirname (path);
312 dirname = g_strdup (dir);
315 if (_wapi_access (dirname, F_OK) == 0) {
316 SetLastError (ERROR_FILE_NOT_FOUND);
318 SetLastError (ERROR_PATH_NOT_FOUND);
323 _wapi_set_last_error_from_errno ();
329 static void file_close (gpointer handle, gpointer data)
331 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
332 int fd = file_handle->fd;
334 DEBUG("%s: closing file handle %p [%s]", __func__, handle,
335 file_handle->filename);
337 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
338 _wapi_unlink (file_handle->filename);
340 g_free (file_handle->filename);
342 if (file_handle->share_info)
343 _wapi_handle_share_release (file_handle->share_info);
348 static WapiFileType file_getfiletype(void)
350 return(FILE_TYPE_DISK);
353 static gboolean file_read(gpointer handle, gpointer buffer,
354 guint32 numbytes, guint32 *bytesread,
355 WapiOverlapped *overlapped)
357 struct _WapiHandle_file *file_handle;
361 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
362 (gpointer *)&file_handle);
364 g_warning ("%s: error looking up file handle %p", __func__,
366 SetLastError (ERROR_INVALID_HANDLE);
370 fd = file_handle->fd;
371 if(bytesread!=NULL) {
375 if(!(file_handle->fileaccess & GENERIC_READ) &&
376 !(file_handle->fileaccess & GENERIC_ALL)) {
377 DEBUG("%s: handle %p doesn't have GENERIC_READ access: %u",
378 __func__, handle, file_handle->fileaccess);
380 SetLastError (ERROR_ACCESS_DENIED);
385 ret = read (fd, buffer, numbytes);
386 } while (ret == -1 && errno == EINTR &&
387 !_wapi_thread_cur_apc_pending());
392 DEBUG("%s: read of handle %p error: %s", __func__,
393 handle, strerror(err));
394 SetLastError (_wapi_get_win32_file_error (err));
398 if (bytesread != NULL) {
405 static gboolean file_write(gpointer handle, gconstpointer buffer,
406 guint32 numbytes, guint32 *byteswritten,
407 WapiOverlapped *overlapped G_GNUC_UNUSED)
409 struct _WapiHandle_file *file_handle;
412 off_t current_pos = 0;
414 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
415 (gpointer *)&file_handle);
417 g_warning ("%s: error looking up file handle %p", __func__,
419 SetLastError (ERROR_INVALID_HANDLE);
423 fd = file_handle->fd;
425 if(byteswritten!=NULL) {
429 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
430 !(file_handle->fileaccess & GENERIC_ALL)) {
431 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
433 SetLastError (ERROR_ACCESS_DENIED);
437 if (lock_while_writing) {
438 /* Need to lock the region we're about to write to,
439 * because we only do advisory locking on POSIX
442 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
443 if (current_pos == -1) {
444 DEBUG ("%s: handle %p lseek failed: %s", __func__,
445 handle, strerror (errno));
446 _wapi_set_last_error_from_errno ();
450 if (_wapi_lock_file_region (fd, current_pos,
451 numbytes) == FALSE) {
452 /* The error has already been set */
458 ret = write (fd, buffer, numbytes);
459 } while (ret == -1 && errno == EINTR &&
460 !_wapi_thread_cur_apc_pending());
462 if (lock_while_writing) {
463 _wapi_unlock_file_region (fd, current_pos, numbytes);
467 if (errno == EINTR) {
470 _wapi_set_last_error_from_errno ();
472 DEBUG("%s: write of handle %p error: %s",
473 __func__, handle, strerror(errno));
478 if (byteswritten != NULL) {
484 static gboolean file_flush(gpointer handle)
486 struct _WapiHandle_file *file_handle;
490 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
491 (gpointer *)&file_handle);
493 g_warning ("%s: error looking up file handle %p", __func__,
495 SetLastError (ERROR_INVALID_HANDLE);
499 fd = file_handle->fd;
501 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
502 !(file_handle->fileaccess & GENERIC_ALL)) {
503 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
505 SetLastError (ERROR_ACCESS_DENIED);
511 DEBUG("%s: fsync of handle %p error: %s", __func__, handle,
514 _wapi_set_last_error_from_errno ();
521 static guint32 file_seek(gpointer handle, gint32 movedistance,
522 gint32 *highmovedistance, WapiSeekMethod method)
524 struct _WapiHandle_file *file_handle;
526 off_t offset, newpos;
530 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
531 (gpointer *)&file_handle);
533 g_warning ("%s: error looking up file handle %p", __func__,
535 SetLastError (ERROR_INVALID_HANDLE);
536 return(INVALID_SET_FILE_POINTER);
539 fd = file_handle->fd;
541 if(!(file_handle->fileaccess & GENERIC_READ) &&
542 !(file_handle->fileaccess & GENERIC_WRITE) &&
543 !(file_handle->fileaccess & GENERIC_ALL)) {
544 DEBUG ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
546 SetLastError (ERROR_ACCESS_DENIED);
547 return(INVALID_SET_FILE_POINTER);
561 DEBUG("%s: invalid seek type %d", __func__, method);
563 SetLastError (ERROR_INVALID_PARAMETER);
564 return(INVALID_SET_FILE_POINTER);
567 #ifdef HAVE_LARGE_FILE_SUPPORT
568 if(highmovedistance==NULL) {
570 DEBUG("%s: setting offset to %lld (low %d)", __func__,
571 offset, movedistance);
573 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
575 DEBUG("%s: setting offset to %lld 0x%llx (high %d 0x%x, low %d 0x%x)", __func__, offset, offset, *highmovedistance, *highmovedistance, movedistance, movedistance);
581 #ifdef HAVE_LARGE_FILE_SUPPORT
582 DEBUG ("%s: moving handle %p by %lld bytes from %d", __func__,
583 handle, offset, whence);
585 DEBUG ("%s: moving handle %p fd %d by %ld bytes from %d", __func__,
586 handle, offset, whence);
589 newpos=lseek(fd, offset, whence);
591 DEBUG("%s: lseek on handle %p returned error %s",
592 __func__, handle, strerror(errno));
594 _wapi_set_last_error_from_errno ();
595 return(INVALID_SET_FILE_POINTER);
598 #ifdef HAVE_LARGE_FILE_SUPPORT
599 DEBUG ("%s: lseek returns %lld", __func__, newpos);
601 DEBUG ("%s: lseek returns %ld", __func__, newpos);
604 #ifdef HAVE_LARGE_FILE_SUPPORT
605 ret=newpos & 0xFFFFFFFF;
606 if(highmovedistance!=NULL) {
607 *highmovedistance=newpos>>32;
611 if(highmovedistance!=NULL) {
612 /* Accurate, but potentially dodgy :-) */
617 DEBUG ("%s: move of handle %p returning %d/%d", __func__,
618 handle, ret, highmovedistance==NULL?0:*highmovedistance);
623 static gboolean file_setendoffile(gpointer handle)
625 struct _WapiHandle_file *file_handle;
631 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
632 (gpointer *)&file_handle);
634 g_warning ("%s: error looking up file handle %p", __func__,
636 SetLastError (ERROR_INVALID_HANDLE);
639 fd = file_handle->fd;
641 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
642 !(file_handle->fileaccess & GENERIC_ALL)) {
643 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
645 SetLastError (ERROR_ACCESS_DENIED);
649 /* Find the current file position, and the file length. If
650 * the file position is greater than the length, write to
651 * extend the file with a hole. If the file position is less
652 * than the length, truncate the file.
655 ret=fstat(fd, &statbuf);
657 DEBUG ("%s: handle %p fstat failed: %s", __func__,
658 handle, strerror(errno));
660 _wapi_set_last_error_from_errno ();
663 size=statbuf.st_size;
665 pos=lseek(fd, (off_t)0, SEEK_CUR);
667 DEBUG("%s: handle %p lseek failed: %s", __func__,
668 handle, strerror(errno));
670 _wapi_set_last_error_from_errno ();
674 #ifdef FTRUNCATE_DOESNT_EXTEND
675 /* I haven't bothered to write the configure.in stuff for this
676 * because I don't know if any platform needs it. I'm leaving
677 * this code just in case though
680 /* Extend the file. Use write() here, because some
681 * manuals say that ftruncate() behaviour is undefined
682 * when the file needs extending. The POSIX spec says
683 * that on XSI-conformant systems it extends, so if
684 * every system we care about conforms, then we can
688 ret = write (fd, "", 1);
689 } while (ret == -1 && errno == EINTR &&
690 !_wapi_thread_cur_apc_pending());
693 DEBUG("%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
695 _wapi_set_last_error_from_errno ();
699 /* And put the file position back after the write */
700 ret = lseek (fd, pos, SEEK_SET);
702 DEBUG ("%s: handle %p second lseek failed: %s",
703 __func__, handle, strerror(errno));
705 _wapi_set_last_error_from_errno ();
711 /* Native Client has no ftruncate function, even in standalone sel_ldr. */
712 #ifndef __native_client__
713 /* always truncate, because the extend write() adds an extra
714 * byte to the end of the file
717 ret=ftruncate(fd, pos);
719 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
721 DEBUG("%s: handle %p ftruncate failed: %s", __func__,
722 handle, strerror(errno));
724 _wapi_set_last_error_from_errno ();
732 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
734 struct _WapiHandle_file *file_handle;
741 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
742 (gpointer *)&file_handle);
744 g_warning ("%s: error looking up file handle %p", __func__,
746 SetLastError (ERROR_INVALID_HANDLE);
747 return(INVALID_FILE_SIZE);
749 fd = file_handle->fd;
751 if(!(file_handle->fileaccess & GENERIC_READ) &&
752 !(file_handle->fileaccess & GENERIC_WRITE) &&
753 !(file_handle->fileaccess & GENERIC_ALL)) {
754 DEBUG("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
756 SetLastError (ERROR_ACCESS_DENIED);
757 return(INVALID_FILE_SIZE);
760 /* If the file has a size with the low bits 0xFFFFFFFF the
761 * caller can't tell if this is an error, so clear the error
764 SetLastError (ERROR_SUCCESS);
766 ret = fstat(fd, &statbuf);
768 DEBUG ("%s: handle %p fstat failed: %s", __func__,
769 handle, strerror(errno));
771 _wapi_set_last_error_from_errno ();
772 return(INVALID_FILE_SIZE);
775 /* fstat indicates block devices as zero-length, so go a different path */
777 if (S_ISBLK(statbuf.st_mode)) {
779 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
780 DEBUG ("%s: handle %p ioctl BLKGETSIZE64 failed: %s",
781 __func__, handle, strerror(errno));
783 _wapi_set_last_error_from_errno ();
784 return(INVALID_FILE_SIZE);
787 size = bigsize & 0xFFFFFFFF;
788 if (highsize != NULL) {
789 *highsize = bigsize>>32;
792 DEBUG ("%s: Returning block device size %d/%d",
793 __func__, size, *highsize);
799 #ifdef HAVE_LARGE_FILE_SUPPORT
800 size = statbuf.st_size & 0xFFFFFFFF;
801 if (highsize != NULL) {
802 *highsize = statbuf.st_size>>32;
805 if (highsize != NULL) {
806 /* Accurate, but potentially dodgy :-) */
809 size = statbuf.st_size;
812 DEBUG ("%s: Returning size %d/%d", __func__, size, *highsize);
817 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
818 WapiFileTime *last_access,
819 WapiFileTime *last_write)
821 struct _WapiHandle_file *file_handle;
824 guint64 create_ticks, access_ticks, write_ticks;
827 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
828 (gpointer *)&file_handle);
830 g_warning ("%s: error looking up file handle %p", __func__,
832 SetLastError (ERROR_INVALID_HANDLE);
835 fd = file_handle->fd;
837 if(!(file_handle->fileaccess & GENERIC_READ) &&
838 !(file_handle->fileaccess & GENERIC_ALL)) {
839 DEBUG("%s: handle %p doesn't have GENERIC_READ access: %u",
840 __func__, handle, file_handle->fileaccess);
842 SetLastError (ERROR_ACCESS_DENIED);
846 ret=fstat(fd, &statbuf);
848 DEBUG("%s: handle %p fstat failed: %s", __func__, handle,
851 _wapi_set_last_error_from_errno ();
855 DEBUG("%s: atime: %ld ctime: %ld mtime: %ld", __func__,
856 statbuf.st_atime, statbuf.st_ctime,
859 /* Try and guess a meaningful create time by using the older
862 /* The magic constant comes from msdn documentation
863 * "Converting a time_t Value to a File Time"
865 if(statbuf.st_atime < statbuf.st_ctime) {
866 create_ticks=((guint64)statbuf.st_atime*10000000)
867 + 116444736000000000ULL;
869 create_ticks=((guint64)statbuf.st_ctime*10000000)
870 + 116444736000000000ULL;
873 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
874 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
876 DEBUG("%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
877 access_ticks, create_ticks, write_ticks);
879 if(create_time!=NULL) {
880 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
881 create_time->dwHighDateTime = create_ticks >> 32;
884 if(last_access!=NULL) {
885 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
886 last_access->dwHighDateTime = access_ticks >> 32;
889 if(last_write!=NULL) {
890 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
891 last_write->dwHighDateTime = write_ticks >> 32;
897 static gboolean file_setfiletime(gpointer handle,
898 const WapiFileTime *create_time G_GNUC_UNUSED,
899 const WapiFileTime *last_access,
900 const WapiFileTime *last_write)
902 struct _WapiHandle_file *file_handle;
904 struct utimbuf utbuf;
906 guint64 access_ticks, write_ticks;
909 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
910 (gpointer *)&file_handle);
912 g_warning ("%s: error looking up file handle %p", __func__,
914 SetLastError (ERROR_INVALID_HANDLE);
917 fd = file_handle->fd;
919 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
920 !(file_handle->fileaccess & GENERIC_ALL)) {
921 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
923 SetLastError (ERROR_ACCESS_DENIED);
927 if(file_handle->filename == NULL) {
928 DEBUG("%s: handle %p unknown filename", __func__, handle);
930 SetLastError (ERROR_INVALID_HANDLE);
934 /* Get the current times, so we can put the same times back in
935 * the event that one of the FileTime structs is NULL
937 ret=fstat (fd, &statbuf);
939 DEBUG("%s: handle %p fstat failed: %s", __func__, handle,
942 SetLastError (ERROR_INVALID_PARAMETER);
946 if(last_access!=NULL) {
947 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
948 last_access->dwLowDateTime;
949 /* This is (time_t)0. We can actually go to INT_MIN,
950 * but this will do for now.
952 if (access_ticks < 116444736000000000ULL) {
953 DEBUG ("%s: attempt to set access time too early",
955 SetLastError (ERROR_INVALID_PARAMETER);
959 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
961 utbuf.actime=statbuf.st_atime;
964 if(last_write!=NULL) {
965 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
966 last_write->dwLowDateTime;
967 /* This is (time_t)0. We can actually go to INT_MIN,
968 * but this will do for now.
970 if (write_ticks < 116444736000000000ULL) {
971 DEBUG ("%s: attempt to set write time too early",
973 SetLastError (ERROR_INVALID_PARAMETER);
977 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
979 utbuf.modtime=statbuf.st_mtime;
982 DEBUG ("%s: setting handle %p access %ld write %ld", __func__,
983 handle, utbuf.actime, utbuf.modtime);
985 ret = _wapi_utime (file_handle->filename, &utbuf);
987 DEBUG ("%s: handle %p [%s] utime failed: %s", __func__,
988 handle, file_handle->filename, strerror(errno));
990 SetLastError (ERROR_INVALID_PARAMETER);
997 static void console_close (gpointer handle, gpointer data)
999 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1000 int fd = console_handle->fd;
1002 DEBUG("%s: closing console handle %p", __func__, handle);
1004 g_free (console_handle->filename);
1009 static WapiFileType console_getfiletype(void)
1011 return(FILE_TYPE_CHAR);
1014 static gboolean console_read(gpointer handle, gpointer buffer,
1015 guint32 numbytes, guint32 *bytesread,
1016 WapiOverlapped *overlapped G_GNUC_UNUSED)
1018 struct _WapiHandle_file *console_handle;
1022 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1023 (gpointer *)&console_handle);
1025 g_warning ("%s: error looking up console handle %p", __func__,
1027 SetLastError (ERROR_INVALID_HANDLE);
1030 fd = console_handle->fd;
1032 if(bytesread!=NULL) {
1036 if(!(console_handle->fileaccess & GENERIC_READ) &&
1037 !(console_handle->fileaccess & GENERIC_ALL)) {
1038 DEBUG ("%s: handle %p doesn't have GENERIC_READ access: %u",
1039 __func__, handle, console_handle->fileaccess);
1041 SetLastError (ERROR_ACCESS_DENIED);
1046 ret=read(fd, buffer, numbytes);
1047 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1050 DEBUG("%s: read of handle %p error: %s", __func__, handle,
1053 _wapi_set_last_error_from_errno ();
1057 if(bytesread!=NULL) {
1064 static gboolean console_write(gpointer handle, gconstpointer buffer,
1065 guint32 numbytes, guint32 *byteswritten,
1066 WapiOverlapped *overlapped G_GNUC_UNUSED)
1068 struct _WapiHandle_file *console_handle;
1072 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1073 (gpointer *)&console_handle);
1075 g_warning ("%s: error looking up console handle %p", __func__,
1077 SetLastError (ERROR_INVALID_HANDLE);
1080 fd = console_handle->fd;
1082 if(byteswritten!=NULL) {
1086 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1087 !(console_handle->fileaccess & GENERIC_ALL)) {
1088 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, console_handle->fileaccess);
1090 SetLastError (ERROR_ACCESS_DENIED);
1095 ret = write(fd, buffer, numbytes);
1096 } while (ret == -1 && errno == EINTR &&
1097 !_wapi_thread_cur_apc_pending());
1100 if (errno == EINTR) {
1103 _wapi_set_last_error_from_errno ();
1105 DEBUG ("%s: write of handle %p error: %s",
1106 __func__, handle, strerror(errno));
1111 if(byteswritten!=NULL) {
1118 static void pipe_close (gpointer handle, gpointer data)
1120 struct _WapiHandle_file *pipe_handle = (struct _WapiHandle_file*)data;
1121 int fd = pipe_handle->fd;
1123 DEBUG("%s: closing pipe handle %p", __func__, handle);
1125 /* No filename with pipe handles */
1130 static WapiFileType pipe_getfiletype(void)
1132 return(FILE_TYPE_PIPE);
1135 static gboolean pipe_read (gpointer handle, gpointer buffer,
1136 guint32 numbytes, guint32 *bytesread,
1137 WapiOverlapped *overlapped G_GNUC_UNUSED)
1139 struct _WapiHandle_file *pipe_handle;
1143 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1144 (gpointer *)&pipe_handle);
1146 g_warning ("%s: error looking up pipe handle %p", __func__,
1148 SetLastError (ERROR_INVALID_HANDLE);
1151 fd = pipe_handle->fd;
1153 if(bytesread!=NULL) {
1157 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1158 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1159 DEBUG("%s: handle %p doesn't have GENERIC_READ access: %u",
1160 __func__, handle, pipe_handle->fileaccess);
1162 SetLastError (ERROR_ACCESS_DENIED);
1166 DEBUG ("%s: reading up to %d bytes from pipe %p", __func__,
1170 ret=read(fd, buffer, numbytes);
1171 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1174 if (errno == EINTR) {
1177 _wapi_set_last_error_from_errno ();
1179 DEBUG("%s: read of handle %p error: %s", __func__,
1180 handle, strerror(errno));
1186 DEBUG ("%s: read %d bytes from pipe", __func__, ret);
1188 if(bytesread!=NULL) {
1195 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1196 guint32 numbytes, guint32 *byteswritten,
1197 WapiOverlapped *overlapped G_GNUC_UNUSED)
1199 struct _WapiHandle_file *pipe_handle;
1203 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1204 (gpointer *)&pipe_handle);
1206 g_warning ("%s: error looking up pipe handle %p", __func__,
1208 SetLastError (ERROR_INVALID_HANDLE);
1211 fd = pipe_handle->fd;
1213 if(byteswritten!=NULL) {
1217 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1218 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1219 DEBUG("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, pipe_handle->fileaccess);
1221 SetLastError (ERROR_ACCESS_DENIED);
1225 DEBUG ("%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1229 ret = write (fd, buffer, numbytes);
1230 } while (ret == -1 && errno == EINTR &&
1231 !_wapi_thread_cur_apc_pending());
1234 if (errno == EINTR) {
1237 _wapi_set_last_error_from_errno ();
1239 DEBUG("%s: write of handle %p error: %s", __func__,
1240 handle, strerror(errno));
1245 if(byteswritten!=NULL) {
1252 static int convert_flags(guint32 fileaccess, guint32 createmode)
1256 switch(fileaccess) {
1263 case GENERIC_READ|GENERIC_WRITE:
1267 DEBUG("%s: Unknown access type 0x%x", __func__,
1272 switch(createmode) {
1274 flags|=O_CREAT|O_EXCL;
1277 flags|=O_CREAT|O_TRUNC;
1284 case TRUNCATE_EXISTING:
1288 DEBUG("%s: Unknown create mode 0x%x", __func__,
1297 static mode_t convert_perms(guint32 sharemode)
1301 if(sharemode&FILE_SHARE_READ) {
1304 if(sharemode&FILE_SHARE_WRITE) {
1312 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1314 struct _WapiFileShare **share_info)
1316 gboolean file_already_shared;
1317 guint32 file_existing_share, file_existing_access;
1319 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);
1321 if (file_already_shared) {
1322 /* The reference to this share info was incremented
1323 * when we looked it up, so be careful to put it back
1324 * if we conclude we can't use this file.
1326 if (file_existing_share == 0) {
1327 /* Quick and easy, no possibility to share */
1328 DEBUG ("%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
1330 _wapi_handle_share_release (*share_info);
1335 if (((file_existing_share == FILE_SHARE_READ) &&
1336 (fileaccess != GENERIC_READ)) ||
1337 ((file_existing_share == FILE_SHARE_WRITE) &&
1338 (fileaccess != GENERIC_WRITE))) {
1339 /* New access mode doesn't match up */
1340 DEBUG ("%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
1342 _wapi_handle_share_release (*share_info);
1347 if (((file_existing_access & GENERIC_READ) &&
1348 !(sharemode & FILE_SHARE_READ)) ||
1349 ((file_existing_access & GENERIC_WRITE) &&
1350 !(sharemode & FILE_SHARE_WRITE))) {
1351 /* New share mode doesn't match up */
1352 DEBUG ("%s: Access mode prevents open: requested share: 0x%x, file has access: 0x%x", __func__, sharemode, file_existing_access);
1354 _wapi_handle_share_release (*share_info);
1359 DEBUG ("%s: New file!", __func__);
1365 static gboolean share_check (struct stat *statbuf, guint32 sharemode,
1367 struct _WapiFileShare **share_info, int fd)
1369 if (share_allows_open (statbuf, sharemode, fileaccess,
1370 share_info) == TRUE) {
1374 /* Got a share violation. Double check that the file is still
1375 * open by someone, in case a process crashed while still
1376 * holding a file handle. This will also cope with someone
1377 * using Mono.Posix to close the file. This is cheaper and
1378 * less intrusive to other processes than initiating a handle
1382 _wapi_handle_check_share (*share_info, fd);
1383 if (share_allows_open (statbuf, sharemode, fileaccess,
1384 share_info) == TRUE) {
1388 /* Still violating. It's possible that a process crashed
1389 * while still holding a file handle, and that a non-mono
1390 * process has the file open. (For example, C-c mcs while
1391 * editing a source file.) As a last resort, run a handle
1392 * collection, which will remove stale share entries.
1394 _wapi_handle_collect ();
1396 return(share_allows_open (statbuf, sharemode, fileaccess, share_info));
1401 * @name: a pointer to a NULL-terminated unicode string, that names
1402 * the file or other object to create.
1403 * @fileaccess: specifies the file access mode
1404 * @sharemode: whether the file should be shared. This parameter is
1405 * currently ignored.
1406 * @security: Ignored for now.
1407 * @createmode: specifies whether to create a new file, whether to
1408 * overwrite an existing file, whether to truncate the file, etc.
1409 * @attrs: specifies file attributes and flags. On win32 attributes
1410 * are characteristics of the file, not the handle, and are ignored
1411 * when an existing file is opened. Flags give the library hints on
1412 * how to process a file to optimise performance.
1413 * @template: the handle of an open %GENERIC_READ file that specifies
1414 * attributes to apply to a newly created file, ignoring @attrs.
1415 * Normally this parameter is NULL. This parameter is ignored when an
1416 * existing file is opened.
1418 * Creates a new file handle. This only applies to normal files:
1419 * pipes are handled by CreatePipe(), and console handles are created
1420 * with GetStdHandle().
1422 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1424 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1425 guint32 sharemode, WapiSecurityAttributes *security,
1426 guint32 createmode, guint32 attrs,
1427 gpointer template G_GNUC_UNUSED)
1429 struct _WapiHandle_file file_handle = {0};
1431 int flags=convert_flags(fileaccess, createmode);
1432 /*mode_t perms=convert_perms(sharemode);*/
1433 /* we don't use sharemode, because that relates to sharing of
1434 * the file when the file is open and is already handled by
1435 * other code, perms instead are the on-disk permissions and
1436 * this is a sane default.
1442 struct stat statbuf;
1444 mono_once (&io_ops_once, io_ops_init);
1446 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1449 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1450 SetLastError (ERROR_ENCRYPTION_FAILED);
1451 return INVALID_HANDLE_VALUE;
1455 DEBUG ("%s: name is NULL", __func__);
1457 SetLastError (ERROR_INVALID_NAME);
1458 return(INVALID_HANDLE_VALUE);
1461 filename = mono_unicode_to_external (name);
1462 if (filename == NULL) {
1463 DEBUG("%s: unicode conversion returned NULL", __func__);
1465 SetLastError (ERROR_INVALID_NAME);
1466 return(INVALID_HANDLE_VALUE);
1469 DEBUG ("%s: Opening %s with share 0x%x and access 0x%x", __func__,
1470 filename, sharemode, fileaccess);
1472 fd = _wapi_open (filename, flags, perms);
1474 /* If we were trying to open a directory with write permissions
1475 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1476 * EISDIR. However, this is a bit bogus because calls to
1477 * manipulate the directory (e.g. SetFileTime) will still work on
1478 * the directory because they use other API calls
1479 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1480 * to open the directory again without write permission.
1482 if (fd == -1 && errno == EISDIR)
1484 /* Try again but don't try to make it writable */
1485 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1489 DEBUG("%s: Error opening file %s: %s", __func__, filename,
1491 _wapi_set_last_path_error_from_errno (NULL, filename);
1494 return(INVALID_HANDLE_VALUE);
1497 if (fd >= _wapi_fd_reserve) {
1498 DEBUG ("%s: File descriptor is too big", __func__);
1500 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1505 return(INVALID_HANDLE_VALUE);
1508 ret = fstat (fd, &statbuf);
1510 DEBUG ("%s: fstat error of file %s: %s", __func__,
1511 filename, strerror (errno));
1512 _wapi_set_last_error_from_errno ();
1516 return(INVALID_HANDLE_VALUE);
1518 #ifdef __native_client__
1519 /* Workaround: Native Client currently returns the same fake inode
1520 * for all files, so do a simple hash on the filename so we don't
1521 * use the same share info for each file.
1523 statbuf.st_ino = g_str_hash(filename);
1526 if (share_check (&statbuf, sharemode, fileaccess,
1527 &file_handle.share_info, fd) == FALSE) {
1528 SetLastError (ERROR_SHARING_VIOLATION);
1532 return (INVALID_HANDLE_VALUE);
1534 if (file_handle.share_info == NULL) {
1535 /* No space, so no more files can be opened */
1536 DEBUG ("%s: No space in the share table", __func__);
1538 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1542 return(INVALID_HANDLE_VALUE);
1545 file_handle.filename = filename;
1547 if(security!=NULL) {
1548 //file_handle->security_attributes=_wapi_handle_scratch_store (
1549 //security, sizeof(WapiSecurityAttributes));
1552 file_handle.fd = fd;
1553 file_handle.fileaccess=fileaccess;
1554 file_handle.sharemode=sharemode;
1555 file_handle.attrs=attrs;
1557 #ifdef HAVE_POSIX_FADVISE
1558 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1559 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1560 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1561 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1565 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1567 if (S_ISFIFO (statbuf.st_mode)) {
1568 handle_type = WAPI_HANDLE_PIPE;
1569 } else if (S_ISCHR (statbuf.st_mode)) {
1570 handle_type = WAPI_HANDLE_CONSOLE;
1572 handle_type = WAPI_HANDLE_FILE;
1575 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1576 if (handle == _WAPI_HANDLE_INVALID) {
1577 g_warning ("%s: error creating file handle", __func__);
1581 SetLastError (ERROR_GEN_FAILURE);
1582 return(INVALID_HANDLE_VALUE);
1585 DEBUG("%s: returning handle %p", __func__, handle);
1592 * @name: a pointer to a NULL-terminated unicode string, that names
1593 * the file to be deleted.
1595 * Deletes file @name.
1597 * Return value: %TRUE on success, %FALSE otherwise.
1599 gboolean DeleteFile(const gunichar2 *name)
1603 gboolean ret = FALSE;
1606 struct stat statbuf;
1607 struct _WapiFileShare *shareinfo;
1611 DEBUG("%s: name is NULL", __func__);
1613 SetLastError (ERROR_INVALID_NAME);
1617 filename=mono_unicode_to_external(name);
1618 if(filename==NULL) {
1619 DEBUG("%s: unicode conversion returned NULL", __func__);
1621 SetLastError (ERROR_INVALID_NAME);
1625 attrs = GetFileAttributes (name);
1626 if (attrs == INVALID_FILE_ATTRIBUTES) {
1627 DEBUG ("%s: file attributes error", __func__);
1628 /* Error set by GetFileAttributes() */
1634 /* Check to make sure sharing allows us to open the file for
1635 * writing. See bug 323389.
1637 * Do the checks that don't need an open file descriptor, for
1638 * simplicity's sake. If we really have to do the full checks
1639 * then we can implement that later.
1641 if (_wapi_stat (filename, &statbuf) < 0) {
1642 _wapi_set_last_path_error_from_errno (NULL, filename);
1647 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1648 &shareinfo) == FALSE) {
1649 SetLastError (ERROR_SHARING_VIOLATION);
1654 _wapi_handle_share_release (shareinfo);
1657 retval = _wapi_unlink (filename);
1660 _wapi_set_last_path_error_from_errno (NULL, filename);
1672 * @name: a pointer to a NULL-terminated unicode string, that names
1673 * the file to be moved.
1674 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1675 * new name for the file.
1677 * Renames file @name to @dest_name.
1678 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1679 * when it is the same file as the source. In that case it silently succeeds.
1681 * Return value: %TRUE on success, %FALSE otherwise.
1683 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1685 gchar *utf8_name, *utf8_dest_name;
1686 int result, errno_copy;
1687 struct stat stat_src, stat_dest;
1688 gboolean ret = FALSE;
1689 struct _WapiFileShare *shareinfo;
1692 DEBUG("%s: name is NULL", __func__);
1694 SetLastError (ERROR_INVALID_NAME);
1698 utf8_name = mono_unicode_to_external (name);
1699 if (utf8_name == NULL) {
1700 DEBUG ("%s: unicode conversion returned NULL", __func__);
1702 SetLastError (ERROR_INVALID_NAME);
1706 if(dest_name==NULL) {
1707 DEBUG("%s: name is NULL", __func__);
1710 SetLastError (ERROR_INVALID_NAME);
1714 utf8_dest_name = mono_unicode_to_external (dest_name);
1715 if (utf8_dest_name == NULL) {
1716 DEBUG ("%s: unicode conversion returned NULL", __func__);
1719 SetLastError (ERROR_INVALID_NAME);
1724 * In C# land we check for the existence of src, but not for dest.
1725 * We check it here and return the failure if dest exists and is not
1726 * the same file as src.
1728 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1729 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1730 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1732 g_free (utf8_dest_name);
1737 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1738 if (stat_dest.st_dev != stat_src.st_dev ||
1739 stat_dest.st_ino != stat_src.st_ino) {
1741 g_free (utf8_dest_name);
1742 SetLastError (ERROR_ALREADY_EXISTS);
1747 /* Check to make sure sharing allows us to open the file for
1748 * writing. See bug 377049.
1750 * Do the checks that don't need an open file descriptor, for
1751 * simplicity's sake. If we really have to do the full checks
1752 * then we can implement that later.
1754 if (share_allows_open (&stat_src, 0, GENERIC_WRITE,
1755 &shareinfo) == FALSE) {
1756 SetLastError (ERROR_SHARING_VIOLATION);
1760 _wapi_handle_share_release (shareinfo);
1762 result = _wapi_rename (utf8_name, utf8_dest_name);
1766 switch(errno_copy) {
1768 SetLastError (ERROR_ALREADY_EXISTS);
1772 /* Ignore here, it is dealt with below */
1776 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1781 g_free (utf8_dest_name);
1783 if (result != 0 && errno_copy == EXDEV) {
1784 if (S_ISDIR (stat_src.st_mode)) {
1785 SetLastError (ERROR_NOT_SAME_DEVICE);
1788 /* Try a copy to the new location, and delete the source */
1789 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1790 /* CopyFile will set the error */
1794 return(DeleteFile (name));
1805 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1809 int buf_size = st_src->st_blksize;
1811 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1812 buf = (char *) malloc (buf_size);
1815 remain = read (src_fd, buf, buf_size);
1817 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1821 _wapi_set_last_error_from_errno ();
1831 while (remain > 0) {
1832 if ((n = write (dest_fd, wbuf, remain)) < 0) {
1833 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1837 _wapi_set_last_error_from_errno ();
1838 DEBUG ("%s: write failed.", __func__);
1854 * @name: a pointer to a NULL-terminated unicode string, that names
1855 * the file to be copied.
1856 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1857 * new name for the file.
1858 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1860 * Copies file @name to @dest_name
1862 * Return value: %TRUE on success, %FALSE otherwise.
1864 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1865 gboolean fail_if_exists)
1867 gchar *utf8_src, *utf8_dest;
1868 int src_fd, dest_fd;
1869 struct stat st, dest_st;
1870 struct utimbuf dest_time;
1871 gboolean ret = TRUE;
1875 DEBUG("%s: name is NULL", __func__);
1877 SetLastError (ERROR_INVALID_NAME);
1881 utf8_src = mono_unicode_to_external (name);
1882 if (utf8_src == NULL) {
1883 DEBUG ("%s: unicode conversion of source returned NULL",
1886 SetLastError (ERROR_INVALID_PARAMETER);
1890 if(dest_name==NULL) {
1891 DEBUG("%s: dest is NULL", __func__);
1894 SetLastError (ERROR_INVALID_NAME);
1898 utf8_dest = mono_unicode_to_external (dest_name);
1899 if (utf8_dest == NULL) {
1900 DEBUG ("%s: unicode conversion of dest returned NULL",
1903 SetLastError (ERROR_INVALID_PARAMETER);
1910 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
1912 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
1920 if (fstat (src_fd, &st) < 0) {
1921 _wapi_set_last_error_from_errno ();
1930 /* Before trying to open/create the dest, we need to report a 'file busy'
1931 * error if src and dest are actually the same file. We do the check here to take
1932 * advantage of the IOMAP capability */
1933 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
1934 st.st_ino == dest_st.st_ino) {
1940 SetLastError (ERROR_SHARING_VIOLATION);
1944 if (fail_if_exists) {
1945 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
1947 /* FIXME: it kinda sucks that this code path potentially scans
1948 * the directory twice due to the weird SetLastError()
1950 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
1952 /* The file does not exist, try creating it */
1953 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
1955 /* Apparently this error is set if we
1956 * overwrite the dest file
1958 SetLastError (ERROR_ALREADY_EXISTS);
1962 _wapi_set_last_error_from_errno ();
1971 if (!write_file (src_fd, dest_fd, &st, TRUE))
1977 dest_time.modtime = st.st_mtime;
1978 dest_time.actime = st.st_atime;
1979 ret_utime = utime (utf8_dest, &dest_time);
1980 if (ret_utime == -1)
1981 DEBUG ("%s: file [%s] utime failed: %s", __func__, utf8_dest, strerror(errno));
1990 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
1995 DEBUG ("%s: %s is NULL", __func__, arg_name);
1996 SetLastError (ERROR_INVALID_NAME);
2000 utf8_ret = mono_unicode_to_external (arg);
2001 if (utf8_ret == NULL) {
2002 DEBUG ("%s: unicode conversion of %s returned NULL",
2003 __func__, arg_name);
2004 SetLastError (ERROR_INVALID_PARAMETER);
2012 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2013 const gunichar2 *backupFileName, guint32 replaceFlags,
2014 gpointer exclude, gpointer reserved)
2016 int result, errno_copy, backup_fd = -1,replaced_fd = -1;
2017 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2018 struct stat stBackup;
2019 gboolean ret = FALSE;
2021 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2023 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2024 goto replace_cleanup;
2025 if (backupFileName != NULL) {
2026 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2027 goto replace_cleanup;
2030 if (utf8_backupFileName) {
2031 // Open the backup file for read so we can restore the file if an error occurs.
2032 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2033 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2036 goto replace_cleanup;
2039 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2042 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2043 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2044 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2045 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2048 if (replaced_fd == -1)
2049 goto replace_cleanup;
2051 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2054 goto replace_cleanup;
2060 g_free (utf8_replacedFileName);
2061 g_free (utf8_replacementFileName);
2062 g_free (utf8_backupFileName);
2063 if (backup_fd != -1)
2065 if (replaced_fd != -1)
2066 close (replaced_fd);
2072 * @stdhandle: specifies the file descriptor
2074 * Returns a handle for stdin, stdout, or stderr. Always returns the
2075 * same handle for the same @stdhandle.
2077 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2080 static mono_mutex_t stdhandle_mutex;
2082 gpointer GetStdHandle(WapiStdHandle stdhandle)
2084 struct _WapiHandle_file *file_handle;
2091 case STD_INPUT_HANDLE:
2096 case STD_OUTPUT_HANDLE:
2101 case STD_ERROR_HANDLE:
2107 DEBUG("%s: unknown standard handle type", __func__);
2109 SetLastError (ERROR_INVALID_PARAMETER);
2110 return(INVALID_HANDLE_VALUE);
2113 handle = GINT_TO_POINTER (fd);
2115 pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2116 (void *)&stdhandle_mutex);
2117 thr_ret = mono_mutex_lock (&stdhandle_mutex);
2118 g_assert (thr_ret == 0);
2120 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2121 (gpointer *)&file_handle);
2123 /* Need to create this console handle */
2124 handle = _wapi_stdhandle_create (fd, name);
2126 if (handle == INVALID_HANDLE_VALUE) {
2127 SetLastError (ERROR_NO_MORE_FILES);
2131 /* Add a reference to this handle */
2132 _wapi_handle_ref (handle);
2136 thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2137 g_assert (thr_ret == 0);
2138 pthread_cleanup_pop (0);
2145 * @handle: The file handle to read from. The handle must have
2146 * %GENERIC_READ access.
2147 * @buffer: The buffer to store read data in
2148 * @numbytes: The maximum number of bytes to read
2149 * @bytesread: The actual number of bytes read is stored here. This
2150 * value can be zero if the handle is positioned at the end of the
2152 * @overlapped: points to a required %WapiOverlapped structure if
2153 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2156 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2157 * function reads up to @numbytes bytes from the file from the current
2158 * file position, and stores them in @buffer. If there are not enough
2159 * bytes left in the file, just the amount available will be read.
2160 * The actual number of bytes read is stored in @bytesread.
2162 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2163 * file position is ignored and the read position is taken from data
2164 * in the @overlapped structure.
2166 * Return value: %TRUE if the read succeeds (even if no bytes were
2167 * read due to an attempt to read past the end of the file), %FALSE on
2170 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2171 guint32 *bytesread, WapiOverlapped *overlapped)
2173 WapiHandleType type;
2175 type = _wapi_handle_type (handle);
2177 if(io_ops[type].readfile==NULL) {
2178 SetLastError (ERROR_INVALID_HANDLE);
2182 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2188 * @handle: The file handle to write to. The handle must have
2189 * %GENERIC_WRITE access.
2190 * @buffer: The buffer to read data from.
2191 * @numbytes: The maximum number of bytes to write.
2192 * @byteswritten: The actual number of bytes written is stored here.
2193 * If the handle is positioned at the file end, the length of the file
2194 * is extended. This parameter may be %NULL.
2195 * @overlapped: points to a required %WapiOverlapped structure if
2196 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2199 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2200 * function writes up to @numbytes bytes from @buffer to the file at
2201 * the current file position. If @handle is positioned at the end of
2202 * the file, the file is extended. The actual number of bytes written
2203 * is stored in @byteswritten.
2205 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2206 * file position is ignored and the write position is taken from data
2207 * in the @overlapped structure.
2209 * Return value: %TRUE if the write succeeds, %FALSE on error.
2211 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2212 guint32 *byteswritten, WapiOverlapped *overlapped)
2214 WapiHandleType type;
2216 type = _wapi_handle_type (handle);
2218 if(io_ops[type].writefile==NULL) {
2219 SetLastError (ERROR_INVALID_HANDLE);
2223 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2229 * @handle: Handle to open file. The handle must have
2230 * %GENERIC_WRITE access.
2232 * Flushes buffers of the file and causes all unwritten data to
2235 * Return value: %TRUE on success, %FALSE otherwise.
2237 gboolean FlushFileBuffers(gpointer handle)
2239 WapiHandleType type;
2241 type = _wapi_handle_type (handle);
2243 if(io_ops[type].flushfile==NULL) {
2244 SetLastError (ERROR_INVALID_HANDLE);
2248 return(io_ops[type].flushfile (handle));
2253 * @handle: The file handle to set. The handle must have
2254 * %GENERIC_WRITE access.
2256 * Moves the end-of-file position to the current position of the file
2257 * pointer. This function is used to truncate or extend a file.
2259 * Return value: %TRUE on success, %FALSE otherwise.
2261 gboolean SetEndOfFile(gpointer handle)
2263 WapiHandleType type;
2265 type = _wapi_handle_type (handle);
2267 if (io_ops[type].setendoffile == NULL) {
2268 SetLastError (ERROR_INVALID_HANDLE);
2272 return(io_ops[type].setendoffile (handle));
2277 * @handle: The file handle to set. The handle must have
2278 * %GENERIC_READ or %GENERIC_WRITE access.
2279 * @movedistance: Low 32 bits of a signed value that specifies the
2280 * number of bytes to move the file pointer.
2281 * @highmovedistance: Pointer to the high 32 bits of a signed value
2282 * that specifies the number of bytes to move the file pointer, or
2284 * @method: The starting point for the file pointer move.
2286 * Sets the file pointer of an open file.
2288 * The distance to move the file pointer is calculated from
2289 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2290 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2291 * is the low 32 bits and @highmovedistance a pointer to the high 32
2292 * bits of a 64 bit signed value. A positive distance moves the file
2293 * pointer forward from the position specified by @method; a negative
2294 * distance moves the file pointer backward.
2296 * If the library is compiled without large file support,
2297 * @highmovedistance is ignored and its value is set to zero on a
2298 * successful return.
2300 * Return value: On success, the low 32 bits of the new file pointer.
2301 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2302 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2304 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2305 gint32 *highmovedistance, WapiSeekMethod method)
2307 WapiHandleType type;
2309 type = _wapi_handle_type (handle);
2311 if (io_ops[type].seek == NULL) {
2312 SetLastError (ERROR_INVALID_HANDLE);
2313 return(INVALID_SET_FILE_POINTER);
2316 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2322 * @handle: The file handle to test.
2324 * Finds the type of file @handle.
2326 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2327 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2328 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2329 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2331 WapiFileType GetFileType(gpointer handle)
2333 WapiHandleType type;
2335 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2336 SetLastError (ERROR_INVALID_HANDLE);
2337 return(FILE_TYPE_UNKNOWN);
2340 type = _wapi_handle_type (handle);
2342 if (io_ops[type].getfiletype == NULL) {
2343 SetLastError (ERROR_INVALID_HANDLE);
2344 return(FILE_TYPE_UNKNOWN);
2347 return(io_ops[type].getfiletype ());
2352 * @handle: The file handle to query. The handle must have
2353 * %GENERIC_READ or %GENERIC_WRITE access.
2354 * @highsize: If non-%NULL, the high 32 bits of the file size are
2357 * Retrieves the size of the file @handle.
2359 * If the library is compiled without large file support, @highsize
2360 * has its value set to zero on a successful return.
2362 * Return value: On success, the low 32 bits of the file size. If
2363 * @highsize is non-%NULL then the high 32 bits of the file size are
2364 * stored here. On failure %INVALID_FILE_SIZE is returned.
2366 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2368 WapiHandleType type;
2370 type = _wapi_handle_type (handle);
2372 if (io_ops[type].getfilesize == NULL) {
2373 SetLastError (ERROR_INVALID_HANDLE);
2374 return(INVALID_FILE_SIZE);
2377 return(io_ops[type].getfilesize (handle, highsize));
2382 * @handle: The file handle to query. The handle must have
2383 * %GENERIC_READ access.
2384 * @create_time: Points to a %WapiFileTime structure to receive the
2385 * number of ticks since the epoch that file was created. May be
2387 * @last_access: Points to a %WapiFileTime structure to receive the
2388 * number of ticks since the epoch when file was last accessed. May be
2390 * @last_write: Points to a %WapiFileTime structure to receive the
2391 * number of ticks since the epoch when file was last written to. May
2394 * Finds the number of ticks since the epoch that the file referenced
2395 * by @handle was created, last accessed and last modified. A tick is
2396 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2399 * Create time isn't recorded on POSIX file systems or reported by
2400 * stat(2), so that time is guessed by returning the oldest of the
2403 * Return value: %TRUE on success, %FALSE otherwise.
2405 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2406 WapiFileTime *last_access, WapiFileTime *last_write)
2408 WapiHandleType type;
2410 type = _wapi_handle_type (handle);
2412 if (io_ops[type].getfiletime == NULL) {
2413 SetLastError (ERROR_INVALID_HANDLE);
2417 return(io_ops[type].getfiletime (handle, create_time, last_access,
2423 * @handle: The file handle to set. The handle must have
2424 * %GENERIC_WRITE access.
2425 * @create_time: Points to a %WapiFileTime structure that contains the
2426 * number of ticks since the epoch that the file was created. May be
2428 * @last_access: Points to a %WapiFileTime structure that contains the
2429 * number of ticks since the epoch when the file was last accessed.
2431 * @last_write: Points to a %WapiFileTime structure that contains the
2432 * number of ticks since the epoch when the file was last written to.
2435 * Sets the number of ticks since the epoch that the file referenced
2436 * by @handle was created, last accessed or last modified. A tick is
2437 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2440 * Create time isn't recorded on POSIX file systems, and is ignored.
2442 * Return value: %TRUE on success, %FALSE otherwise.
2444 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2445 const WapiFileTime *last_access,
2446 const WapiFileTime *last_write)
2448 WapiHandleType type;
2450 type = _wapi_handle_type (handle);
2452 if (io_ops[type].setfiletime == NULL) {
2453 SetLastError (ERROR_INVALID_HANDLE);
2457 return(io_ops[type].setfiletime (handle, create_time, last_access,
2461 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2462 * January 1 1601 GMT
2465 #define TICKS_PER_MILLISECOND 10000L
2466 #define TICKS_PER_SECOND 10000000L
2467 #define TICKS_PER_MINUTE 600000000L
2468 #define TICKS_PER_HOUR 36000000000LL
2469 #define TICKS_PER_DAY 864000000000LL
2471 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2473 static const guint16 mon_yday[2][13]={
2474 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2475 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2479 * FileTimeToSystemTime:
2480 * @file_time: Points to a %WapiFileTime structure that contains the
2481 * number of ticks to convert.
2482 * @system_time: Points to a %WapiSystemTime structure to receive the
2485 * Converts a tick count into broken-out time values.
2487 * Return value: %TRUE on success, %FALSE otherwise.
2489 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2490 WapiSystemTime *system_time)
2492 gint64 file_ticks, totaldays, rem, y;
2495 if(system_time==NULL) {
2496 DEBUG("%s: system_time NULL", __func__);
2498 SetLastError (ERROR_INVALID_PARAMETER);
2502 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2503 file_time->dwLowDateTime;
2505 /* Really compares if file_ticks>=0x8000000000000000
2506 * (LLONG_MAX+1) but we're working with a signed value for the
2507 * year and day calculation to work later
2510 DEBUG("%s: file_time too big", __func__);
2512 SetLastError (ERROR_INVALID_PARAMETER);
2516 totaldays=(file_ticks / TICKS_PER_DAY);
2517 rem = file_ticks % TICKS_PER_DAY;
2518 DEBUG("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2520 system_time->wHour=rem/TICKS_PER_HOUR;
2521 rem %= TICKS_PER_HOUR;
2522 DEBUG("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2524 system_time->wMinute = rem / TICKS_PER_MINUTE;
2525 rem %= TICKS_PER_MINUTE;
2526 DEBUG("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2529 system_time->wSecond = rem / TICKS_PER_SECOND;
2530 rem %= TICKS_PER_SECOND;
2531 DEBUG("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2534 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2535 DEBUG("%s: Milliseconds: %d", __func__,
2536 system_time->wMilliseconds);
2538 /* January 1, 1601 was a Monday, according to Emacs calendar */
2539 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2540 DEBUG("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2542 /* This algorithm to find year and month given days from epoch
2547 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2548 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2550 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2551 /* Guess a corrected year, assuming 365 days per year */
2552 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2553 DEBUG("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2556 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2557 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2559 /* Adjust days and y to match the guessed year. */
2560 totaldays -= ((yg - y) * 365
2561 + LEAPS_THRU_END_OF (yg - 1)
2562 - LEAPS_THRU_END_OF (y - 1));
2563 DEBUG("%s: totaldays: %lld", __func__, totaldays);
2565 DEBUG("%s: y: %lld", __func__, y);
2568 system_time->wYear = y;
2569 DEBUG("%s: Year: %d", __func__, system_time->wYear);
2571 ip = mon_yday[isleap(y)];
2573 for(y=11; totaldays < ip[y]; --y) {
2577 DEBUG("%s: totaldays: %lld", __func__, totaldays);
2579 system_time->wMonth = y + 1;
2580 DEBUG("%s: Month: %d", __func__, system_time->wMonth);
2582 system_time->wDay = totaldays + 1;
2583 DEBUG("%s: Day: %d", __func__, system_time->wDay);
2588 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2590 struct _WapiHandle_find find_handle = {0};
2592 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2595 if (pattern == NULL) {
2596 DEBUG ("%s: pattern is NULL", __func__);
2598 SetLastError (ERROR_PATH_NOT_FOUND);
2599 return(INVALID_HANDLE_VALUE);
2602 utf8_pattern = mono_unicode_to_external (pattern);
2603 if (utf8_pattern == NULL) {
2604 DEBUG ("%s: unicode conversion returned NULL", __func__);
2606 SetLastError (ERROR_INVALID_NAME);
2607 return(INVALID_HANDLE_VALUE);
2610 DEBUG ("%s: looking for [%s]", __func__, utf8_pattern);
2612 /* Figure out which bit of the pattern is the directory */
2613 dir_part = _wapi_dirname (utf8_pattern);
2614 entry_part = _wapi_basename (utf8_pattern);
2617 /* Don't do this check for now, it breaks if directories
2618 * really do have metachars in their names (see bug 58116).
2619 * FIXME: Figure out a better solution to keep some checks...
2621 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2622 SetLastError (ERROR_INVALID_NAME);
2624 g_free (entry_part);
2625 g_free (utf8_pattern);
2626 return(INVALID_HANDLE_VALUE);
2630 /* The pattern can specify a directory or a set of files.
2632 * The pattern can have wildcard characters ? and *, but only
2633 * in the section after the last directory delimiter. (Return
2634 * ERROR_INVALID_NAME if there are wildcards in earlier path
2635 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2636 * means "match one character", "??" seems to mean "match one
2637 * or two characters", "???" seems to mean "match one, two or
2638 * three characters", etc. Windows will also try and match
2639 * the mangled "short name" of files, so 8 character patterns
2640 * with wildcards will show some surprising results.
2642 * All the written documentation I can find says that '?'
2643 * should only match one character, and doesn't mention '??',
2644 * '???' etc. I'm going to assume that the strict behaviour
2645 * (ie '???' means three and only three characters) is the
2646 * correct one, because that lets me use fnmatch(3) rather
2647 * than mess around with regexes.
2650 find_handle.namelist = NULL;
2651 result = _wapi_io_scandir (dir_part, entry_part,
2652 &find_handle.namelist);
2655 /* No files, which windows seems to call
2658 SetLastError (ERROR_FILE_NOT_FOUND);
2659 g_free (utf8_pattern);
2660 g_free (entry_part);
2662 return (INVALID_HANDLE_VALUE);
2666 #ifdef DEBUG_ENABLED
2667 gint errnum = errno;
2669 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2670 DEBUG ("%s: scandir error: %s", __func__,
2671 g_strerror (errnum));
2672 g_free (utf8_pattern);
2673 g_free (entry_part);
2675 return (INVALID_HANDLE_VALUE);
2678 g_free (utf8_pattern);
2679 g_free (entry_part);
2681 DEBUG ("%s: Got %d matches", __func__, result);
2683 find_handle.dir_part = dir_part;
2684 find_handle.num = result;
2685 find_handle.count = 0;
2687 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2688 if (handle == _WAPI_HANDLE_INVALID) {
2689 g_warning ("%s: error creating find handle", __func__);
2691 g_free (entry_part);
2692 g_free (utf8_pattern);
2693 SetLastError (ERROR_GEN_FAILURE);
2695 return(INVALID_HANDLE_VALUE);
2698 if (handle != INVALID_HANDLE_VALUE &&
2699 !FindNextFile (handle, find_data)) {
2701 SetLastError (ERROR_NO_MORE_FILES);
2702 handle = INVALID_HANDLE_VALUE;
2708 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2710 struct _WapiHandle_find *find_handle;
2712 struct stat buf, linkbuf;
2715 gchar *utf8_filename, *utf8_basename;
2716 gunichar2 *utf16_basename;
2720 gboolean ret = FALSE;
2722 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2723 (gpointer *)&find_handle);
2725 g_warning ("%s: error looking up find handle %p", __func__,
2727 SetLastError (ERROR_INVALID_HANDLE);
2731 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2733 thr_ret = _wapi_handle_lock_handle (handle);
2734 g_assert (thr_ret == 0);
2737 if (find_handle->count >= find_handle->num) {
2738 SetLastError (ERROR_NO_MORE_FILES);
2742 /* stat next match */
2744 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2746 result = _wapi_stat (filename, &buf);
2747 if (result == -1 && errno == ENOENT) {
2748 /* Might be a dangling symlink */
2749 result = _wapi_lstat (filename, &buf);
2753 DEBUG ("%s: stat failed: %s", __func__, filename);
2759 #ifndef __native_client__
2760 result = _wapi_lstat (filename, &linkbuf);
2762 DEBUG ("%s: lstat failed: %s", __func__, filename);
2769 utf8_filename = mono_utf8_from_external (filename);
2770 if (utf8_filename == NULL) {
2771 /* We couldn't turn this filename into utf8 (eg the
2772 * encoding of the name wasn't convertible), so just
2775 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2782 DEBUG ("%s: Found [%s]", __func__, utf8_filename);
2784 /* fill data block */
2786 if (buf.st_mtime < buf.st_ctime)
2787 create_time = buf.st_mtime;
2789 create_time = buf.st_ctime;
2791 #ifdef __native_client__
2792 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, NULL);
2794 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2797 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2798 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2799 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2801 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2802 find_data->nFileSizeHigh = 0;
2803 find_data->nFileSizeLow = 0;
2805 find_data->nFileSizeHigh = buf.st_size >> 32;
2806 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2809 find_data->dwReserved0 = 0;
2810 find_data->dwReserved1 = 0;
2812 utf8_basename = _wapi_basename (utf8_filename);
2813 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2815 if(utf16_basename==NULL) {
2816 g_free (utf8_basename);
2817 g_free (utf8_filename);
2822 /* utf16 is 2 * utf8 */
2825 memset (find_data->cFileName, '\0', (MAX_PATH*2));
2827 /* Truncating a utf16 string like this might leave the last
2830 memcpy (find_data->cFileName, utf16_basename,
2831 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
2833 find_data->cAlternateFileName [0] = 0; /* not used */
2835 g_free (utf8_basename);
2836 g_free (utf8_filename);
2837 g_free (utf16_basename);
2840 thr_ret = _wapi_handle_unlock_handle (handle);
2841 g_assert (thr_ret == 0);
2842 pthread_cleanup_pop (0);
2849 * @wapi_handle: the find handle to close.
2851 * Closes find handle @wapi_handle
2853 * Return value: %TRUE on success, %FALSE otherwise.
2855 gboolean FindClose (gpointer handle)
2857 struct _WapiHandle_find *find_handle;
2861 if (handle == NULL) {
2862 SetLastError (ERROR_INVALID_HANDLE);
2866 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2867 (gpointer *)&find_handle);
2869 g_warning ("%s: error looking up find handle %p", __func__,
2871 SetLastError (ERROR_INVALID_HANDLE);
2875 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2877 thr_ret = _wapi_handle_lock_handle (handle);
2878 g_assert (thr_ret == 0);
2880 g_strfreev (find_handle->namelist);
2881 g_free (find_handle->dir_part);
2883 thr_ret = _wapi_handle_unlock_handle (handle);
2884 g_assert (thr_ret == 0);
2885 pthread_cleanup_pop (0);
2887 _wapi_handle_unref (handle);
2894 * @name: a pointer to a NULL-terminated unicode string, that names
2895 * the directory to be created.
2896 * @security: ignored for now
2898 * Creates directory @name
2900 * Return value: %TRUE on success, %FALSE otherwise.
2902 gboolean CreateDirectory (const gunichar2 *name,
2903 WapiSecurityAttributes *security)
2909 DEBUG("%s: name is NULL", __func__);
2911 SetLastError (ERROR_INVALID_NAME);
2915 utf8_name = mono_unicode_to_external (name);
2916 if (utf8_name == NULL) {
2917 DEBUG ("%s: unicode conversion returned NULL", __func__);
2919 SetLastError (ERROR_INVALID_NAME);
2923 result = _wapi_mkdir (utf8_name, 0777);
2930 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2937 * @name: a pointer to a NULL-terminated unicode string, that names
2938 * the directory to be removed.
2940 * Removes directory @name
2942 * Return value: %TRUE on success, %FALSE otherwise.
2944 gboolean RemoveDirectory (const gunichar2 *name)
2950 DEBUG("%s: name is NULL", __func__);
2952 SetLastError (ERROR_INVALID_NAME);
2956 utf8_name = mono_unicode_to_external (name);
2957 if (utf8_name == NULL) {
2958 DEBUG ("%s: unicode conversion returned NULL", __func__);
2960 SetLastError (ERROR_INVALID_NAME);
2964 result = _wapi_rmdir (utf8_name);
2966 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2977 * GetFileAttributes:
2978 * @name: a pointer to a NULL-terminated unicode filename.
2980 * Gets the attributes for @name;
2982 * Return value: %INVALID_FILE_ATTRIBUTES on failure
2984 guint32 GetFileAttributes (const gunichar2 *name)
2987 struct stat buf, linkbuf;
2992 DEBUG("%s: name is NULL", __func__);
2994 SetLastError (ERROR_INVALID_NAME);
2998 utf8_name = mono_unicode_to_external (name);
2999 if (utf8_name == NULL) {
3000 DEBUG ("%s: unicode conversion returned NULL", __func__);
3002 SetLastError (ERROR_INVALID_PARAMETER);
3003 return (INVALID_FILE_ATTRIBUTES);
3006 result = _wapi_stat (utf8_name, &buf);
3007 if (result == -1 && errno == ENOENT) {
3008 /* Might be a dangling symlink... */
3009 result = _wapi_lstat (utf8_name, &buf);
3013 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3015 return (INVALID_FILE_ATTRIBUTES);
3018 #ifndef __native_client__
3019 result = _wapi_lstat (utf8_name, &linkbuf);
3021 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3023 return (INVALID_FILE_ATTRIBUTES);
3027 #ifdef __native_client__
3028 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, NULL);
3030 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3039 * GetFileAttributesEx:
3040 * @name: a pointer to a NULL-terminated unicode filename.
3041 * @level: must be GetFileExInfoStandard
3042 * @info: pointer to a WapiFileAttributesData structure
3044 * Gets attributes, size and filetimes for @name;
3046 * Return value: %TRUE on success, %FALSE on failure
3048 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3051 WapiFileAttributesData *data;
3053 struct stat buf, linkbuf;
3057 if (level != GetFileExInfoStandard) {
3058 DEBUG ("%s: info level %d not supported.", __func__,
3061 SetLastError (ERROR_INVALID_PARAMETER);
3066 DEBUG("%s: name is NULL", __func__);
3068 SetLastError (ERROR_INVALID_NAME);
3072 utf8_name = mono_unicode_to_external (name);
3073 if (utf8_name == NULL) {
3074 DEBUG ("%s: unicode conversion returned NULL", __func__);
3076 SetLastError (ERROR_INVALID_PARAMETER);
3080 result = _wapi_stat (utf8_name, &buf);
3081 if (result == -1 && errno == ENOENT) {
3082 /* Might be a dangling symlink... */
3083 result = _wapi_lstat (utf8_name, &buf);
3087 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3092 result = _wapi_lstat (utf8_name, &linkbuf);
3094 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3099 /* fill data block */
3101 data = (WapiFileAttributesData *)info;
3103 if (buf.st_mtime < buf.st_ctime)
3104 create_time = buf.st_mtime;
3106 create_time = buf.st_ctime;
3108 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3114 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3115 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3116 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3118 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3119 data->nFileSizeHigh = 0;
3120 data->nFileSizeLow = 0;
3123 data->nFileSizeHigh = buf.st_size >> 32;
3124 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3132 * @name: name of file
3133 * @attrs: attributes to set
3135 * Changes the attributes on a named file.
3137 * Return value: %TRUE on success, %FALSE on failure.
3139 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3141 /* FIXME: think of something clever to do on unix */
3147 * Currently we only handle one *internal* case, with a value that is
3148 * not standard: 0x80000000, which means `set executable bit'
3152 DEBUG("%s: name is NULL", __func__);
3154 SetLastError (ERROR_INVALID_NAME);
3158 utf8_name = mono_unicode_to_external (name);
3159 if (utf8_name == NULL) {
3160 DEBUG ("%s: unicode conversion returned NULL", __func__);
3162 SetLastError (ERROR_INVALID_NAME);
3166 result = _wapi_stat (utf8_name, &buf);
3167 if (result == -1 && errno == ENOENT) {
3168 /* Might be a dangling symlink... */
3169 result = _wapi_lstat (utf8_name, &buf);
3173 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3178 /* Contrary to the documentation, ms allows NORMAL to be
3179 * specified along with other attributes, so dont bother to
3180 * catch that case here.
3182 if (attrs & FILE_ATTRIBUTE_READONLY) {
3183 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3185 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3188 /* Ignore the other attributes for now */
3190 if (attrs & 0x80000000){
3191 mode_t exec_mask = 0;
3193 if ((buf.st_mode & S_IRUSR) != 0)
3194 exec_mask |= S_IXUSR;
3196 if ((buf.st_mode & S_IRGRP) != 0)
3197 exec_mask |= S_IXGRP;
3199 if ((buf.st_mode & S_IROTH) != 0)
3200 exec_mask |= S_IXOTH;
3202 result = chmod (utf8_name, buf.st_mode | exec_mask);
3204 /* Don't bother to reset executable (might need to change this
3214 * GetCurrentDirectory
3215 * @length: size of the buffer
3216 * @buffer: pointer to buffer that recieves path
3218 * Retrieves the current directory for the current process.
3220 * Return value: number of characters in buffer on success, zero on failure
3222 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3224 gunichar2 *utf16_path;
3228 #ifdef __native_client__
3229 gchar *path = g_get_current_dir ();
3230 if (length < strlen(path) + 1 || path == NULL)
3232 memcpy (buffer, path, strlen(path) + 1);
3234 if (getcwd ((char*)buffer, length) == NULL) {
3235 if (errno == ERANGE) { /*buffer length is not big enough */
3236 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*/
3239 utf16_path = mono_unicode_from_external (path, &bytes);
3240 g_free (utf16_path);
3244 _wapi_set_last_error_from_errno ();
3249 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3250 count = (bytes/2)+1;
3251 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3253 /* Add the terminator */
3254 memset (buffer, '\0', bytes+2);
3255 memcpy (buffer, utf16_path, bytes);
3257 g_free (utf16_path);
3263 * SetCurrentDirectory
3264 * @path: path to new directory
3266 * Changes the directory path for the current process.
3268 * Return value: %TRUE on success, %FALSE on failure.
3270 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3276 SetLastError (ERROR_INVALID_PARAMETER);
3280 utf8_path = mono_unicode_to_external (path);
3281 if (_wapi_chdir (utf8_path) != 0) {
3282 _wapi_set_last_error_from_errno ();
3292 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3293 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3295 struct _WapiHandle_file pipe_read_handle = {0};
3296 struct _WapiHandle_file pipe_write_handle = {0};
3297 gpointer read_handle;
3298 gpointer write_handle;
3302 mono_once (&io_ops_once, io_ops_init);
3304 DEBUG ("%s: Creating pipe", __func__);
3308 DEBUG ("%s: Error creating pipe: %s", __func__,
3311 _wapi_set_last_error_from_errno ();
3315 if (filedes[0] >= _wapi_fd_reserve ||
3316 filedes[1] >= _wapi_fd_reserve) {
3317 DEBUG ("%s: File descriptor is too big", __func__);
3319 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3327 /* filedes[0] is open for reading, filedes[1] for writing */
3329 pipe_read_handle.fd = filedes [0];
3330 pipe_read_handle.fileaccess = GENERIC_READ;
3331 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3333 if (read_handle == _WAPI_HANDLE_INVALID) {
3334 g_warning ("%s: error creating pipe read handle", __func__);
3337 SetLastError (ERROR_GEN_FAILURE);
3342 pipe_write_handle.fd = filedes [1];
3343 pipe_write_handle.fileaccess = GENERIC_WRITE;
3344 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3345 &pipe_write_handle);
3346 if (write_handle == _WAPI_HANDLE_INVALID) {
3347 g_warning ("%s: error creating pipe write handle", __func__);
3348 _wapi_handle_unref (read_handle);
3352 SetLastError (ERROR_GEN_FAILURE);
3357 *readpipe = read_handle;
3358 *writepipe = write_handle;
3360 DEBUG ("%s: Returning pipe: read handle %p, write handle %p",
3361 __func__, read_handle, write_handle);
3366 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3368 gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3369 gunichar2 *tmpdir16=NULL;
3374 if(tmpdir[strlen (tmpdir)]!='/') {
3376 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3379 tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3380 if(tmpdir16==NULL) {
3387 DEBUG ("%s: Size %d smaller than needed (%ld)",
3388 __func__, len, dirlen+1);
3392 /* Add the terminator */
3393 memset (buf, '\0', bytes+2);
3394 memcpy (buf, tmpdir16, bytes);
3400 if(tmpdir16!=NULL) {
3408 #ifdef HAVE_GETFSSTAT
3409 /* Darwin has getfsstat */
3410 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3412 struct statfs *stats;
3415 glong length, total = 0;
3417 n = getfsstat (NULL, 0, MNT_NOWAIT);
3420 size = n * sizeof (struct statfs);
3421 stats = (struct statfs *) g_malloc (size);
3424 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3428 for (i = 0; i < n; i++){
3429 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3430 if (total + length < len){
3431 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3432 buf [total+length] = 0;
3435 total += length + 1;
3444 /* In-place octal sequence replacement */
3446 unescape_octal (gchar *str)
3455 while (*rptr != '\0') {
3456 if (*rptr == '\\') {
3459 c = (*(rptr++) - '0') << 6;
3460 c += (*(rptr++) - '0') << 3;
3461 c += *(rptr++) - '0';
3463 } else if (wptr != rptr) {
3471 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3474 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3475 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3476 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3481 guint32 buffer_index;
3482 guint32 mountpoint_index;
3483 guint32 field_number;
3484 guint32 allocated_size;
3485 guint32 fsname_index;
3486 guint32 fstype_index;
3487 gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3488 gchar *mountpoint_allocated;
3489 gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3490 gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3491 gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3494 gboolean check_mount_source;
3495 } LinuxMountInfoParseState;
3497 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3498 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3499 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3500 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3502 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3506 LinuxMountInfoParseState state;
3507 gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3509 memset (buf, 0, len * sizeof (gunichar2));
3510 fd = open ("/proc/self/mountinfo", O_RDONLY);
3512 parser = GetLogicalDriveStrings_MountInfo;
3514 fd = open ("/proc/mounts", O_RDONLY);
3516 parser = GetLogicalDriveStrings_Mounts;
3520 ret = GetLogicalDriveStrings_Mtab (len, buf);
3524 memset (&state, 0, sizeof (LinuxMountInfoParseState));
3525 state.field_number = 1;
3526 state.delimiter = ' ';
3528 while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3529 state.buffer_index = 0;
3531 while ((*parser)(len, buf, &state)) {
3532 if (state.buffer [state.buffer_index] == '\n') {
3533 gboolean quit = add_drive_string (len, buf, &state);
3534 state.field_number = 1;
3535 state.buffer_index++;
3536 if (state.mountpoint_allocated) {
3537 g_free (state.mountpoint_allocated);
3538 state.mountpoint_allocated = NULL;
3555 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3559 if (state->field_number == 1)
3560 state->check_mount_source = TRUE;
3562 while (state->buffer_index < (guint32)state->nbytes) {
3563 if (state->buffer [state->buffer_index] == state->delimiter) {
3564 state->field_number++;
3565 switch (state->field_number) {
3567 state->mountpoint_index = 0;
3571 if (state->mountpoint_allocated)
3572 state->mountpoint_allocated [state->mountpoint_index] = 0;
3574 state->mountpoint [state->mountpoint_index] = 0;
3578 ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3580 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3582 state->buffer_index = state->nbytes;
3585 state->buffer_index++;
3587 } else if (state->buffer [state->buffer_index] == '\n')
3590 switch (state->field_number) {
3592 if (state->check_mount_source) {
3593 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3594 /* We can ignore the rest, it's a device
3596 state->check_mount_source = FALSE;
3597 state->fsname [state->fsname_index++] = '/';
3600 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3601 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3606 append_to_mountpoint (state);
3610 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3611 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3615 state->buffer_index++;
3621 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3623 while (state->buffer_index < (guint32)state->nbytes) {
3624 if (state->buffer [state->buffer_index] == state->delimiter) {
3625 state->field_number++;
3626 switch (state->field_number) {
3628 state->mountpoint_index = 0;
3632 if (state->mountpoint_allocated)
3633 state->mountpoint_allocated [state->mountpoint_index] = 0;
3635 state->mountpoint [state->mountpoint_index] = 0;
3639 state->delimiter = '-';
3643 state->delimiter = ' ';
3647 state->check_mount_source = TRUE;
3650 state->buffer_index++;
3652 } else if (state->buffer [state->buffer_index] == '\n')
3655 switch (state->field_number) {
3657 append_to_mountpoint (state);
3661 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3662 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3666 if (state->check_mount_source) {
3667 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3668 /* We can ignore the rest, it's a device
3670 state->check_mount_source = FALSE;
3671 state->fsname [state->fsname_index++] = '/';
3674 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3675 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3680 state->buffer_index++;
3687 append_to_mountpoint (LinuxMountInfoParseState *state)
3689 gchar ch = state->buffer [state->buffer_index];
3690 if (state->mountpoint_allocated) {
3691 if (state->mountpoint_index >= state->allocated_size) {
3692 guint32 newsize = (state->allocated_size << 1) + 1;
3693 gchar *newbuf = g_malloc0 (newsize * sizeof (gchar));
3695 memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3696 g_free (state->mountpoint_allocated);
3697 state->mountpoint_allocated = newbuf;
3698 state->allocated_size = newsize;
3700 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3702 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3703 state->allocated_size = (state->mountpoint_index << 1) + 1;
3704 state->mountpoint_allocated = g_malloc0 (state->allocated_size * sizeof (gchar));
3705 memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3706 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3708 state->mountpoint [state->mountpoint_index++] = ch;
3713 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3715 gboolean quit = FALSE;
3716 gboolean ignore_entry;
3718 if (state->fsname_index == 1 && state->fsname [0] == '/')
3719 ignore_entry = FALSE;
3720 else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0)
3721 ignore_entry = TRUE;
3722 else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3723 /* Ignore GNOME's gvfs */
3724 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3725 ignore_entry = TRUE;
3727 ignore_entry = FALSE;
3729 ignore_entry = TRUE;
3731 if (!ignore_entry) {
3734 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3736 unescape_octal (mountpoint);
3737 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3738 if (state->total + length + 1 > len) {
3740 state->total = len * 2;
3743 memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3744 state->total += length;
3748 state->fsname_index = 0;
3749 state->fstype_index = 0;
3755 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3757 return GetLogicalDriveStrings_Mtab (len, buf);
3761 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3764 gunichar2 *ptr, *dir;
3765 glong length, total = 0;
3769 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3774 /* Sigh, mntent and friends don't work well.
3775 * It stops on the first line that doesn't begin with a '/'.
3776 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3777 fp = fopen ("/etc/mtab", "rt");
3779 fp = fopen ("/etc/mnttab", "rt");
3785 while (fgets (buffer, 512, fp) != NULL) {
3789 splitted = g_strsplit (buffer, " ", 0);
3790 if (!*splitted || !*(splitted + 1)) {
3791 g_strfreev (splitted);
3795 unescape_octal (*(splitted + 1));
3796 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3797 g_strfreev (splitted);
3798 if (total + length + 1 > len) {
3801 return len * 2; /* guess */
3804 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3806 total += length + 1;
3811 /* Commented out, does not work with my mtab!!! - Gonz */
3812 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3816 gunichar2 *ptr, *dir;
3817 glong len, total = 0;
3820 fp = setmntent ("/etc/mtab", "rt");
3822 fp = setmntent ("/etc/mnttab", "rt");
3828 while ((mnt = getmntent (fp)) != NULL) {
3829 g_print ("GOT %s\n", mnt->mnt_dir);
3830 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3831 if (total + len + 1 > len) {
3832 return len * 2; /* guess */
3835 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3847 #if (defined(HAVE_STATVFS) || defined(HAVE_STATFS)) && !defined(PLATFORM_ANDROID)
3848 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3849 WapiULargeInteger *total_number_of_bytes,
3850 WapiULargeInteger *total_number_of_free_bytes)
3853 struct statvfs fsstat;
3854 #elif defined(HAVE_STATFS)
3855 struct statfs fsstat;
3857 gboolean isreadonly;
3858 gchar *utf8_path_name;
3860 unsigned long block_size;
3862 if (path_name == NULL) {
3863 utf8_path_name = g_strdup (g_get_current_dir());
3864 if (utf8_path_name == NULL) {
3865 SetLastError (ERROR_DIRECTORY);
3870 utf8_path_name = mono_unicode_to_external (path_name);
3871 if (utf8_path_name == NULL) {
3872 DEBUG("%s: unicode conversion returned NULL", __func__);
3874 SetLastError (ERROR_INVALID_NAME);
3881 ret = statvfs (utf8_path_name, &fsstat);
3882 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
3883 block_size = fsstat.f_frsize;
3884 #elif defined(HAVE_STATFS)
3885 ret = statfs (utf8_path_name, &fsstat);
3886 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
3887 block_size = fsstat.f_bsize;
3889 } while(ret == -1 && errno == EINTR);
3891 g_free(utf8_path_name);
3894 _wapi_set_last_error_from_errno ();
3895 DEBUG ("%s: statvfs failed: %s", __func__, strerror (errno));
3899 /* total number of free bytes for non-root */
3900 if (free_bytes_avail != NULL) {
3902 free_bytes_avail->QuadPart = 0;
3905 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
3909 /* total number of bytes available for non-root */
3910 if (total_number_of_bytes != NULL) {
3911 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
3914 /* total number of bytes available for root */
3915 if (total_number_of_free_bytes != NULL) {
3917 total_number_of_free_bytes->QuadPart = 0;
3920 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
3927 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3928 WapiULargeInteger *total_number_of_bytes,
3929 WapiULargeInteger *total_number_of_free_bytes)
3931 if (free_bytes_avail != NULL) {
3932 free_bytes_avail->QuadPart = (guint64) -1;
3935 if (total_number_of_bytes != NULL) {
3936 total_number_of_bytes->QuadPart = (guint64) -1;
3939 if (total_number_of_free_bytes != NULL) {
3940 total_number_of_free_bytes->QuadPart = (guint64) -1;
3948 * General Unix support
3953 const long fstypeid;
3955 const gchar* fstype;
3958 static _wapi_drive_type _wapi_drive_types[] = {
3960 { DRIVE_REMOTE, "afp" },
3961 { DRIVE_REMOTE, "autofs" },
3962 { DRIVE_CDROM, "cddafs" },
3963 { DRIVE_CDROM, "cd9660" },
3964 { DRIVE_RAMDISK, "devfs" },
3965 { DRIVE_FIXED, "exfat" },
3966 { DRIVE_RAMDISK, "fdesc" },
3967 { DRIVE_REMOTE, "ftp" },
3968 { DRIVE_FIXED, "hfs" },
3969 { DRIVE_FIXED, "msdos" },
3970 { DRIVE_REMOTE, "nfs" },
3971 { DRIVE_FIXED, "ntfs" },
3972 { DRIVE_REMOTE, "smbfs" },
3973 { DRIVE_FIXED, "udf" },
3974 { DRIVE_REMOTE, "webdav" },
3975 { DRIVE_UNKNOWN, NULL }
3977 { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
3978 { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
3979 { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
3980 { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
3981 { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
3982 { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
3983 { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
3984 { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
3985 { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
3986 { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
3987 { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
3988 { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
3989 { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
3990 { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
3991 { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
3992 { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
3993 { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
3994 { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
3995 { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
3996 { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
3997 { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
3998 { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
3999 { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4000 { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4001 { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4002 { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4003 { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4004 { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4005 { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4006 { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4007 { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4008 { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4009 { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4010 { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4011 { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4012 { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4013 { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4014 { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4015 { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4016 { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4017 { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4018 { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4019 { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4020 { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4021 { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4022 { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4023 { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4024 { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4025 { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4026 { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4027 { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4028 { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4029 { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4030 { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4031 { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4032 { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4033 { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4034 { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4035 { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4036 { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4037 { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4038 { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4039 { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4040 { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4041 { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4042 { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4043 { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4044 { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4045 { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4046 { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4047 { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4048 { DRIVE_UNKNOWN, 0, NULL}
4050 { DRIVE_RAMDISK, "ramfs" },
4051 { DRIVE_RAMDISK, "tmpfs" },
4052 { DRIVE_RAMDISK, "proc" },
4053 { DRIVE_RAMDISK, "sysfs" },
4054 { DRIVE_RAMDISK, "debugfs" },
4055 { DRIVE_RAMDISK, "devpts" },
4056 { DRIVE_RAMDISK, "securityfs" },
4057 { DRIVE_CDROM, "iso9660" },
4058 { DRIVE_FIXED, "ext2" },
4059 { DRIVE_FIXED, "ext3" },
4060 { DRIVE_FIXED, "ext4" },
4061 { DRIVE_FIXED, "sysv" },
4062 { DRIVE_FIXED, "reiserfs" },
4063 { DRIVE_FIXED, "ufs" },
4064 { DRIVE_FIXED, "vfat" },
4065 { DRIVE_FIXED, "msdos" },
4066 { DRIVE_FIXED, "udf" },
4067 { DRIVE_FIXED, "hfs" },
4068 { DRIVE_FIXED, "hpfs" },
4069 { DRIVE_FIXED, "qnx4" },
4070 { DRIVE_FIXED, "ntfs" },
4071 { DRIVE_FIXED, "ntfs-3g" },
4072 { DRIVE_REMOTE, "smbfs" },
4073 { DRIVE_REMOTE, "fuse" },
4074 { DRIVE_REMOTE, "nfs" },
4075 { DRIVE_REMOTE, "nfs4" },
4076 { DRIVE_REMOTE, "cifs" },
4077 { DRIVE_REMOTE, "ncpfs" },
4078 { DRIVE_REMOTE, "coda" },
4079 { DRIVE_REMOTE, "afs" },
4080 { DRIVE_UNKNOWN, NULL }
4085 static guint32 _wapi_get_drive_type(long f_type)
4087 _wapi_drive_type *current;
4089 current = &_wapi_drive_types[0];
4090 while (current->drive_type != DRIVE_UNKNOWN) {
4091 if (current->fstypeid == f_type)
4092 return current->drive_type;
4096 return DRIVE_UNKNOWN;
4099 static guint32 _wapi_get_drive_type(const gchar* fstype)
4101 _wapi_drive_type *current;
4103 current = &_wapi_drive_types[0];
4104 while (current->drive_type != DRIVE_UNKNOWN) {
4105 if (strcmp (current->fstype, fstype) == 0)
4111 return current->drive_type;
4115 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4117 GetDriveTypeFromPath (const char *utf8_root_path_name)
4121 if (statfs (utf8_root_path_name, &buf) == -1)
4122 return DRIVE_UNKNOWN;
4124 return _wapi_get_drive_type (buf.f_fstypename);
4126 return _wapi_get_drive_type (buf.f_type);
4131 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4138 fp = fopen ("/etc/mtab", "rt");
4140 fp = fopen ("/etc/mnttab", "rt");
4142 return(DRIVE_UNKNOWN);
4145 drive_type = DRIVE_NO_ROOT_DIR;
4146 while (fgets (buffer, 512, fp) != NULL) {
4147 splitted = g_strsplit (buffer, " ", 0);
4148 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4149 g_strfreev (splitted);
4153 /* compare given root_path_name with the one from mtab,
4154 if length of utf8_root_path_name is zero it must be the root dir */
4155 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4156 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4157 drive_type = _wapi_get_drive_type (*(splitted + 2));
4158 /* it is possible this path might be mounted again with
4159 a known type...keep looking */
4160 if (drive_type != DRIVE_UNKNOWN) {
4161 g_strfreev (splitted);
4166 g_strfreev (splitted);
4174 guint32 GetDriveType(const gunichar2 *root_path_name)
4176 gchar *utf8_root_path_name;
4179 if (root_path_name == NULL) {
4180 utf8_root_path_name = g_strdup (g_get_current_dir());
4181 if (utf8_root_path_name == NULL) {
4182 return(DRIVE_NO_ROOT_DIR);
4186 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4187 if (utf8_root_path_name == NULL) {
4188 DEBUG("%s: unicode conversion returned NULL", __func__);
4189 return(DRIVE_NO_ROOT_DIR);
4192 /* strip trailing slash for compare below */
4193 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4194 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4197 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4198 g_free (utf8_root_path_name);
4200 return (drive_type);
4204 get_fstypename (gchar *utfpath)
4206 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4209 _wapi_drive_type *current;
4211 if (statfs (utfpath, &stat) == -1)
4214 return g_strdup (stat.f_fstypename);
4216 current = &_wapi_drive_types[0];
4217 while (current->drive_type != DRIVE_UNKNOWN) {
4218 if (stat.f_type == current->fstypeid)
4219 return g_strdup (current->fstype);
4229 /* Linux has struct statfs which has a different layout */
4230 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__)
4232 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4236 gboolean status = FALSE;
4239 // We only support getting the file system type
4240 if (fsbuffer == NULL)
4243 utfpath = mono_unicode_to_external (path);
4244 if ((fstypename = get_fstypename (utfpath)) != NULL){
4245 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4246 if (ret != NULL && len < fsbuffersize){
4247 memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4253 g_free (fstypename);
4262 _wapi_io_init (void)
4264 mono_mutex_init (&stdhandle_mutex);