2 * io.c: File, console and find handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002 Ximian, Inc.
8 * Copyright (c) 2002-2006 Novell, Inc.
18 #include <sys/types.h>
24 #include <mono/io-layer/wapi.h>
25 #include <mono/io-layer/wapi-private.h>
26 #include <mono/io-layer/handles-private.h>
27 #include <mono/io-layer/io-private.h>
28 #include <mono/io-layer/timefuncs-private.h>
29 #include <mono/io-layer/thread-private.h>
30 #include <mono/io-layer/io-portability.h>
31 #include <mono/utils/strenc.h>
35 static gboolean _wapi_lock_file_region (int fd, off_t offset, off_t length);
36 static gboolean _wapi_unlock_file_region (int fd, off_t offset, off_t length);
38 static void file_close (gpointer handle, gpointer data);
39 static WapiFileType file_getfiletype(void);
40 static gboolean file_read(gpointer handle, gpointer buffer,
41 guint32 numbytes, guint32 *bytesread,
42 WapiOverlapped *overlapped);
43 static gboolean file_write(gpointer handle, gconstpointer buffer,
44 guint32 numbytes, guint32 *byteswritten,
45 WapiOverlapped *overlapped);
46 static gboolean file_flush(gpointer handle);
47 static guint32 file_seek(gpointer handle, gint32 movedistance,
48 gint32 *highmovedistance, WapiSeekMethod method);
49 static gboolean file_setendoffile(gpointer handle);
50 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
51 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
52 WapiFileTime *last_access,
53 WapiFileTime *last_write);
54 static gboolean file_setfiletime(gpointer handle,
55 const WapiFileTime *create_time,
56 const WapiFileTime *last_access,
57 const WapiFileTime *last_write);
59 /* File handle is only signalled for overlapped IO */
60 struct _WapiHandleOps _wapi_file_ops = {
61 file_close, /* close */
65 NULL, /* special_wait */
69 void _wapi_file_details (gpointer handle_info)
71 struct _WapiHandle_file *file = (struct _WapiHandle_file *)handle_info;
73 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
75 file->fileaccess&GENERIC_READ?'R':'.',
76 file->fileaccess&GENERIC_WRITE?'W':'.',
77 file->fileaccess&GENERIC_EXECUTE?'X':'.',
78 file->sharemode&FILE_SHARE_READ?'R':'.',
79 file->sharemode&FILE_SHARE_WRITE?'W':'.',
80 file->sharemode&FILE_SHARE_DELETE?'D':'.',
84 static void console_close (gpointer handle, gpointer data);
85 static WapiFileType console_getfiletype(void);
86 static gboolean console_read(gpointer handle, gpointer buffer,
87 guint32 numbytes, guint32 *bytesread,
88 WapiOverlapped *overlapped);
89 static gboolean console_write(gpointer handle, gconstpointer buffer,
90 guint32 numbytes, guint32 *byteswritten,
91 WapiOverlapped *overlapped);
93 /* Console is mostly the same as file, except it can block waiting for
96 struct _WapiHandleOps _wapi_console_ops = {
97 console_close, /* close */
101 NULL, /* special_wait */
105 void _wapi_console_details (gpointer handle_info)
107 _wapi_file_details (handle_info);
110 /* Find handle has no ops.
112 struct _WapiHandleOps _wapi_find_ops = {
117 NULL, /* special_wait */
121 static void pipe_close (gpointer handle, gpointer data);
122 static WapiFileType pipe_getfiletype (void);
123 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
124 guint32 *bytesread, WapiOverlapped *overlapped);
125 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
126 guint32 numbytes, guint32 *byteswritten,
127 WapiOverlapped *overlapped);
131 struct _WapiHandleOps _wapi_pipe_ops = {
132 pipe_close, /* close */
136 NULL, /* special_wait */
140 void _wapi_pipe_details (gpointer handle_info)
142 _wapi_file_details (handle_info);
145 static const struct {
146 /* File, console and pipe handles */
147 WapiFileType (*getfiletype)(void);
149 /* File, console and pipe handles */
150 gboolean (*readfile)(gpointer handle, gpointer buffer,
151 guint32 numbytes, guint32 *bytesread,
152 WapiOverlapped *overlapped);
153 gboolean (*writefile)(gpointer handle, gconstpointer buffer,
154 guint32 numbytes, guint32 *byteswritten,
155 WapiOverlapped *overlapped);
156 gboolean (*flushfile)(gpointer handle);
159 guint32 (*seek)(gpointer handle, gint32 movedistance,
160 gint32 *highmovedistance, WapiSeekMethod method);
161 gboolean (*setendoffile)(gpointer handle);
162 guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
163 gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
164 WapiFileTime *last_access,
165 WapiFileTime *last_write);
166 gboolean (*setfiletime)(gpointer handle,
167 const WapiFileTime *create_time,
168 const WapiFileTime *last_access,
169 const WapiFileTime *last_write);
170 } io_ops[WAPI_HANDLE_COUNT]={
171 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
174 file_read, file_write,
175 file_flush, file_seek,
181 {console_getfiletype,
184 NULL, NULL, NULL, NULL, NULL, NULL},
186 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
188 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
190 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
192 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
193 /* socket (will need at least read and write) */
194 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
196 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
198 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
203 NULL, NULL, NULL, NULL, NULL, NULL},
206 static mono_once_t io_ops_once=MONO_ONCE_INIT;
207 static gboolean lock_while_writing = FALSE;
209 static void io_ops_init (void)
211 /* _wapi_handle_register_capabilities (WAPI_HANDLE_FILE, */
212 /* WAPI_HANDLE_CAP_WAIT); */
213 /* _wapi_handle_register_capabilities (WAPI_HANDLE_CONSOLE, */
214 /* WAPI_HANDLE_CAP_WAIT); */
216 if (g_getenv ("MONO_STRICT_IO_EMULATION") != NULL) {
217 lock_while_writing = TRUE;
221 /* Some utility functions.
224 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
231 /* FIXME: this could definitely be better, but there seems to
232 * be no pattern to the attributes that are set
235 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
236 if (S_ISSOCK (buf->st_mode))
237 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
239 filename = _wapi_basename (pathname);
241 if (S_ISDIR (buf->st_mode)) {
242 attrs = FILE_ATTRIBUTE_DIRECTORY;
243 if (!(buf->st_mode & S_IWUSR)) {
244 attrs |= FILE_ATTRIBUTE_READONLY;
246 if (filename[0] == '.') {
247 attrs |= FILE_ATTRIBUTE_HIDDEN;
250 if (!(buf->st_mode & S_IWUSR)) {
251 attrs = FILE_ATTRIBUTE_READONLY;
253 if (filename[0] == '.') {
254 attrs |= FILE_ATTRIBUTE_HIDDEN;
256 } else if (filename[0] == '.') {
257 attrs = FILE_ATTRIBUTE_HIDDEN;
259 attrs = FILE_ATTRIBUTE_NORMAL;
264 if (S_ISLNK (lbuf->st_mode)) {
265 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
275 _wapi_set_last_error_from_errno (void)
277 SetLastError (_wapi_get_win32_file_error (errno));
280 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
283 if (errno == ENOENT) {
284 /* Check the path - if it's a missing directory then
285 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
291 dirname = _wapi_dirname (path);
293 dirname = g_strdup (dir);
296 if (_wapi_access (dirname, F_OK) == 0) {
297 SetLastError (ERROR_FILE_NOT_FOUND);
299 SetLastError (ERROR_PATH_NOT_FOUND);
304 _wapi_set_last_error_from_errno ();
310 static void file_close (gpointer handle, gpointer data)
312 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
315 g_message("%s: closing file handle %p [%s]", __func__, handle,
316 file_handle->filename);
319 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
320 _wapi_unlink (file_handle->filename);
322 g_free (file_handle->filename);
324 _wapi_handle_share_release (file_handle->share_info);
326 close (GPOINTER_TO_UINT(handle));
329 static WapiFileType file_getfiletype(void)
331 return(FILE_TYPE_DISK);
334 static gboolean file_read(gpointer handle, gpointer buffer,
335 guint32 numbytes, guint32 *bytesread,
336 WapiOverlapped *overlapped)
338 struct _WapiHandle_file *file_handle;
340 int fd = GPOINTER_TO_UINT(handle);
343 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
344 (gpointer *)&file_handle);
346 g_warning ("%s: error looking up file handle %p", __func__,
348 SetLastError (ERROR_INVALID_HANDLE);
352 if(bytesread!=NULL) {
356 if(!(file_handle->fileaccess & GENERIC_READ) &&
357 !(file_handle->fileaccess & GENERIC_ALL)) {
359 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
360 __func__, handle, file_handle->fileaccess);
363 SetLastError (ERROR_ACCESS_DENIED);
368 ret = read (fd, buffer, numbytes);
369 } while (ret == -1 && errno == EINTR &&
370 !_wapi_thread_cur_apc_pending());
376 g_message("%s: read of handle %p error: %s", __func__,
377 handle, strerror(err));
379 SetLastError (_wapi_get_win32_file_error (err));
383 if (bytesread != NULL) {
390 static gboolean file_write(gpointer handle, gconstpointer buffer,
391 guint32 numbytes, guint32 *byteswritten,
392 WapiOverlapped *overlapped G_GNUC_UNUSED)
394 struct _WapiHandle_file *file_handle;
397 off_t current_pos = 0;
398 int fd = GPOINTER_TO_UINT(handle);
400 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
401 (gpointer *)&file_handle);
403 g_warning ("%s: error looking up file handle %p", __func__,
405 SetLastError (ERROR_INVALID_HANDLE);
409 if(byteswritten!=NULL) {
413 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
414 !(file_handle->fileaccess & GENERIC_ALL)) {
416 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
419 SetLastError (ERROR_ACCESS_DENIED);
423 if (lock_while_writing) {
424 /* Need to lock the region we're about to write to,
425 * because we only do advisory locking on POSIX
428 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
429 if (current_pos == -1) {
431 g_message ("%s: handle %p lseek failed: %s", __func__,
432 handle, strerror (errno));
434 _wapi_set_last_error_from_errno ();
438 if (_wapi_lock_file_region (fd, current_pos,
439 numbytes) == FALSE) {
440 /* The error has already been set */
446 ret = write (fd, buffer, numbytes);
447 } while (ret == -1 && errno == EINTR &&
448 !_wapi_thread_cur_apc_pending());
450 if (lock_while_writing) {
451 _wapi_unlock_file_region (fd, current_pos, numbytes);
455 if (errno == EINTR) {
458 _wapi_set_last_error_from_errno ();
461 g_message("%s: write of handle %p error: %s",
462 __func__, handle, strerror(errno));
468 if (byteswritten != NULL) {
474 static gboolean file_flush(gpointer handle)
476 struct _WapiHandle_file *file_handle;
479 int fd = GPOINTER_TO_UINT(handle);
481 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
482 (gpointer *)&file_handle);
484 g_warning ("%s: error looking up file handle %p", __func__,
486 SetLastError (ERROR_INVALID_HANDLE);
490 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
491 !(file_handle->fileaccess & GENERIC_ALL)) {
493 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
496 SetLastError (ERROR_ACCESS_DENIED);
503 g_message("%s: fsync of handle %p error: %s", __func__, handle,
507 _wapi_set_last_error_from_errno ();
514 static guint32 file_seek(gpointer handle, gint32 movedistance,
515 gint32 *highmovedistance, WapiSeekMethod method)
517 struct _WapiHandle_file *file_handle;
519 off_t offset, newpos;
522 int fd = GPOINTER_TO_UINT(handle);
524 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
525 (gpointer *)&file_handle);
527 g_warning ("%s: error looking up file handle %p", __func__,
529 SetLastError (ERROR_INVALID_HANDLE);
530 return(INVALID_SET_FILE_POINTER);
533 if(!(file_handle->fileaccess & GENERIC_READ) &&
534 !(file_handle->fileaccess & GENERIC_WRITE) &&
535 !(file_handle->fileaccess & GENERIC_ALL)) {
537 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
540 SetLastError (ERROR_ACCESS_DENIED);
541 return(INVALID_SET_FILE_POINTER);
556 g_message("%s: invalid seek type %d", __func__, method);
559 SetLastError (ERROR_INVALID_PARAMETER);
560 return(INVALID_SET_FILE_POINTER);
563 #ifdef HAVE_LARGE_FILE_SUPPORT
564 if(highmovedistance==NULL) {
567 g_message("%s: setting offset to %lld (low %d)", __func__,
568 offset, movedistance);
571 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
574 g_message("%s: setting offset to %lld 0x%llx (high %d 0x%x, low %d 0x%x)", __func__, offset, offset, *highmovedistance, *highmovedistance, movedistance, movedistance);
582 #ifdef HAVE_LARGE_FILE_SUPPORT
583 g_message("%s: moving handle %p by %lld bytes from %d", __func__,
584 handle, offset, whence);
586 g_message("%s: moving handle %p fd %d by %ld bytes from %d", __func__,
587 handle, offset, whence);
591 newpos=lseek(fd, offset, whence);
594 g_message("%s: lseek on handle %p returned error %s",
595 __func__, handle, strerror(errno));
598 _wapi_set_last_error_from_errno ();
599 return(INVALID_SET_FILE_POINTER);
603 #ifdef HAVE_LARGE_FILE_SUPPORT
604 g_message("%s: lseek returns %lld", __func__, newpos);
606 g_message ("%s: lseek returns %ld", __func__, newpos);
610 #ifdef HAVE_LARGE_FILE_SUPPORT
611 ret=newpos & 0xFFFFFFFF;
612 if(highmovedistance!=NULL) {
613 *highmovedistance=newpos>>32;
617 if(highmovedistance!=NULL) {
618 /* Accurate, but potentially dodgy :-) */
624 g_message ("%s: move of handle %p returning %d/%d", __func__,
625 handle, ret, highmovedistance==NULL?0:*highmovedistance);
631 static gboolean file_setendoffile(gpointer handle)
633 struct _WapiHandle_file *file_handle;
638 int fd = GPOINTER_TO_UINT(handle);
640 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
641 (gpointer *)&file_handle);
643 g_warning ("%s: error looking up file handle %p", __func__,
645 SetLastError (ERROR_INVALID_HANDLE);
649 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
650 !(file_handle->fileaccess & GENERIC_ALL)) {
652 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
655 SetLastError (ERROR_ACCESS_DENIED);
659 /* Find the current file position, and the file length. If
660 * the file position is greater than the length, write to
661 * extend the file with a hole. If the file position is less
662 * than the length, truncate the file.
665 ret=fstat(fd, &statbuf);
668 g_message ("%s: handle %p fstat failed: %s", __func__,
669 handle, strerror(errno));
672 _wapi_set_last_error_from_errno ();
675 size=statbuf.st_size;
677 pos=lseek(fd, (off_t)0, SEEK_CUR);
680 g_message("%s: handle %p lseek failed: %s", __func__,
681 handle, strerror(errno));
684 _wapi_set_last_error_from_errno ();
688 #ifdef FTRUNCATE_DOESNT_EXTEND
689 /* I haven't bothered to write the configure.in stuff for this
690 * because I don't know if any platform needs it. I'm leaving
691 * this code just in case though
694 /* Extend the file. Use write() here, because some
695 * manuals say that ftruncate() behaviour is undefined
696 * when the file needs extending. The POSIX spec says
697 * that on XSI-conformant systems it extends, so if
698 * every system we care about conforms, then we can
702 ret = write (fd, "", 1);
703 } while (ret == -1 && errno == EINTR &&
704 !_wapi_thread_cur_apc_pending());
708 g_message("%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
711 _wapi_set_last_error_from_errno ();
715 /* And put the file position back after the write */
716 ret = lseek (fd, pos, SEEK_SET);
719 g_message ("%s: handle %p second lseek failed: %s",
720 __func__, handle, strerror(errno));
723 _wapi_set_last_error_from_errno ();
729 /* always truncate, because the extend write() adds an extra
730 * byte to the end of the file
733 ret=ftruncate(fd, pos);
735 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
738 g_message("%s: handle %p ftruncate failed: %s", __func__,
739 handle, strerror(errno));
742 _wapi_set_last_error_from_errno ();
749 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
751 struct _WapiHandle_file *file_handle;
756 int fd = GPOINTER_TO_UINT(handle);
758 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
759 (gpointer *)&file_handle);
761 g_warning ("%s: error looking up file handle %p", __func__,
763 SetLastError (ERROR_INVALID_HANDLE);
764 return(INVALID_FILE_SIZE);
767 if(!(file_handle->fileaccess & GENERIC_READ) &&
768 !(file_handle->fileaccess & GENERIC_WRITE) &&
769 !(file_handle->fileaccess & GENERIC_ALL)) {
771 g_message("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
774 SetLastError (ERROR_ACCESS_DENIED);
775 return(INVALID_FILE_SIZE);
778 /* If the file has a size with the low bits 0xFFFFFFFF the
779 * caller can't tell if this is an error, so clear the error
782 SetLastError (ERROR_SUCCESS);
784 ret = fstat(fd, &statbuf);
787 g_message ("%s: handle %p fstat failed: %s", __func__,
788 handle, strerror(errno));
791 _wapi_set_last_error_from_errno ();
792 return(INVALID_FILE_SIZE);
795 #ifdef HAVE_LARGE_FILE_SUPPORT
796 size = statbuf.st_size & 0xFFFFFFFF;
797 if (highsize != NULL) {
798 *highsize = statbuf.st_size>>32;
801 if (highsize != NULL) {
802 /* Accurate, but potentially dodgy :-) */
805 size = statbuf.st_size;
809 g_message ("%s: Returning size %d/%d", __func__, size, *highsize);
815 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
816 WapiFileTime *last_access,
817 WapiFileTime *last_write)
819 struct _WapiHandle_file *file_handle;
822 guint64 create_ticks, access_ticks, write_ticks;
824 int fd = GPOINTER_TO_UINT(handle);
826 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
827 (gpointer *)&file_handle);
829 g_warning ("%s: error looking up file handle %p", __func__,
831 SetLastError (ERROR_INVALID_HANDLE);
835 if(!(file_handle->fileaccess & GENERIC_READ) &&
836 !(file_handle->fileaccess & GENERIC_ALL)) {
838 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
839 __func__, handle, file_handle->fileaccess);
842 SetLastError (ERROR_ACCESS_DENIED);
846 ret=fstat(fd, &statbuf);
849 g_message("%s: handle %p fstat failed: %s", __func__, handle,
853 _wapi_set_last_error_from_errno ();
858 g_message("%s: atime: %ld ctime: %ld mtime: %ld", __func__,
859 statbuf.st_atime, statbuf.st_ctime,
863 /* Try and guess a meaningful create time by using the older
866 /* The magic constant comes from msdn documentation
867 * "Converting a time_t Value to a File Time"
869 if(statbuf.st_atime < statbuf.st_ctime) {
870 create_ticks=((guint64)statbuf.st_atime*10000000)
871 + 116444736000000000ULL;
873 create_ticks=((guint64)statbuf.st_ctime*10000000)
874 + 116444736000000000ULL;
877 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
878 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
881 g_message("%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
882 access_ticks, create_ticks, write_ticks);
885 if(create_time!=NULL) {
886 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
887 create_time->dwHighDateTime = create_ticks >> 32;
890 if(last_access!=NULL) {
891 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
892 last_access->dwHighDateTime = access_ticks >> 32;
895 if(last_write!=NULL) {
896 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
897 last_write->dwHighDateTime = write_ticks >> 32;
903 static gboolean file_setfiletime(gpointer handle,
904 const WapiFileTime *create_time G_GNUC_UNUSED,
905 const WapiFileTime *last_access,
906 const WapiFileTime *last_write)
908 struct _WapiHandle_file *file_handle;
910 struct utimbuf utbuf;
912 guint64 access_ticks, write_ticks;
914 int fd = GPOINTER_TO_UINT(handle);
916 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
917 (gpointer *)&file_handle);
919 g_warning ("%s: error looking up file handle %p", __func__,
921 SetLastError (ERROR_INVALID_HANDLE);
925 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
926 !(file_handle->fileaccess & GENERIC_ALL)) {
928 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
931 SetLastError (ERROR_ACCESS_DENIED);
935 if(file_handle->filename == NULL) {
937 g_message("%s: handle %p unknown filename", __func__, handle);
940 SetLastError (ERROR_INVALID_HANDLE);
944 /* Get the current times, so we can put the same times back in
945 * the event that one of the FileTime structs is NULL
947 ret=fstat (fd, &statbuf);
950 g_message("%s: handle %p fstat failed: %s", __func__, handle,
954 SetLastError (ERROR_INVALID_PARAMETER);
958 if(last_access!=NULL) {
959 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
960 last_access->dwLowDateTime;
961 /* This is (time_t)0. We can actually go to INT_MIN,
962 * but this will do for now.
964 if (access_ticks < 116444736000000000ULL) {
966 g_message ("%s: attempt to set access time too early",
969 SetLastError (ERROR_INVALID_PARAMETER);
973 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
975 utbuf.actime=statbuf.st_atime;
978 if(last_write!=NULL) {
979 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
980 last_write->dwLowDateTime;
981 /* This is (time_t)0. We can actually go to INT_MIN,
982 * but this will do for now.
984 if (write_ticks < 116444736000000000ULL) {
986 g_message ("%s: attempt to set write time too early",
989 SetLastError (ERROR_INVALID_PARAMETER);
993 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
995 utbuf.modtime=statbuf.st_mtime;
999 g_message ("%s: setting handle %p access %ld write %ld", __func__,
1000 handle, utbuf.actime, utbuf.modtime);
1003 ret = _wapi_utime (file_handle->filename, &utbuf);
1006 g_message ("%s: handle %p [%s] utime failed: %s", __func__,
1007 handle, file_handle->filename, strerror(errno));
1010 SetLastError (ERROR_INVALID_PARAMETER);
1017 static void console_close (gpointer handle, gpointer data)
1019 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1022 g_message("%s: closing console handle %p", __func__, handle);
1025 g_free (console_handle->filename);
1027 close (GPOINTER_TO_UINT(handle));
1030 static WapiFileType console_getfiletype(void)
1032 return(FILE_TYPE_CHAR);
1035 static gboolean console_read(gpointer handle, gpointer buffer,
1036 guint32 numbytes, guint32 *bytesread,
1037 WapiOverlapped *overlapped G_GNUC_UNUSED)
1039 struct _WapiHandle_file *console_handle;
1042 int fd = GPOINTER_TO_UINT(handle);
1044 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1045 (gpointer *)&console_handle);
1047 g_warning ("%s: error looking up console handle %p", __func__,
1049 SetLastError (ERROR_INVALID_HANDLE);
1053 if(bytesread!=NULL) {
1057 if(!(console_handle->fileaccess & GENERIC_READ) &&
1058 !(console_handle->fileaccess & GENERIC_ALL)) {
1060 g_message ("%s: handle %p doesn't have GENERIC_READ access: %u",
1061 __func__, handle, console_handle->fileaccess);
1064 SetLastError (ERROR_ACCESS_DENIED);
1069 ret=read(fd, buffer, numbytes);
1070 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1074 g_message("%s: read of handle %p error: %s", __func__, handle,
1078 _wapi_set_last_error_from_errno ();
1082 if(bytesread!=NULL) {
1089 static gboolean console_write(gpointer handle, gconstpointer buffer,
1090 guint32 numbytes, guint32 *byteswritten,
1091 WapiOverlapped *overlapped G_GNUC_UNUSED)
1093 struct _WapiHandle_file *console_handle;
1096 int fd = GPOINTER_TO_UINT(handle);
1098 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1099 (gpointer *)&console_handle);
1101 g_warning ("%s: error looking up console handle %p", __func__,
1103 SetLastError (ERROR_INVALID_HANDLE);
1107 if(byteswritten!=NULL) {
1111 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1112 !(console_handle->fileaccess & GENERIC_ALL)) {
1114 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, console_handle->fileaccess);
1117 SetLastError (ERROR_ACCESS_DENIED);
1122 ret = write(fd, buffer, numbytes);
1123 } while (ret == -1 && errno == EINTR &&
1124 !_wapi_thread_cur_apc_pending());
1127 if (errno == EINTR) {
1130 _wapi_set_last_error_from_errno ();
1133 g_message ("%s: write of handle %p error: %s",
1134 __func__, handle, strerror(errno));
1140 if(byteswritten!=NULL) {
1147 static void pipe_close (gpointer handle, gpointer data G_GNUC_UNUSED)
1150 g_message("%s: closing pipe handle %p", __func__, handle);
1153 /* No filename with pipe handles */
1155 close(GPOINTER_TO_UINT(handle));
1158 static WapiFileType pipe_getfiletype(void)
1160 return(FILE_TYPE_PIPE);
1163 static gboolean pipe_read (gpointer handle, gpointer buffer,
1164 guint32 numbytes, guint32 *bytesread,
1165 WapiOverlapped *overlapped G_GNUC_UNUSED)
1167 struct _WapiHandle_file *pipe_handle;
1170 int fd = GPOINTER_TO_UINT(handle);
1172 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1173 (gpointer *)&pipe_handle);
1175 g_warning ("%s: error looking up pipe handle %p", __func__,
1177 SetLastError (ERROR_INVALID_HANDLE);
1181 if(bytesread!=NULL) {
1185 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1186 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1188 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
1189 __func__, handle, pipe_handle->fileaccess);
1192 SetLastError (ERROR_ACCESS_DENIED);
1197 g_message ("%s: reading up to %d bytes from pipe %p", __func__,
1202 ret=read(fd, buffer, numbytes);
1203 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1206 if (errno == EINTR) {
1209 _wapi_set_last_error_from_errno ();
1212 g_message("%s: read of handle %p error: %s", __func__,
1213 handle, strerror(errno));
1221 g_message ("%s: read %d bytes from pipe", __func__, ret);
1224 if(bytesread!=NULL) {
1231 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1232 guint32 numbytes, guint32 *byteswritten,
1233 WapiOverlapped *overlapped G_GNUC_UNUSED)
1235 struct _WapiHandle_file *pipe_handle;
1238 int fd = GPOINTER_TO_UINT(handle);
1240 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1241 (gpointer *)&pipe_handle);
1243 g_warning ("%s: error looking up pipe handle %p", __func__,
1245 SetLastError (ERROR_INVALID_HANDLE);
1249 if(byteswritten!=NULL) {
1253 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1254 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1256 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, pipe_handle->fileaccess);
1259 SetLastError (ERROR_ACCESS_DENIED);
1264 g_message ("%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1269 ret = write (fd, buffer, numbytes);
1270 } while (ret == -1 && errno == EINTR &&
1271 !_wapi_thread_cur_apc_pending());
1274 if (errno == EINTR) {
1277 _wapi_set_last_error_from_errno ();
1280 g_message("%s: write of handle %p error: %s", __func__,
1281 handle, strerror(errno));
1287 if(byteswritten!=NULL) {
1294 static int convert_flags(guint32 fileaccess, guint32 createmode)
1298 switch(fileaccess) {
1305 case GENERIC_READ|GENERIC_WRITE:
1310 g_message("%s: Unknown access type 0x%x", __func__,
1316 switch(createmode) {
1318 flags|=O_CREAT|O_EXCL;
1321 flags|=O_CREAT|O_TRUNC;
1328 case TRUNCATE_EXISTING:
1333 g_message("%s: Unknown create mode 0x%x", __func__,
1342 static guint32 convert_from_flags(int flags)
1344 guint32 fileaccess=0;
1347 #define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR)
1350 if((flags & O_ACCMODE) == O_RDONLY) {
1351 fileaccess=GENERIC_READ;
1352 } else if ((flags & O_ACCMODE) == O_WRONLY) {
1353 fileaccess=GENERIC_WRITE;
1354 } else if ((flags & O_ACCMODE) == O_RDWR) {
1355 fileaccess=GENERIC_READ|GENERIC_WRITE;
1358 g_message("%s: Can't figure out flags 0x%x", __func__, flags);
1362 /* Maybe sort out create mode too */
1368 static mode_t convert_perms(guint32 sharemode)
1372 if(sharemode&FILE_SHARE_READ) {
1375 if(sharemode&FILE_SHARE_WRITE) {
1383 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1385 struct _WapiFileShare **share_info)
1387 gboolean file_already_shared;
1388 guint32 file_existing_share, file_existing_access;
1390 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);
1392 if (file_already_shared) {
1393 /* The reference to this share info was incremented
1394 * when we looked it up, so be careful to put it back
1395 * if we conclude we can't use this file.
1397 if (file_existing_share == 0) {
1398 /* Quick and easy, no possibility to share */
1400 g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
1403 _wapi_handle_share_release (*share_info);
1408 if (((file_existing_share == FILE_SHARE_READ) &&
1409 (fileaccess != GENERIC_READ)) ||
1410 ((file_existing_share == FILE_SHARE_WRITE) &&
1411 (fileaccess != GENERIC_WRITE))) {
1412 /* New access mode doesn't match up */
1414 g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
1417 _wapi_handle_share_release (*share_info);
1422 if (((file_existing_access & GENERIC_READ) &&
1423 !(sharemode & FILE_SHARE_READ)) ||
1424 ((file_existing_access & GENERIC_WRITE) &&
1425 !(sharemode & FILE_SHARE_WRITE))) {
1426 /* New share mode doesn't match up */
1428 g_message ("%s: Access mode prevents open: requested share: 0x%x, file has access: 0x%x", __func__, sharemode, file_existing_access);
1431 _wapi_handle_share_release (*share_info);
1437 g_message ("%s: New file!", __func__);
1444 static gboolean share_check (struct stat *statbuf, guint32 sharemode,
1446 struct _WapiFileShare **share_info, int fd)
1448 if (share_allows_open (statbuf, sharemode, fileaccess,
1449 share_info) == TRUE) {
1453 /* Got a share violation. Double check that the file is still
1454 * open by someone, in case a process crashed while still
1455 * holding a file handle. This will also cope with someone
1456 * using Mono.Posix to close the file. This is cheaper and
1457 * less intrusive to other processes than initiating a handle
1461 _wapi_handle_check_share (*share_info, fd);
1462 if (share_allows_open (statbuf, sharemode, fileaccess,
1463 share_info) == TRUE) {
1467 /* Still violating. It's possible that a process crashed
1468 * while still holding a file handle, and that a non-mono
1469 * process has the file open. (For example, C-c mcs while
1470 * editing a source file.) As a last resort, run a handle
1471 * collection, which will remove stale share entries.
1473 _wapi_handle_collect ();
1475 return(share_allows_open (statbuf, sharemode, fileaccess, share_info));
1480 * @name: a pointer to a NULL-terminated unicode string, that names
1481 * the file or other object to create.
1482 * @fileaccess: specifies the file access mode
1483 * @sharemode: whether the file should be shared. This parameter is
1484 * currently ignored.
1485 * @security: Ignored for now.
1486 * @createmode: specifies whether to create a new file, whether to
1487 * overwrite an existing file, whether to truncate the file, etc.
1488 * @attrs: specifies file attributes and flags. On win32 attributes
1489 * are characteristics of the file, not the handle, and are ignored
1490 * when an existing file is opened. Flags give the library hints on
1491 * how to process a file to optimise performance.
1492 * @template: the handle of an open %GENERIC_READ file that specifies
1493 * attributes to apply to a newly created file, ignoring @attrs.
1494 * Normally this parameter is NULL. This parameter is ignored when an
1495 * existing file is opened.
1497 * Creates a new file handle. This only applies to normal files:
1498 * pipes are handled by CreatePipe(), and console handles are created
1499 * with GetStdHandle().
1501 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1503 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1504 guint32 sharemode, WapiSecurityAttributes *security,
1505 guint32 createmode, guint32 attrs,
1506 gpointer template G_GNUC_UNUSED)
1508 struct _WapiHandle_file file_handle = {0};
1510 int flags=convert_flags(fileaccess, createmode);
1511 /*mode_t perms=convert_perms(sharemode);*/
1512 /* we don't use sharemode, because that relates to sharing of
1513 * the file when the file is open and is already handled by
1514 * other code, perms instead are the on-disk permissions and
1515 * this is a sane default.
1521 struct stat statbuf;
1523 mono_once (&io_ops_once, io_ops_init);
1525 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1528 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1529 SetLastError (ERROR_ENCRYPTION_FAILED);
1530 return INVALID_HANDLE_VALUE;
1535 g_message ("%s: name is NULL", __func__);
1538 SetLastError (ERROR_INVALID_NAME);
1539 return(INVALID_HANDLE_VALUE);
1542 filename = mono_unicode_to_external (name);
1543 if (filename == NULL) {
1545 g_message("%s: unicode conversion returned NULL", __func__);
1548 SetLastError (ERROR_INVALID_NAME);
1549 return(INVALID_HANDLE_VALUE);
1553 g_message ("%s: Opening %s with share 0x%x and access 0x%x", __func__,
1554 filename, sharemode, fileaccess);
1557 fd = _wapi_open (filename, flags, perms);
1559 /* If we were trying to open a directory with write permissions
1560 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1561 * EISDIR. However, this is a bit bogus because calls to
1562 * manipulate the directory (e.g. SetFileTime) will still work on
1563 * the directory because they use other API calls
1564 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1565 * to open the directory again without write permission.
1567 if (fd == -1 && errno == EISDIR)
1569 /* Try again but don't try to make it writable */
1570 fd = open(filename, flags & ~(O_RDWR|O_WRONLY), perms);
1575 g_message("%s: Error opening file %s: %s", __func__, filename,
1578 _wapi_set_last_path_error_from_errno (NULL, filename);
1581 return(INVALID_HANDLE_VALUE);
1584 if (fd >= _wapi_fd_reserve) {
1586 g_message ("%s: File descriptor is too big", __func__);
1589 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1594 return(INVALID_HANDLE_VALUE);
1597 ret = fstat (fd, &statbuf);
1600 g_message ("%s: fstat error of file %s: %s", __func__,
1601 filename, strerror (errno));
1603 _wapi_set_last_error_from_errno ();
1607 return(INVALID_HANDLE_VALUE);
1610 if (share_check (&statbuf, sharemode, fileaccess,
1611 &file_handle.share_info, fd) == FALSE) {
1612 SetLastError (ERROR_SHARING_VIOLATION);
1616 return (INVALID_HANDLE_VALUE);
1618 if (file_handle.share_info == NULL) {
1619 /* No space, so no more files can be opened */
1621 g_message ("%s: No space in the share table", __func__);
1624 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1628 return(INVALID_HANDLE_VALUE);
1631 file_handle.filename = filename;
1633 if(security!=NULL) {
1634 //file_handle->security_attributes=_wapi_handle_scratch_store (
1635 //security, sizeof(WapiSecurityAttributes));
1638 file_handle.fileaccess=fileaccess;
1639 file_handle.sharemode=sharemode;
1640 file_handle.attrs=attrs;
1642 #ifdef HAVE_POSIX_FADVISE
1643 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1644 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1645 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1646 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1650 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1652 if (S_ISFIFO (statbuf.st_mode)) {
1653 handle_type = WAPI_HANDLE_PIPE;
1654 } else if (S_ISCHR (statbuf.st_mode)) {
1655 handle_type = WAPI_HANDLE_CONSOLE;
1657 handle_type = WAPI_HANDLE_FILE;
1660 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1661 if (handle == _WAPI_HANDLE_INVALID) {
1662 g_warning ("%s: error creating file handle", __func__);
1666 SetLastError (ERROR_GEN_FAILURE);
1667 return(INVALID_HANDLE_VALUE);
1671 g_message("%s: returning handle %p", __func__, handle);
1679 * @name: a pointer to a NULL-terminated unicode string, that names
1680 * the file to be deleted.
1682 * Deletes file @name.
1684 * Return value: %TRUE on success, %FALSE otherwise.
1686 gboolean DeleteFile(const gunichar2 *name)
1690 gboolean ret = FALSE;
1692 struct stat statbuf;
1693 struct _WapiFileShare *shareinfo;
1697 g_message("%s: name is NULL", __func__);
1700 SetLastError (ERROR_INVALID_NAME);
1704 filename=mono_unicode_to_external(name);
1705 if(filename==NULL) {
1707 g_message("%s: unicode conversion returned NULL", __func__);
1710 SetLastError (ERROR_INVALID_NAME);
1714 attrs = GetFileAttributes (name);
1715 if (attrs == INVALID_FILE_ATTRIBUTES) {
1717 g_message ("%s: file attributes error", __func__);
1719 /* Error set by GetFileAttributes() */
1724 if (attrs & FILE_ATTRIBUTE_READONLY) {
1726 g_message ("%s: file %s is readonly", __func__, filename);
1728 SetLastError (ERROR_ACCESS_DENIED);
1733 /* Check to make sure sharing allows us to open the file for
1734 * writing. See bug 323389.
1736 * Do the checks that don't need an open file descriptor, for
1737 * simplicity's sake. If we really have to do the full checks
1738 * then we can implement that later.
1740 if (_wapi_stat (filename, &statbuf) < 0) {
1741 _wapi_set_last_path_error_from_errno (NULL, filename);
1746 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1747 &shareinfo) == FALSE) {
1748 SetLastError (ERROR_SHARING_VIOLATION);
1752 _wapi_handle_share_release (shareinfo);
1754 retval = _wapi_unlink (filename);
1757 _wapi_set_last_path_error_from_errno (NULL, filename);
1769 * @name: a pointer to a NULL-terminated unicode string, that names
1770 * the file to be moved.
1771 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1772 * new name for the file.
1774 * Renames file @name to @dest_name.
1775 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1776 * when it is the same file as the source. In that case it silently succeeds.
1778 * Return value: %TRUE on success, %FALSE otherwise.
1780 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1782 gchar *utf8_name, *utf8_dest_name;
1783 int result, errno_copy;
1784 struct stat stat_src, stat_dest;
1785 gboolean ret = FALSE;
1786 struct _WapiFileShare *shareinfo;
1790 g_message("%s: name is NULL", __func__);
1793 SetLastError (ERROR_INVALID_NAME);
1797 utf8_name = mono_unicode_to_external (name);
1798 if (utf8_name == NULL) {
1800 g_message ("%s: unicode conversion returned NULL", __func__);
1803 SetLastError (ERROR_INVALID_NAME);
1807 if(dest_name==NULL) {
1809 g_message("%s: name is NULL", __func__);
1813 SetLastError (ERROR_INVALID_NAME);
1817 utf8_dest_name = mono_unicode_to_external (dest_name);
1818 if (utf8_dest_name == NULL) {
1820 g_message ("%s: unicode conversion returned NULL", __func__);
1824 SetLastError (ERROR_INVALID_NAME);
1829 * In C# land we check for the existence of src, but not for dest.
1830 * We check it here and return the failure if dest exists and is not
1831 * the same file as src.
1833 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1834 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1836 g_free (utf8_dest_name);
1840 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1841 if (stat_dest.st_dev != stat_src.st_dev ||
1842 stat_dest.st_ino != stat_src.st_ino) {
1844 g_free (utf8_dest_name);
1845 SetLastError (ERROR_ALREADY_EXISTS);
1850 /* Check to make sure sharing allows us to open the file for
1851 * writing. See bug 377049.
1853 * Do the checks that don't need an open file descriptor, for
1854 * simplicity's sake. If we really have to do the full checks
1855 * then we can implement that later.
1857 if (share_allows_open (&stat_src, 0, GENERIC_WRITE,
1858 &shareinfo) == FALSE) {
1859 SetLastError (ERROR_SHARING_VIOLATION);
1862 _wapi_handle_share_release (shareinfo);
1864 result = _wapi_rename (utf8_name, utf8_dest_name);
1868 switch(errno_copy) {
1870 SetLastError (ERROR_ALREADY_EXISTS);
1874 /* Ignore here, it is dealt with below */
1878 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1883 g_free (utf8_dest_name);
1885 if (result != 0 && errno_copy == EXDEV) {
1886 /* Try a copy to the new location, and delete the source */
1887 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1888 /* CopyFile will set the error */
1892 return(DeleteFile (name));
1903 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1907 int buf_size = st_src->st_blksize;
1909 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1910 buf = (char *) malloc (buf_size);
1913 remain = read (src_fd, buf, buf_size);
1915 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1919 _wapi_set_last_error_from_errno ();
1929 while (remain > 0) {
1930 if ((n = write (dest_fd, wbuf, remain)) < 0) {
1931 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1935 _wapi_set_last_error_from_errno ();
1937 g_message ("%s: write failed.", __func__);
1954 * @name: a pointer to a NULL-terminated unicode string, that names
1955 * the file to be copied.
1956 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1957 * new name for the file.
1958 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1960 * Copies file @name to @dest_name
1962 * Return value: %TRUE on success, %FALSE otherwise.
1964 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1965 gboolean fail_if_exists)
1967 gchar *utf8_src, *utf8_dest;
1968 int src_fd, dest_fd;
1970 gboolean ret = TRUE;
1974 g_message("%s: name is NULL", __func__);
1977 SetLastError (ERROR_INVALID_NAME);
1981 utf8_src = mono_unicode_to_external (name);
1982 if (utf8_src == NULL) {
1984 g_message ("%s: unicode conversion of source returned NULL",
1988 SetLastError (ERROR_INVALID_PARAMETER);
1992 if(dest_name==NULL) {
1994 g_message("%s: name is NULL", __func__);
1998 SetLastError (ERROR_INVALID_NAME);
2002 utf8_dest = mono_unicode_to_external (dest_name);
2003 if (utf8_dest == NULL) {
2005 g_message ("%s: unicode conversion of dest returned NULL",
2009 SetLastError (ERROR_INVALID_PARAMETER);
2016 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2018 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2026 if (fstat (src_fd, &st) < 0) {
2027 _wapi_set_last_error_from_errno ();
2036 if (fail_if_exists) {
2037 dest_fd = open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL,
2040 dest_fd = open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2042 /* O_TRUNC might cause a fail if the file
2045 dest_fd = open (utf8_dest, O_WRONLY | O_CREAT,
2048 /* Apparently this error is set if we
2049 * overwrite the dest file
2051 SetLastError (ERROR_ALREADY_EXISTS);
2055 _wapi_set_last_error_from_errno ();
2064 if (!write_file (src_fd, dest_fd, &st, TRUE))
2076 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2082 g_message ("%s: %s is NULL", __func__, arg_name);
2084 SetLastError (ERROR_INVALID_NAME);
2088 utf8_ret = mono_unicode_to_external (arg);
2089 if (utf8_ret == NULL) {
2091 g_message ("%s: unicode conversion of %s returned NULL",
2092 __func__, arg_name);
2094 SetLastError (ERROR_INVALID_PARAMETER);
2102 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2103 const gunichar2 *backupFileName, guint32 replaceFlags,
2104 gpointer exclude, gpointer reserved)
2106 int result, errno_copy, backup_fd = -1,replaced_fd = -1;
2107 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2108 struct stat stBackup;
2109 gboolean ret = FALSE;
2111 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2113 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2114 goto replace_cleanup;
2115 if (backupFileName != NULL) {
2116 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2117 goto replace_cleanup;
2120 if (utf8_backupFileName) {
2121 // Open the backup file for read so we can restore the file if an error occurs.
2122 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2123 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2126 goto replace_cleanup;
2129 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2132 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2133 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2134 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2135 replaced_fd = open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2137 if (replaced_fd == -1) {
2138 replaced_fd = open (utf8_backupFileName, O_WRONLY | O_CREAT,
2141 if (replaced_fd == -1)
2142 goto replace_cleanup;
2144 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2147 goto replace_cleanup;
2153 g_free (utf8_replacedFileName);
2154 g_free (utf8_replacementFileName);
2155 g_free (utf8_backupFileName);
2156 if (backup_fd != -1)
2158 if (replaced_fd != -1)
2159 close (replaced_fd);
2163 static gpointer stdhandle_create (int fd, const gchar *name)
2165 struct _WapiHandle_file file_handle = {0};
2170 g_message("%s: creating standard handle type %s, fd %d", __func__,
2174 /* Check if fd is valid */
2176 flags=fcntl(fd, F_GETFL);
2177 } while (flags == -1 && errno == EINTR);
2180 /* Invalid fd. Not really much point checking for EBADF
2184 g_message("%s: fcntl error on fd %d: %s", __func__, fd,
2188 _wapi_set_last_error_from_errno ();
2189 return(INVALID_HANDLE_VALUE);
2192 file_handle.filename = g_strdup(name);
2193 /* some default security attributes might be needed */
2194 file_handle.security_attributes=0;
2195 file_handle.fileaccess=convert_from_flags(flags);
2197 /* Apparently input handles can't be written to. (I don't
2198 * know if output or error handles can't be read from.)
2201 file_handle.fileaccess &= ~GENERIC_WRITE;
2204 file_handle.sharemode=0;
2205 file_handle.attrs=0;
2207 handle = _wapi_handle_new_fd (WAPI_HANDLE_CONSOLE, fd, &file_handle);
2208 if (handle == _WAPI_HANDLE_INVALID) {
2209 g_warning ("%s: error creating file handle", __func__);
2210 SetLastError (ERROR_GEN_FAILURE);
2211 return(INVALID_HANDLE_VALUE);
2215 g_message("%s: returning handle %p", __func__, handle);
2223 * @stdhandle: specifies the file descriptor
2225 * Returns a handle for stdin, stdout, or stderr. Always returns the
2226 * same handle for the same @stdhandle.
2228 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2231 static mono_mutex_t stdhandle_mutex = MONO_MUTEX_INITIALIZER;
2233 gpointer GetStdHandle(WapiStdHandle stdhandle)
2235 struct _WapiHandle_file *file_handle;
2242 case STD_INPUT_HANDLE:
2247 case STD_OUTPUT_HANDLE:
2252 case STD_ERROR_HANDLE:
2259 g_message("%s: unknown standard handle type", __func__);
2262 SetLastError (ERROR_INVALID_PARAMETER);
2263 return(INVALID_HANDLE_VALUE);
2266 handle = GINT_TO_POINTER (fd);
2268 pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2269 (void *)&stdhandle_mutex);
2270 thr_ret = mono_mutex_lock (&stdhandle_mutex);
2271 g_assert (thr_ret == 0);
2273 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2274 (gpointer *)&file_handle);
2276 /* Need to create this console handle */
2277 handle = stdhandle_create (fd, name);
2279 if (handle == INVALID_HANDLE_VALUE) {
2280 SetLastError (ERROR_NO_MORE_FILES);
2284 /* Add a reference to this handle */
2285 _wapi_handle_ref (handle);
2289 thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2290 g_assert (thr_ret == 0);
2291 pthread_cleanup_pop (0);
2298 * @handle: The file handle to read from. The handle must have
2299 * %GENERIC_READ access.
2300 * @buffer: The buffer to store read data in
2301 * @numbytes: The maximum number of bytes to read
2302 * @bytesread: The actual number of bytes read is stored here. This
2303 * value can be zero if the handle is positioned at the end of the
2305 * @overlapped: points to a required %WapiOverlapped structure if
2306 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2309 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2310 * function reads up to @numbytes bytes from the file from the current
2311 * file position, and stores them in @buffer. If there are not enough
2312 * bytes left in the file, just the amount available will be read.
2313 * The actual number of bytes read is stored in @bytesread.
2315 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2316 * file position is ignored and the read position is taken from data
2317 * in the @overlapped structure.
2319 * Return value: %TRUE if the read succeeds (even if no bytes were
2320 * read due to an attempt to read past the end of the file), %FALSE on
2323 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2324 guint32 *bytesread, WapiOverlapped *overlapped)
2326 WapiHandleType type;
2328 type = _wapi_handle_type (handle);
2330 if(io_ops[type].readfile==NULL) {
2331 SetLastError (ERROR_INVALID_HANDLE);
2335 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2341 * @handle: The file handle to write to. The handle must have
2342 * %GENERIC_WRITE access.
2343 * @buffer: The buffer to read data from.
2344 * @numbytes: The maximum number of bytes to write.
2345 * @byteswritten: The actual number of bytes written is stored here.
2346 * If the handle is positioned at the file end, the length of the file
2347 * is extended. This parameter may be %NULL.
2348 * @overlapped: points to a required %WapiOverlapped structure if
2349 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2352 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2353 * function writes up to @numbytes bytes from @buffer to the file at
2354 * the current file position. If @handle is positioned at the end of
2355 * the file, the file is extended. The actual number of bytes written
2356 * is stored in @byteswritten.
2358 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2359 * file position is ignored and the write position is taken from data
2360 * in the @overlapped structure.
2362 * Return value: %TRUE if the write succeeds, %FALSE on error.
2364 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2365 guint32 *byteswritten, WapiOverlapped *overlapped)
2367 WapiHandleType type;
2369 type = _wapi_handle_type (handle);
2371 if(io_ops[type].writefile==NULL) {
2372 SetLastError (ERROR_INVALID_HANDLE);
2376 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2382 * @handle: Handle to open file. The handle must have
2383 * %GENERIC_WRITE access.
2385 * Flushes buffers of the file and causes all unwritten data to
2388 * Return value: %TRUE on success, %FALSE otherwise.
2390 gboolean FlushFileBuffers(gpointer handle)
2392 WapiHandleType type;
2394 type = _wapi_handle_type (handle);
2396 if(io_ops[type].flushfile==NULL) {
2397 SetLastError (ERROR_INVALID_HANDLE);
2401 return(io_ops[type].flushfile (handle));
2406 * @handle: The file handle to set. The handle must have
2407 * %GENERIC_WRITE access.
2409 * Moves the end-of-file position to the current position of the file
2410 * pointer. This function is used to truncate or extend a file.
2412 * Return value: %TRUE on success, %FALSE otherwise.
2414 gboolean SetEndOfFile(gpointer handle)
2416 WapiHandleType type;
2418 type = _wapi_handle_type (handle);
2420 if (io_ops[type].setendoffile == NULL) {
2421 SetLastError (ERROR_INVALID_HANDLE);
2425 return(io_ops[type].setendoffile (handle));
2430 * @handle: The file handle to set. The handle must have
2431 * %GENERIC_READ or %GENERIC_WRITE access.
2432 * @movedistance: Low 32 bits of a signed value that specifies the
2433 * number of bytes to move the file pointer.
2434 * @highmovedistance: Pointer to the high 32 bits of a signed value
2435 * that specifies the number of bytes to move the file pointer, or
2437 * @method: The starting point for the file pointer move.
2439 * Sets the file pointer of an open file.
2441 * The distance to move the file pointer is calculated from
2442 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2443 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2444 * is the low 32 bits and @highmovedistance a pointer to the high 32
2445 * bits of a 64 bit signed value. A positive distance moves the file
2446 * pointer forward from the position specified by @method; a negative
2447 * distance moves the file pointer backward.
2449 * If the library is compiled without large file support,
2450 * @highmovedistance is ignored and its value is set to zero on a
2451 * successful return.
2453 * Return value: On success, the low 32 bits of the new file pointer.
2454 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2455 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2457 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2458 gint32 *highmovedistance, WapiSeekMethod method)
2460 WapiHandleType type;
2462 type = _wapi_handle_type (handle);
2464 if (io_ops[type].seek == NULL) {
2465 SetLastError (ERROR_INVALID_HANDLE);
2466 return(INVALID_SET_FILE_POINTER);
2469 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2475 * @handle: The file handle to test.
2477 * Finds the type of file @handle.
2479 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2480 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2481 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2482 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2484 WapiFileType GetFileType(gpointer handle)
2486 WapiHandleType type;
2488 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2489 SetLastError (ERROR_INVALID_HANDLE);
2490 return(FILE_TYPE_UNKNOWN);
2493 type = _wapi_handle_type (handle);
2495 if (io_ops[type].getfiletype == NULL) {
2496 SetLastError (ERROR_INVALID_HANDLE);
2497 return(FILE_TYPE_UNKNOWN);
2500 return(io_ops[type].getfiletype ());
2505 * @handle: The file handle to query. The handle must have
2506 * %GENERIC_READ or %GENERIC_WRITE access.
2507 * @highsize: If non-%NULL, the high 32 bits of the file size are
2510 * Retrieves the size of the file @handle.
2512 * If the library is compiled without large file support, @highsize
2513 * has its value set to zero on a successful return.
2515 * Return value: On success, the low 32 bits of the file size. If
2516 * @highsize is non-%NULL then the high 32 bits of the file size are
2517 * stored here. On failure %INVALID_FILE_SIZE is returned.
2519 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2521 WapiHandleType type;
2523 type = _wapi_handle_type (handle);
2525 if (io_ops[type].getfilesize == NULL) {
2526 SetLastError (ERROR_INVALID_HANDLE);
2527 return(INVALID_FILE_SIZE);
2530 return(io_ops[type].getfilesize (handle, highsize));
2535 * @handle: The file handle to query. The handle must have
2536 * %GENERIC_READ access.
2537 * @create_time: Points to a %WapiFileTime structure to receive the
2538 * number of ticks since the epoch that file was created. May be
2540 * @last_access: Points to a %WapiFileTime structure to receive the
2541 * number of ticks since the epoch when file was last accessed. May be
2543 * @last_write: Points to a %WapiFileTime structure to receive the
2544 * number of ticks since the epoch when file was last written to. May
2547 * Finds the number of ticks since the epoch that the file referenced
2548 * by @handle was created, last accessed and last modified. A tick is
2549 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2552 * Create time isn't recorded on POSIX file systems or reported by
2553 * stat(2), so that time is guessed by returning the oldest of the
2556 * Return value: %TRUE on success, %FALSE otherwise.
2558 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2559 WapiFileTime *last_access, WapiFileTime *last_write)
2561 WapiHandleType type;
2563 type = _wapi_handle_type (handle);
2565 if (io_ops[type].getfiletime == NULL) {
2566 SetLastError (ERROR_INVALID_HANDLE);
2570 return(io_ops[type].getfiletime (handle, create_time, last_access,
2576 * @handle: The file handle to set. The handle must have
2577 * %GENERIC_WRITE access.
2578 * @create_time: Points to a %WapiFileTime structure that contains the
2579 * number of ticks since the epoch that the file was created. May be
2581 * @last_access: Points to a %WapiFileTime structure that contains the
2582 * number of ticks since the epoch when the file was last accessed.
2584 * @last_write: Points to a %WapiFileTime structure that contains the
2585 * number of ticks since the epoch when the file was last written to.
2588 * Sets the number of ticks since the epoch that the file referenced
2589 * by @handle was created, last accessed or last modified. A tick is
2590 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2593 * Create time isn't recorded on POSIX file systems, and is ignored.
2595 * Return value: %TRUE on success, %FALSE otherwise.
2597 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2598 const WapiFileTime *last_access,
2599 const WapiFileTime *last_write)
2601 WapiHandleType type;
2603 type = _wapi_handle_type (handle);
2605 if (io_ops[type].setfiletime == NULL) {
2606 SetLastError (ERROR_INVALID_HANDLE);
2610 return(io_ops[type].setfiletime (handle, create_time, last_access,
2614 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2615 * January 1 1601 GMT
2618 #define TICKS_PER_MILLISECOND 10000L
2619 #define TICKS_PER_SECOND 10000000L
2620 #define TICKS_PER_MINUTE 600000000L
2621 #define TICKS_PER_HOUR 36000000000LL
2622 #define TICKS_PER_DAY 864000000000LL
2624 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2626 static const guint16 mon_yday[2][13]={
2627 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2628 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2632 * FileTimeToSystemTime:
2633 * @file_time: Points to a %WapiFileTime structure that contains the
2634 * number of ticks to convert.
2635 * @system_time: Points to a %WapiSystemTime structure to receive the
2638 * Converts a tick count into broken-out time values.
2640 * Return value: %TRUE on success, %FALSE otherwise.
2642 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2643 WapiSystemTime *system_time)
2645 gint64 file_ticks, totaldays, rem, y;
2648 if(system_time==NULL) {
2650 g_message("%s: system_time NULL", __func__);
2653 SetLastError (ERROR_INVALID_PARAMETER);
2657 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2658 file_time->dwLowDateTime;
2660 /* Really compares if file_ticks>=0x8000000000000000
2661 * (LLONG_MAX+1) but we're working with a signed value for the
2662 * year and day calculation to work later
2666 g_message("%s: file_time too big", __func__);
2669 SetLastError (ERROR_INVALID_PARAMETER);
2673 totaldays=(file_ticks / TICKS_PER_DAY);
2674 rem = file_ticks % TICKS_PER_DAY;
2676 g_message("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2679 system_time->wHour=rem/TICKS_PER_HOUR;
2680 rem %= TICKS_PER_HOUR;
2682 g_message("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2685 system_time->wMinute = rem / TICKS_PER_MINUTE;
2686 rem %= TICKS_PER_MINUTE;
2688 g_message("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2692 system_time->wSecond = rem / TICKS_PER_SECOND;
2693 rem %= TICKS_PER_SECOND;
2695 g_message("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2699 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2701 g_message("%s: Milliseconds: %d", __func__,
2702 system_time->wMilliseconds);
2705 /* January 1, 1601 was a Monday, according to Emacs calendar */
2706 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2708 g_message("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2711 /* This algorithm to find year and month given days from epoch
2716 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2717 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2719 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2720 /* Guess a corrected year, assuming 365 days per year */
2721 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2723 g_message("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2726 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2727 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2730 /* Adjust days and y to match the guessed year. */
2731 totaldays -= ((yg - y) * 365
2732 + LEAPS_THRU_END_OF (yg - 1)
2733 - LEAPS_THRU_END_OF (y - 1));
2735 g_message("%s: totaldays: %lld", __func__, totaldays);
2739 g_message("%s: y: %lld", __func__, y);
2743 system_time->wYear = y;
2745 g_message("%s: Year: %d", __func__, system_time->wYear);
2748 ip = mon_yday[isleap(y)];
2750 for(y=11; totaldays < ip[y]; --y) {
2755 g_message("%s: totaldays: %lld", __func__, totaldays);
2758 system_time->wMonth = y + 1;
2760 g_message("%s: Month: %d", __func__, system_time->wMonth);
2763 system_time->wDay = totaldays + 1;
2765 g_message("%s: Day: %d", __func__, system_time->wDay);
2771 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2773 struct _WapiHandle_find find_handle = {0};
2775 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2778 if (pattern == NULL) {
2780 g_message ("%s: pattern is NULL", __func__);
2783 SetLastError (ERROR_PATH_NOT_FOUND);
2784 return(INVALID_HANDLE_VALUE);
2787 utf8_pattern = mono_unicode_to_external (pattern);
2788 if (utf8_pattern == NULL) {
2790 g_message ("%s: unicode conversion returned NULL", __func__);
2793 SetLastError (ERROR_INVALID_NAME);
2794 return(INVALID_HANDLE_VALUE);
2798 g_message ("%s: looking for [%s]", __func__, utf8_pattern);
2801 /* Figure out which bit of the pattern is the directory */
2802 dir_part = _wapi_dirname (utf8_pattern);
2803 entry_part = _wapi_basename (utf8_pattern);
2806 /* Don't do this check for now, it breaks if directories
2807 * really do have metachars in their names (see bug 58116).
2808 * FIXME: Figure out a better solution to keep some checks...
2810 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2811 SetLastError (ERROR_INVALID_NAME);
2813 g_free (entry_part);
2814 g_free (utf8_pattern);
2815 return(INVALID_HANDLE_VALUE);
2819 /* The pattern can specify a directory or a set of files.
2821 * The pattern can have wildcard characters ? and *, but only
2822 * in the section after the last directory delimiter. (Return
2823 * ERROR_INVALID_NAME if there are wildcards in earlier path
2824 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2825 * means "match one character", "??" seems to mean "match one
2826 * or two characters", "???" seems to mean "match one, two or
2827 * three characters", etc. Windows will also try and match
2828 * the mangled "short name" of files, so 8 character patterns
2829 * with wildcards will show some surprising results.
2831 * All the written documentation I can find says that '?'
2832 * should only match one character, and doesn't mention '??',
2833 * '???' etc. I'm going to assume that the strict behaviour
2834 * (ie '???' means three and only three characters) is the
2835 * correct one, because that lets me use fnmatch(3) rather
2836 * than mess around with regexes.
2839 find_handle.namelist = NULL;
2840 result = _wapi_io_scandir (dir_part, entry_part,
2841 &find_handle.namelist);
2844 /* No files, which windows seems to call
2847 SetLastError (ERROR_FILE_NOT_FOUND);
2848 g_free (utf8_pattern);
2849 g_free (entry_part);
2851 return (INVALID_HANDLE_VALUE);
2856 gint errnum = errno;
2858 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2860 g_message ("%s: scandir error: %s", __func__,
2861 g_strerror (errnum));
2863 g_free (utf8_pattern);
2864 g_free (entry_part);
2866 return (INVALID_HANDLE_VALUE);
2869 g_free (utf8_pattern);
2870 g_free (entry_part);
2873 g_message ("%s: Got %d matches", __func__, result);
2876 find_handle.dir_part = dir_part;
2877 find_handle.num = result;
2878 find_handle.count = 0;
2880 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2881 if (handle == _WAPI_HANDLE_INVALID) {
2882 g_warning ("%s: error creating find handle", __func__);
2884 g_free (entry_part);
2885 g_free (utf8_pattern);
2886 SetLastError (ERROR_GEN_FAILURE);
2888 return(INVALID_HANDLE_VALUE);
2891 if (handle != INVALID_HANDLE_VALUE &&
2892 !FindNextFile (handle, find_data)) {
2894 SetLastError (ERROR_NO_MORE_FILES);
2895 handle = INVALID_HANDLE_VALUE;
2901 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2903 struct _WapiHandle_find *find_handle;
2907 gchar *utf8_filename, *utf8_basename;
2908 gunichar2 *utf16_basename;
2912 gboolean ret = FALSE;
2914 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2915 (gpointer *)&find_handle);
2917 g_warning ("%s: error looking up find handle %p", __func__,
2919 SetLastError (ERROR_INVALID_HANDLE);
2923 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2925 thr_ret = _wapi_handle_lock_handle (handle);
2926 g_assert (thr_ret == 0);
2929 if (find_handle->count >= find_handle->num) {
2930 SetLastError (ERROR_NO_MORE_FILES);
2934 /* stat next match */
2936 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2937 if (_wapi_lstat (filename, &buf) != 0) {
2939 g_message ("%s: stat failed: %s", __func__, filename);
2946 utf8_filename = mono_utf8_from_external (filename);
2947 if (utf8_filename == NULL) {
2948 /* We couldn't turn this filename into utf8 (eg the
2949 * encoding of the name wasn't convertible), so just
2952 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2960 g_message ("%s: Found [%s]", __func__, utf8_filename);
2963 /* fill data block */
2965 if (buf.st_mtime < buf.st_ctime)
2966 create_time = buf.st_mtime;
2968 create_time = buf.st_ctime;
2970 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &buf);
2972 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2973 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2974 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2976 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2977 find_data->nFileSizeHigh = 0;
2978 find_data->nFileSizeLow = 0;
2980 find_data->nFileSizeHigh = buf.st_size >> 32;
2981 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2984 find_data->dwReserved0 = 0;
2985 find_data->dwReserved1 = 0;
2987 utf8_basename = _wapi_basename (utf8_filename);
2988 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2990 if(utf16_basename==NULL) {
2991 g_free (utf8_basename);
2992 g_free (utf8_filename);
2997 /* utf16 is 2 * utf8 */
3000 memset (find_data->cFileName, '\0', (MAX_PATH*2));
3002 /* Truncating a utf16 string like this might leave the last
3005 memcpy (find_data->cFileName, utf16_basename,
3006 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3008 find_data->cAlternateFileName [0] = 0; /* not used */
3010 g_free (utf8_basename);
3011 g_free (utf8_filename);
3012 g_free (utf16_basename);
3015 thr_ret = _wapi_handle_unlock_handle (handle);
3016 g_assert (thr_ret == 0);
3017 pthread_cleanup_pop (0);
3024 * @wapi_handle: the find handle to close.
3026 * Closes find handle @wapi_handle
3028 * Return value: %TRUE on success, %FALSE otherwise.
3030 gboolean FindClose (gpointer handle)
3032 struct _WapiHandle_find *find_handle;
3036 if (handle == NULL) {
3037 SetLastError (ERROR_INVALID_HANDLE);
3041 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
3042 (gpointer *)&find_handle);
3044 g_warning ("%s: error looking up find handle %p", __func__,
3046 SetLastError (ERROR_INVALID_HANDLE);
3050 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
3052 thr_ret = _wapi_handle_lock_handle (handle);
3053 g_assert (thr_ret == 0);
3055 g_strfreev (find_handle->namelist);
3056 g_free (find_handle->dir_part);
3058 thr_ret = _wapi_handle_unlock_handle (handle);
3059 g_assert (thr_ret == 0);
3060 pthread_cleanup_pop (0);
3062 _wapi_handle_unref (handle);
3069 * @name: a pointer to a NULL-terminated unicode string, that names
3070 * the directory to be created.
3071 * @security: ignored for now
3073 * Creates directory @name
3075 * Return value: %TRUE on success, %FALSE otherwise.
3077 gboolean CreateDirectory (const gunichar2 *name,
3078 WapiSecurityAttributes *security)
3085 g_message("%s: name is NULL", __func__);
3088 SetLastError (ERROR_INVALID_NAME);
3092 utf8_name = mono_unicode_to_external (name);
3093 if (utf8_name == NULL) {
3095 g_message ("%s: unicode conversion returned NULL", __func__);
3098 SetLastError (ERROR_INVALID_NAME);
3102 result = _wapi_mkdir (utf8_name, 0777);
3109 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3116 * @name: a pointer to a NULL-terminated unicode string, that names
3117 * the directory to be removed.
3119 * Removes directory @name
3121 * Return value: %TRUE on success, %FALSE otherwise.
3123 gboolean RemoveDirectory (const gunichar2 *name)
3130 g_message("%s: name is NULL", __func__);
3133 SetLastError (ERROR_INVALID_NAME);
3137 utf8_name = mono_unicode_to_external (name);
3138 if (utf8_name == NULL) {
3140 g_message ("%s: unicode conversion returned NULL", __func__);
3143 SetLastError (ERROR_INVALID_NAME);
3147 result = _wapi_rmdir (utf8_name);
3149 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3160 * GetFileAttributes:
3161 * @name: a pointer to a NULL-terminated unicode filename.
3163 * Gets the attributes for @name;
3165 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3167 guint32 GetFileAttributes (const gunichar2 *name)
3170 struct stat buf, linkbuf;
3176 g_message("%s: name is NULL", __func__);
3179 SetLastError (ERROR_INVALID_NAME);
3183 utf8_name = mono_unicode_to_external (name);
3184 if (utf8_name == NULL) {
3186 g_message ("%s: unicode conversion returned NULL", __func__);
3189 SetLastError (ERROR_INVALID_PARAMETER);
3190 return (INVALID_FILE_ATTRIBUTES);
3193 result = _wapi_stat (utf8_name, &buf);
3194 if (result == -1 && errno == ENOENT) {
3195 /* Might be a dangling symlink... */
3196 result = _wapi_lstat (utf8_name, &buf);
3200 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3202 return (INVALID_FILE_ATTRIBUTES);
3205 result = _wapi_lstat (utf8_name, &linkbuf);
3207 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3209 return (INVALID_FILE_ATTRIBUTES);
3212 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3220 * GetFileAttributesEx:
3221 * @name: a pointer to a NULL-terminated unicode filename.
3222 * @level: must be GetFileExInfoStandard
3223 * @info: pointer to a WapiFileAttributesData structure
3225 * Gets attributes, size and filetimes for @name;
3227 * Return value: %TRUE on success, %FALSE on failure
3229 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3232 WapiFileAttributesData *data;
3234 struct stat buf, linkbuf;
3238 if (level != GetFileExInfoStandard) {
3240 g_message ("%s: info level %d not supported.", __func__,
3244 SetLastError (ERROR_INVALID_PARAMETER);
3250 g_message("%s: name is NULL", __func__);
3253 SetLastError (ERROR_INVALID_NAME);
3257 utf8_name = mono_unicode_to_external (name);
3258 if (utf8_name == NULL) {
3260 g_message ("%s: unicode conversion returned NULL", __func__);
3263 SetLastError (ERROR_INVALID_PARAMETER);
3267 result = _wapi_stat (utf8_name, &buf);
3268 if (result == -1 && errno == ENOENT) {
3269 /* Might be a dangling symlink... */
3270 result = _wapi_lstat (utf8_name, &buf);
3274 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3279 result = _wapi_lstat (utf8_name, &linkbuf);
3281 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3286 /* fill data block */
3288 data = (WapiFileAttributesData *)info;
3290 if (buf.st_mtime < buf.st_ctime)
3291 create_time = buf.st_mtime;
3293 create_time = buf.st_ctime;
3295 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3301 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3302 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3303 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3305 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3306 data->nFileSizeHigh = 0;
3307 data->nFileSizeLow = 0;
3310 data->nFileSizeHigh = buf.st_size >> 32;
3311 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3319 * @name: name of file
3320 * @attrs: attributes to set
3322 * Changes the attributes on a named file.
3324 * Return value: %TRUE on success, %FALSE on failure.
3326 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3328 /* FIXME: think of something clever to do on unix */
3334 * Currently we only handle one *internal* case, with a value that is
3335 * not standard: 0x80000000, which means `set executable bit'
3340 g_message("%s: name is NULL", __func__);
3343 SetLastError (ERROR_INVALID_NAME);
3347 utf8_name = mono_unicode_to_external (name);
3348 if (utf8_name == NULL) {
3350 g_message ("%s: unicode conversion returned NULL", __func__);
3353 SetLastError (ERROR_INVALID_NAME);
3357 result = _wapi_stat (utf8_name, &buf);
3359 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3364 /* Contrary to the documentation, ms allows NORMAL to be
3365 * specified along with other attributes, so dont bother to
3366 * catch that case here.
3368 if (attrs & FILE_ATTRIBUTE_READONLY) {
3369 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3371 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3374 /* Ignore the other attributes for now */
3376 if (attrs & 0x80000000){
3377 mode_t exec_mask = 0;
3379 if ((buf.st_mode & S_IRUSR) != 0)
3380 exec_mask |= S_IXUSR;
3382 if ((buf.st_mode & S_IRGRP) != 0)
3383 exec_mask |= S_IXGRP;
3385 if ((buf.st_mode & S_IROTH) != 0)
3386 exec_mask |= S_IXOTH;
3388 result = chmod (utf8_name, buf.st_mode | exec_mask);
3390 /* Don't bother to reset executable (might need to change this
3400 * GetCurrentDirectory
3401 * @length: size of the buffer
3402 * @buffer: pointer to buffer that recieves path
3404 * Retrieves the current directory for the current process.
3406 * Return value: number of characters in buffer on success, zero on failure
3408 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3411 gunichar2 *utf16_path;
3415 path = g_get_current_dir ();
3419 utf16_path=mono_unicode_from_external (path, &bytes);
3421 /* if buffer too small, return number of characters required.
3422 * this is plain dumb.
3425 count = (bytes/2)+1;
3426 if (count > length) {
3428 g_free (utf16_path);
3433 /* Add the terminator */
3434 memset (buffer, '\0', bytes+2);
3435 memcpy (buffer, utf16_path, bytes);
3437 g_free (utf16_path);
3444 * SetCurrentDirectory
3445 * @path: path to new directory
3447 * Changes the directory path for the current process.
3449 * Return value: %TRUE on success, %FALSE on failure.
3451 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3457 SetLastError (ERROR_INVALID_PARAMETER);
3461 utf8_path = mono_unicode_to_external (path);
3462 if (_wapi_chdir (utf8_path) != 0) {
3463 _wapi_set_last_error_from_errno ();
3473 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3474 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3476 struct _WapiHandle_file pipe_read_handle = {0};
3477 struct _WapiHandle_file pipe_write_handle = {0};
3478 gpointer read_handle;
3479 gpointer write_handle;
3483 mono_once (&io_ops_once, io_ops_init);
3486 g_message ("%s: Creating pipe", __func__);
3492 g_message ("%s: Error creating pipe: %s", __func__,
3496 _wapi_set_last_error_from_errno ();
3500 if (filedes[0] >= _wapi_fd_reserve ||
3501 filedes[1] >= _wapi_fd_reserve) {
3503 g_message ("%s: File descriptor is too big", __func__);
3506 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3514 /* filedes[0] is open for reading, filedes[1] for writing */
3516 pipe_read_handle.fileaccess = GENERIC_READ;
3517 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3519 if (read_handle == _WAPI_HANDLE_INVALID) {
3520 g_warning ("%s: error creating pipe read handle", __func__);
3523 SetLastError (ERROR_GEN_FAILURE);
3528 pipe_write_handle.fileaccess = GENERIC_WRITE;
3529 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3530 &pipe_write_handle);
3531 if (write_handle == _WAPI_HANDLE_INVALID) {
3532 g_warning ("%s: error creating pipe write handle", __func__);
3533 _wapi_handle_unref (read_handle);
3537 SetLastError (ERROR_GEN_FAILURE);
3542 *readpipe = read_handle;
3543 *writepipe = write_handle;
3546 g_message ("%s: Returning pipe: read handle %p, write handle %p",
3547 __func__, read_handle, write_handle);
3553 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3555 gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3556 gunichar2 *tmpdir16=NULL;
3561 if(tmpdir[strlen (tmpdir)]!='/') {
3563 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3566 tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3567 if(tmpdir16==NULL) {
3575 g_message ("%s: Size %d smaller than needed (%ld)",
3576 __func__, len, dirlen+1);
3581 /* Add the terminator */
3582 memset (buf, '\0', bytes+2);
3583 memcpy (buf, tmpdir16, bytes);
3589 if(tmpdir16!=NULL) {
3598 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3601 gunichar2 *ptr, *dir;
3602 glong length, total = 0;
3606 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3611 /* Sigh, mntent and friends don't work well.
3612 * It stops on the first line that doesn't begin with a '/'.
3613 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3614 fp = fopen ("/etc/mtab", "rt");
3616 fp = fopen ("/etc/mnttab", "rt");
3622 while (fgets (buffer, 512, fp) != NULL) {
3626 splitted = g_strsplit (buffer, " ", 0);
3627 if (!*splitted || !*(splitted + 1)) {
3628 g_strfreev (splitted);
3632 dir = g_utf8_to_utf16 (*(splitted + 1), -1, &length, NULL, NULL);
3633 g_strfreev (splitted);
3634 if (total + length + 1 > len) {
3636 return len * 2; /* guess */
3639 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3641 total += length + 1;
3646 /* Commented out, does not work with my mtab!!! - Gonz */
3647 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3651 gunichar2 *ptr, *dir;
3652 glong len, total = 0;
3655 fp = setmntent ("/etc/mtab", "rt");
3657 fp = setmntent ("/etc/mnttab", "rt");
3663 while ((mnt = getmntent (fp)) != NULL) {
3664 g_print ("GOT %s\n", mnt->mnt_dir);
3665 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3666 if (total + len + 1 > len) {
3667 return len * 2; /* guess */
3670 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3681 static gboolean _wapi_lock_file_region (int fd, off_t offset, off_t length)
3683 struct flock lock_data;
3686 lock_data.l_type = F_WRLCK;
3687 lock_data.l_whence = SEEK_SET;
3688 lock_data.l_start = offset;
3689 lock_data.l_len = length;
3692 ret = fcntl (fd, F_SETLK, &lock_data);
3693 } while(ret == -1 && errno == EINTR);
3696 g_message ("%s: fcntl returns %d", __func__, ret);
3701 * if locks are not available (NFS for example),
3706 || errno == EOPNOTSUPP
3715 SetLastError (ERROR_LOCK_VIOLATION);
3722 static gboolean _wapi_unlock_file_region (int fd, off_t offset, off_t length)
3724 struct flock lock_data;
3727 lock_data.l_type = F_UNLCK;
3728 lock_data.l_whence = SEEK_SET;
3729 lock_data.l_start = offset;
3730 lock_data.l_len = length;
3733 ret = fcntl (fd, F_SETLK, &lock_data);
3734 } while(ret == -1 && errno == EINTR);
3737 g_message ("%s: fcntl returns %d", __func__, ret);
3742 * if locks are not available (NFS for example),
3747 || errno == EOPNOTSUPP
3756 SetLastError (ERROR_LOCK_VIOLATION);
3763 gboolean LockFile (gpointer handle, guint32 offset_low, guint32 offset_high,
3764 guint32 length_low, guint32 length_high)
3766 struct _WapiHandle_file *file_handle;
3768 off_t offset, length;
3769 int fd = GPOINTER_TO_UINT(handle);
3771 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
3772 (gpointer *)&file_handle);
3774 g_warning ("%s: error looking up file handle %p", __func__,
3776 SetLastError (ERROR_INVALID_HANDLE);
3780 if (!(file_handle->fileaccess & GENERIC_READ) &&
3781 !(file_handle->fileaccess & GENERIC_WRITE) &&
3782 !(file_handle->fileaccess & GENERIC_ALL)) {
3784 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
3786 SetLastError (ERROR_ACCESS_DENIED);
3790 #ifdef HAVE_LARGE_FILE_SUPPORT
3791 offset = ((gint64)offset_high << 32) | offset_low;
3792 length = ((gint64)length_high << 32) | length_low;
3795 g_message ("%s: Locking handle %p, offset %lld, length %lld", __func__,
3796 handle, offset, length);
3799 offset = offset_low;
3800 length = length_low;
3803 g_message ("%s: Locking handle %p, offset %ld, length %ld", __func__,
3804 handle, offset, length);
3808 return(_wapi_lock_file_region (fd, offset, length));
3811 gboolean UnlockFile (gpointer handle, guint32 offset_low,
3812 guint32 offset_high, guint32 length_low,
3813 guint32 length_high)
3815 struct _WapiHandle_file *file_handle;
3817 off_t offset, length;
3818 int fd = GPOINTER_TO_UINT(handle);
3820 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
3821 (gpointer *)&file_handle);
3823 g_warning ("%s: error looking up file handle %p", __func__,
3825 SetLastError (ERROR_INVALID_HANDLE);
3829 if (!(file_handle->fileaccess & GENERIC_READ) &&
3830 !(file_handle->fileaccess & GENERIC_WRITE) &&
3831 !(file_handle->fileaccess & GENERIC_ALL)) {
3833 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
3835 SetLastError (ERROR_ACCESS_DENIED);
3839 #ifdef HAVE_LARGE_FILE_SUPPORT
3840 offset = ((gint64)offset_high << 32) | offset_low;
3841 length = ((gint64)length_high << 32) | length_low;
3844 g_message ("%s: Unlocking handle %p, offset %lld, length %lld",
3845 __func__, handle, offset, length);
3848 offset = offset_low;
3849 length = length_low;
3852 g_message ("%s: Unlocking handle %p, offset %ld, length %ld", __func__,
3853 handle, offset, length);
3857 return(_wapi_unlock_file_region (fd, offset, length));