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,
230 /* FIXME: this could definitely be better, but there seems to
231 * be no pattern to the attributes that are set
234 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
235 if (S_ISSOCK (buf->st_mode))
236 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
238 filename = _wapi_basename (pathname);
240 if (S_ISDIR (buf->st_mode)) {
241 attrs = FILE_ATTRIBUTE_DIRECTORY;
242 if (!(buf->st_mode & S_IWUSR)) {
243 attrs |= FILE_ATTRIBUTE_READONLY;
245 if (filename[0] == '.') {
246 attrs |= FILE_ATTRIBUTE_HIDDEN;
249 if (!(buf->st_mode & S_IWUSR)) {
250 attrs = FILE_ATTRIBUTE_READONLY;
252 if (filename[0] == '.') {
253 attrs |= FILE_ATTRIBUTE_HIDDEN;
255 } else if (filename[0] == '.') {
256 attrs = FILE_ATTRIBUTE_HIDDEN;
258 attrs = FILE_ATTRIBUTE_NORMAL;
268 _wapi_set_last_error_from_errno (void)
270 SetLastError (_wapi_get_win32_file_error (errno));
273 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
276 if (errno == ENOENT) {
277 /* Check the path - if it's a missing directory then
278 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
284 dirname = _wapi_dirname (path);
286 dirname = g_strdup (dir);
289 if (_wapi_access (dirname, F_OK) == 0) {
290 SetLastError (ERROR_FILE_NOT_FOUND);
292 SetLastError (ERROR_PATH_NOT_FOUND);
297 _wapi_set_last_error_from_errno ();
303 static void file_close (gpointer handle, gpointer data)
305 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
308 g_message("%s: closing file handle %p [%s]", __func__, handle,
309 file_handle->filename);
312 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
313 _wapi_unlink (file_handle->filename);
315 g_free (file_handle->filename);
317 _wapi_handle_share_release (file_handle->share_info);
319 close (GPOINTER_TO_UINT(handle));
322 static WapiFileType file_getfiletype(void)
324 return(FILE_TYPE_DISK);
327 static gboolean file_read(gpointer handle, gpointer buffer,
328 guint32 numbytes, guint32 *bytesread,
329 WapiOverlapped *overlapped)
331 struct _WapiHandle_file *file_handle;
333 int fd = GPOINTER_TO_UINT(handle);
336 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
337 (gpointer *)&file_handle);
339 g_warning ("%s: error looking up file handle %p", __func__,
341 SetLastError (ERROR_INVALID_HANDLE);
345 if(bytesread!=NULL) {
349 if(!(file_handle->fileaccess & GENERIC_READ) &&
350 !(file_handle->fileaccess & GENERIC_ALL)) {
352 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
353 __func__, handle, file_handle->fileaccess);
356 SetLastError (ERROR_ACCESS_DENIED);
361 ret = read (fd, buffer, numbytes);
362 } while (ret == -1 && errno == EINTR &&
363 !_wapi_thread_cur_apc_pending());
369 g_message("%s: read of handle %p error: %s", __func__,
370 handle, strerror(err));
372 SetLastError (_wapi_get_win32_file_error (err));
376 if (bytesread != NULL) {
383 static gboolean file_write(gpointer handle, gconstpointer buffer,
384 guint32 numbytes, guint32 *byteswritten,
385 WapiOverlapped *overlapped G_GNUC_UNUSED)
387 struct _WapiHandle_file *file_handle;
391 int fd = GPOINTER_TO_UINT(handle);
393 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
394 (gpointer *)&file_handle);
396 g_warning ("%s: error looking up file handle %p", __func__,
398 SetLastError (ERROR_INVALID_HANDLE);
402 if(byteswritten!=NULL) {
406 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
407 !(file_handle->fileaccess & GENERIC_ALL)) {
409 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
412 SetLastError (ERROR_ACCESS_DENIED);
416 if (lock_while_writing) {
417 /* Need to lock the region we're about to write to,
418 * because we only do advisory locking on POSIX
421 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
422 if (current_pos == -1) {
424 g_message ("%s: handle %p lseek failed: %s", __func__,
425 handle, strerror (errno));
427 _wapi_set_last_error_from_errno ();
431 if (_wapi_lock_file_region (fd, current_pos,
432 numbytes) == FALSE) {
433 /* The error has already been set */
439 ret = write (fd, buffer, numbytes);
440 } while (ret == -1 && errno == EINTR &&
441 !_wapi_thread_cur_apc_pending());
443 if (lock_while_writing) {
444 _wapi_unlock_file_region (fd, current_pos, numbytes);
448 if (errno == EINTR) {
451 _wapi_set_last_error_from_errno ();
454 g_message("%s: write of handle %p error: %s",
455 __func__, handle, strerror(errno));
461 if (byteswritten != NULL) {
467 static gboolean file_flush(gpointer handle)
469 struct _WapiHandle_file *file_handle;
472 int fd = GPOINTER_TO_UINT(handle);
474 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
475 (gpointer *)&file_handle);
477 g_warning ("%s: error looking up file handle %p", __func__,
479 SetLastError (ERROR_INVALID_HANDLE);
483 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
484 !(file_handle->fileaccess & GENERIC_ALL)) {
486 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
489 SetLastError (ERROR_ACCESS_DENIED);
496 g_message("%s: fsync of handle %p error: %s", __func__, handle,
500 _wapi_set_last_error_from_errno ();
507 static guint32 file_seek(gpointer handle, gint32 movedistance,
508 gint32 *highmovedistance, WapiSeekMethod method)
510 struct _WapiHandle_file *file_handle;
512 off_t offset, newpos;
515 int fd = GPOINTER_TO_UINT(handle);
517 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
518 (gpointer *)&file_handle);
520 g_warning ("%s: error looking up file handle %p", __func__,
522 SetLastError (ERROR_INVALID_HANDLE);
523 return(INVALID_SET_FILE_POINTER);
526 if(!(file_handle->fileaccess & GENERIC_READ) &&
527 !(file_handle->fileaccess & GENERIC_WRITE) &&
528 !(file_handle->fileaccess & GENERIC_ALL)) {
530 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
533 SetLastError (ERROR_ACCESS_DENIED);
534 return(INVALID_SET_FILE_POINTER);
549 g_message("%s: invalid seek type %d", __func__, method);
552 SetLastError (ERROR_INVALID_PARAMETER);
553 return(INVALID_SET_FILE_POINTER);
556 #ifdef HAVE_LARGE_FILE_SUPPORT
557 if(highmovedistance==NULL) {
560 g_message("%s: setting offset to %lld (low %d)", __func__,
561 offset, movedistance);
564 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
567 g_message("%s: setting offset to %lld 0x%llx (high %d 0x%x, low %d 0x%x)", __func__, offset, offset, *highmovedistance, *highmovedistance, movedistance, movedistance);
575 #ifdef HAVE_LARGE_FILE_SUPPORT
576 g_message("%s: moving handle %p by %lld bytes from %d", __func__,
577 handle, offset, whence);
579 g_message("%s: moving handle %p fd %d by %ld bytes from %d", __func__,
580 handle, offset, whence);
584 newpos=lseek(fd, offset, whence);
587 g_message("%s: lseek on handle %p returned error %s",
588 __func__, handle, strerror(errno));
591 _wapi_set_last_error_from_errno ();
592 return(INVALID_SET_FILE_POINTER);
596 #ifdef HAVE_LARGE_FILE_SUPPORT
597 g_message("%s: lseek returns %lld", __func__, newpos);
599 g_message ("%s: lseek returns %ld", __func__, newpos);
603 #ifdef HAVE_LARGE_FILE_SUPPORT
604 ret=newpos & 0xFFFFFFFF;
605 if(highmovedistance!=NULL) {
606 *highmovedistance=newpos>>32;
610 if(highmovedistance!=NULL) {
611 /* Accurate, but potentially dodgy :-) */
617 g_message ("%s: move of handle %p returning %d/%d", __func__,
618 handle, ret, highmovedistance==NULL?0:*highmovedistance);
624 static gboolean file_setendoffile(gpointer handle)
626 struct _WapiHandle_file *file_handle;
631 int fd = GPOINTER_TO_UINT(handle);
633 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
634 (gpointer *)&file_handle);
636 g_warning ("%s: error looking up file handle %p", __func__,
638 SetLastError (ERROR_INVALID_HANDLE);
642 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
643 !(file_handle->fileaccess & GENERIC_ALL)) {
645 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
648 SetLastError (ERROR_ACCESS_DENIED);
652 /* Find the current file position, and the file length. If
653 * the file position is greater than the length, write to
654 * extend the file with a hole. If the file position is less
655 * than the length, truncate the file.
658 ret=fstat(fd, &statbuf);
661 g_message ("%s: handle %p fstat failed: %s", __func__,
662 handle, strerror(errno));
665 _wapi_set_last_error_from_errno ();
668 size=statbuf.st_size;
670 pos=lseek(fd, (off_t)0, SEEK_CUR);
673 g_message("%s: handle %p lseek failed: %s", __func__,
674 handle, strerror(errno));
677 _wapi_set_last_error_from_errno ();
681 #ifdef FTRUNCATE_DOESNT_EXTEND
682 /* I haven't bothered to write the configure.in stuff for this
683 * because I don't know if any platform needs it. I'm leaving
684 * this code just in case though
687 /* Extend the file. Use write() here, because some
688 * manuals say that ftruncate() behaviour is undefined
689 * when the file needs extending. The POSIX spec says
690 * that on XSI-conformant systems it extends, so if
691 * every system we care about conforms, then we can
695 ret = write (fd, "", 1);
696 } while (ret == -1 && errno == EINTR &&
697 !_wapi_thread_cur_apc_pending());
701 g_message("%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
704 _wapi_set_last_error_from_errno ();
708 /* And put the file position back after the write */
709 ret = lseek (fd, pos, SEEK_SET);
712 g_message ("%s: handle %p second lseek failed: %s",
713 __func__, handle, strerror(errno));
716 _wapi_set_last_error_from_errno ();
722 /* always truncate, because the extend write() adds an extra
723 * byte to the end of the file
726 ret=ftruncate(fd, pos);
728 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
731 g_message("%s: handle %p ftruncate failed: %s", __func__,
732 handle, strerror(errno));
735 _wapi_set_last_error_from_errno ();
742 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
744 struct _WapiHandle_file *file_handle;
749 int fd = GPOINTER_TO_UINT(handle);
751 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
752 (gpointer *)&file_handle);
754 g_warning ("%s: error looking up file handle %p", __func__,
756 SetLastError (ERROR_INVALID_HANDLE);
757 return(INVALID_FILE_SIZE);
760 if(!(file_handle->fileaccess & GENERIC_READ) &&
761 !(file_handle->fileaccess & GENERIC_WRITE) &&
762 !(file_handle->fileaccess & GENERIC_ALL)) {
764 g_message("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
767 SetLastError (ERROR_ACCESS_DENIED);
768 return(INVALID_FILE_SIZE);
771 /* If the file has a size with the low bits 0xFFFFFFFF the
772 * caller can't tell if this is an error, so clear the error
775 SetLastError (ERROR_SUCCESS);
777 ret = fstat(fd, &statbuf);
780 g_message ("%s: handle %p fstat failed: %s", __func__,
781 handle, strerror(errno));
784 _wapi_set_last_error_from_errno ();
785 return(INVALID_FILE_SIZE);
788 #ifdef HAVE_LARGE_FILE_SUPPORT
789 size = statbuf.st_size & 0xFFFFFFFF;
790 if (highsize != NULL) {
791 *highsize = statbuf.st_size>>32;
794 if (highsize != NULL) {
795 /* Accurate, but potentially dodgy :-) */
798 size = statbuf.st_size;
802 g_message ("%s: Returning size %d/%d", __func__, size, *highsize);
808 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
809 WapiFileTime *last_access,
810 WapiFileTime *last_write)
812 struct _WapiHandle_file *file_handle;
815 guint64 create_ticks, access_ticks, write_ticks;
817 int fd = GPOINTER_TO_UINT(handle);
819 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
820 (gpointer *)&file_handle);
822 g_warning ("%s: error looking up file handle %p", __func__,
824 SetLastError (ERROR_INVALID_HANDLE);
828 if(!(file_handle->fileaccess & GENERIC_READ) &&
829 !(file_handle->fileaccess & GENERIC_ALL)) {
831 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
832 __func__, handle, file_handle->fileaccess);
835 SetLastError (ERROR_ACCESS_DENIED);
839 ret=fstat(fd, &statbuf);
842 g_message("%s: handle %p fstat failed: %s", __func__, handle,
846 _wapi_set_last_error_from_errno ();
851 g_message("%s: atime: %ld ctime: %ld mtime: %ld", __func__,
852 statbuf.st_atime, statbuf.st_ctime,
856 /* Try and guess a meaningful create time by using the older
859 /* The magic constant comes from msdn documentation
860 * "Converting a time_t Value to a File Time"
862 if(statbuf.st_atime < statbuf.st_ctime) {
863 create_ticks=((guint64)statbuf.st_atime*10000000)
864 + 116444736000000000ULL;
866 create_ticks=((guint64)statbuf.st_ctime*10000000)
867 + 116444736000000000ULL;
870 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
871 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
874 g_message("%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
875 access_ticks, create_ticks, write_ticks);
878 if(create_time!=NULL) {
879 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
880 create_time->dwHighDateTime = create_ticks >> 32;
883 if(last_access!=NULL) {
884 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
885 last_access->dwHighDateTime = access_ticks >> 32;
888 if(last_write!=NULL) {
889 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
890 last_write->dwHighDateTime = write_ticks >> 32;
896 static gboolean file_setfiletime(gpointer handle,
897 const WapiFileTime *create_time G_GNUC_UNUSED,
898 const WapiFileTime *last_access,
899 const WapiFileTime *last_write)
901 struct _WapiHandle_file *file_handle;
903 struct utimbuf utbuf;
905 guint64 access_ticks, write_ticks;
907 int fd = GPOINTER_TO_UINT(handle);
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);
918 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
919 !(file_handle->fileaccess & GENERIC_ALL)) {
921 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
924 SetLastError (ERROR_ACCESS_DENIED);
928 if(file_handle->filename == NULL) {
930 g_message("%s: handle %p unknown filename", __func__, handle);
933 SetLastError (ERROR_INVALID_HANDLE);
937 /* Get the current times, so we can put the same times back in
938 * the event that one of the FileTime structs is NULL
940 ret=fstat (fd, &statbuf);
943 g_message("%s: handle %p fstat failed: %s", __func__, handle,
947 SetLastError (ERROR_INVALID_PARAMETER);
951 if(last_access!=NULL) {
952 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
953 last_access->dwLowDateTime;
954 /* This is (time_t)0. We can actually go to INT_MIN,
955 * but this will do for now.
957 if (access_ticks < 116444736000000000ULL) {
959 g_message ("%s: attempt to set access time too early",
962 SetLastError (ERROR_INVALID_PARAMETER);
966 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
968 utbuf.actime=statbuf.st_atime;
971 if(last_write!=NULL) {
972 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
973 last_write->dwLowDateTime;
974 /* This is (time_t)0. We can actually go to INT_MIN,
975 * but this will do for now.
977 if (write_ticks < 116444736000000000ULL) {
979 g_message ("%s: attempt to set write time too early",
982 SetLastError (ERROR_INVALID_PARAMETER);
986 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
988 utbuf.modtime=statbuf.st_mtime;
992 g_message ("%s: setting handle %p access %ld write %ld", __func__,
993 handle, utbuf.actime, utbuf.modtime);
996 ret = _wapi_utime (file_handle->filename, &utbuf);
999 g_message ("%s: handle %p [%s] utime failed: %s", __func__,
1000 handle, file_handle->filename, strerror(errno));
1003 SetLastError (ERROR_INVALID_PARAMETER);
1010 static void console_close (gpointer handle, gpointer data)
1012 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1015 g_message("%s: closing console handle %p", __func__, handle);
1018 g_free (console_handle->filename);
1020 close (GPOINTER_TO_UINT(handle));
1023 static WapiFileType console_getfiletype(void)
1025 return(FILE_TYPE_CHAR);
1028 static gboolean console_read(gpointer handle, gpointer buffer,
1029 guint32 numbytes, guint32 *bytesread,
1030 WapiOverlapped *overlapped G_GNUC_UNUSED)
1032 struct _WapiHandle_file *console_handle;
1035 int fd = GPOINTER_TO_UINT(handle);
1037 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1038 (gpointer *)&console_handle);
1040 g_warning ("%s: error looking up console handle %p", __func__,
1042 SetLastError (ERROR_INVALID_HANDLE);
1046 if(bytesread!=NULL) {
1050 if(!(console_handle->fileaccess & GENERIC_READ) &&
1051 !(console_handle->fileaccess & GENERIC_ALL)) {
1053 g_message ("%s: handle %p doesn't have GENERIC_READ access: %u",
1054 __func__, handle, console_handle->fileaccess);
1057 SetLastError (ERROR_ACCESS_DENIED);
1062 ret=read(fd, buffer, numbytes);
1063 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1067 g_message("%s: read of handle %p error: %s", __func__, handle,
1071 _wapi_set_last_error_from_errno ();
1075 if(bytesread!=NULL) {
1082 static gboolean console_write(gpointer handle, gconstpointer buffer,
1083 guint32 numbytes, guint32 *byteswritten,
1084 WapiOverlapped *overlapped G_GNUC_UNUSED)
1086 struct _WapiHandle_file *console_handle;
1089 int fd = GPOINTER_TO_UINT(handle);
1091 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1092 (gpointer *)&console_handle);
1094 g_warning ("%s: error looking up console handle %p", __func__,
1096 SetLastError (ERROR_INVALID_HANDLE);
1100 if(byteswritten!=NULL) {
1104 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1105 !(console_handle->fileaccess & GENERIC_ALL)) {
1107 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, console_handle->fileaccess);
1110 SetLastError (ERROR_ACCESS_DENIED);
1115 ret = write(fd, buffer, numbytes);
1116 } while (ret == -1 && errno == EINTR &&
1117 !_wapi_thread_cur_apc_pending());
1120 if (errno == EINTR) {
1123 _wapi_set_last_error_from_errno ();
1126 g_message ("%s: write of handle %p error: %s",
1127 __func__, handle, strerror(errno));
1133 if(byteswritten!=NULL) {
1140 static void pipe_close (gpointer handle, gpointer data G_GNUC_UNUSED)
1143 g_message("%s: closing pipe handle %p", __func__, handle);
1146 /* No filename with pipe handles */
1148 close(GPOINTER_TO_UINT(handle));
1151 static WapiFileType pipe_getfiletype(void)
1153 return(FILE_TYPE_PIPE);
1156 static gboolean pipe_read (gpointer handle, gpointer buffer,
1157 guint32 numbytes, guint32 *bytesread,
1158 WapiOverlapped *overlapped G_GNUC_UNUSED)
1160 struct _WapiHandle_file *pipe_handle;
1163 int fd = GPOINTER_TO_UINT(handle);
1165 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1166 (gpointer *)&pipe_handle);
1168 g_warning ("%s: error looking up pipe handle %p", __func__,
1170 SetLastError (ERROR_INVALID_HANDLE);
1174 if(bytesread!=NULL) {
1178 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1179 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1181 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
1182 __func__, handle, pipe_handle->fileaccess);
1185 SetLastError (ERROR_ACCESS_DENIED);
1190 g_message ("%s: reading up to %d bytes from pipe %p", __func__,
1195 ret=read(fd, buffer, numbytes);
1196 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1199 if (errno == EINTR) {
1202 _wapi_set_last_error_from_errno ();
1205 g_message("%s: read of handle %p error: %s", __func__,
1206 handle, strerror(errno));
1214 g_message ("%s: read %d bytes from pipe", __func__, ret);
1217 if(bytesread!=NULL) {
1224 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1225 guint32 numbytes, guint32 *byteswritten,
1226 WapiOverlapped *overlapped G_GNUC_UNUSED)
1228 struct _WapiHandle_file *pipe_handle;
1231 int fd = GPOINTER_TO_UINT(handle);
1233 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1234 (gpointer *)&pipe_handle);
1236 g_warning ("%s: error looking up pipe handle %p", __func__,
1238 SetLastError (ERROR_INVALID_HANDLE);
1242 if(byteswritten!=NULL) {
1246 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1247 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1249 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, pipe_handle->fileaccess);
1252 SetLastError (ERROR_ACCESS_DENIED);
1257 g_message ("%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1262 ret = write (fd, buffer, numbytes);
1263 } while (ret == -1 && errno == EINTR &&
1264 !_wapi_thread_cur_apc_pending());
1267 if (errno == EINTR) {
1270 _wapi_set_last_error_from_errno ();
1273 g_message("%s: write of handle %p error: %s", __func__,
1274 handle, strerror(errno));
1280 if(byteswritten!=NULL) {
1287 static int convert_flags(guint32 fileaccess, guint32 createmode)
1291 switch(fileaccess) {
1298 case GENERIC_READ|GENERIC_WRITE:
1303 g_message("%s: Unknown access type 0x%x", __func__,
1309 switch(createmode) {
1311 flags|=O_CREAT|O_EXCL;
1314 flags|=O_CREAT|O_TRUNC;
1321 case TRUNCATE_EXISTING:
1326 g_message("%s: Unknown create mode 0x%x", __func__,
1335 static guint32 convert_from_flags(int flags)
1337 guint32 fileaccess=0;
1340 #define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR)
1343 if((flags & O_ACCMODE) == O_RDONLY) {
1344 fileaccess=GENERIC_READ;
1345 } else if ((flags & O_ACCMODE) == O_WRONLY) {
1346 fileaccess=GENERIC_WRITE;
1347 } else if ((flags & O_ACCMODE) == O_RDWR) {
1348 fileaccess=GENERIC_READ|GENERIC_WRITE;
1351 g_message("%s: Can't figure out flags 0x%x", __func__, flags);
1355 /* Maybe sort out create mode too */
1361 static mode_t convert_perms(guint32 sharemode)
1365 if(sharemode&FILE_SHARE_READ) {
1368 if(sharemode&FILE_SHARE_WRITE) {
1376 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1378 struct _WapiFileShare **share_info)
1380 gboolean file_already_shared;
1381 guint32 file_existing_share, file_existing_access;
1383 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);
1385 if (file_already_shared) {
1386 /* The reference to this share info was incremented
1387 * when we looked it up, so be careful to put it back
1388 * if we conclude we can't use this file.
1390 if (file_existing_share == 0) {
1391 /* Quick and easy, no possibility to share */
1393 g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
1396 _wapi_handle_share_release (*share_info);
1401 if (((file_existing_share == FILE_SHARE_READ) &&
1402 (fileaccess != GENERIC_READ)) ||
1403 ((file_existing_share == FILE_SHARE_WRITE) &&
1404 (fileaccess != GENERIC_WRITE))) {
1405 /* New access mode doesn't match up */
1407 g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
1410 _wapi_handle_share_release (*share_info);
1415 if (((file_existing_access & GENERIC_READ) &&
1416 !(sharemode & FILE_SHARE_READ)) ||
1417 ((file_existing_access & GENERIC_WRITE) &&
1418 !(sharemode & FILE_SHARE_WRITE))) {
1419 /* New share mode doesn't match up */
1421 g_message ("%s: Access mode prevents open: requested share: 0x%x, file has access: 0x%x", __func__, sharemode, file_existing_access);
1424 _wapi_handle_share_release (*share_info);
1430 g_message ("%s: New file!", __func__);
1437 static gboolean share_check (struct stat *statbuf, guint32 sharemode,
1439 struct _WapiFileShare **share_info, int fd)
1441 if (share_allows_open (statbuf, sharemode, fileaccess,
1442 share_info) == TRUE) {
1446 /* Got a share violation. Double check that the file is still
1447 * open by someone, in case a process crashed while still
1448 * holding a file handle. This will also cope with someone
1449 * using Mono.Posix to close the file. This is cheaper and
1450 * less intrusive to other processes than initiating a handle
1454 _wapi_handle_check_share (*share_info, fd);
1455 if (share_allows_open (statbuf, sharemode, fileaccess,
1456 share_info) == TRUE) {
1460 /* Still violating. It's possible that a process crashed
1461 * while still holding a file handle, and that a non-mono
1462 * process has the file open. (For example, C-c mcs while
1463 * editing a source file.) As a last resort, run a handle
1464 * collection, which will remove stale share entries.
1466 _wapi_handle_collect ();
1468 return(share_allows_open (statbuf, sharemode, fileaccess, share_info));
1473 * @name: a pointer to a NULL-terminated unicode string, that names
1474 * the file or other object to create.
1475 * @fileaccess: specifies the file access mode
1476 * @sharemode: whether the file should be shared. This parameter is
1477 * currently ignored.
1478 * @security: Ignored for now.
1479 * @createmode: specifies whether to create a new file, whether to
1480 * overwrite an existing file, whether to truncate the file, etc.
1481 * @attrs: specifies file attributes and flags. On win32 attributes
1482 * are characteristics of the file, not the handle, and are ignored
1483 * when an existing file is opened. Flags give the library hints on
1484 * how to process a file to optimise performance.
1485 * @template: the handle of an open %GENERIC_READ file that specifies
1486 * attributes to apply to a newly created file, ignoring @attrs.
1487 * Normally this parameter is NULL. This parameter is ignored when an
1488 * existing file is opened.
1490 * Creates a new file handle. This only applies to normal files:
1491 * pipes are handled by CreatePipe(), and console handles are created
1492 * with GetStdHandle().
1494 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1496 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1497 guint32 sharemode, WapiSecurityAttributes *security,
1498 guint32 createmode, guint32 attrs,
1499 gpointer template G_GNUC_UNUSED)
1501 struct _WapiHandle_file file_handle = {0};
1503 int flags=convert_flags(fileaccess, createmode);
1504 /*mode_t perms=convert_perms(sharemode);*/
1505 /* we don't use sharemode, because that relates to sharing of
1506 * the file when the file is open and is already handled by
1507 * other code, perms instead are the on-disk permissions and
1508 * this is a sane default.
1514 struct stat statbuf;
1516 mono_once (&io_ops_once, io_ops_init);
1518 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1519 SetLastError (ERROR_ENCRYPTION_FAILED);
1520 return INVALID_HANDLE_VALUE;
1525 g_message ("%s: name is NULL", __func__);
1528 SetLastError (ERROR_INVALID_NAME);
1529 return(INVALID_HANDLE_VALUE);
1532 filename = mono_unicode_to_external (name);
1533 if (filename == NULL) {
1535 g_message("%s: unicode conversion returned NULL", __func__);
1538 SetLastError (ERROR_INVALID_NAME);
1539 return(INVALID_HANDLE_VALUE);
1543 g_message ("%s: Opening %s with share 0x%x and access 0x%x", __func__,
1544 filename, sharemode, fileaccess);
1547 fd = _wapi_open (filename, flags, perms);
1549 /* If we were trying to open a directory with write permissions
1550 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1551 * EISDIR. However, this is a bit bogus because calls to
1552 * manipulate the directory (e.g. SetFileTime) will still work on
1553 * the directory because they use other API calls
1554 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1555 * to open the directory again without write permission.
1557 if (fd == -1 && errno == EISDIR)
1559 /* Try again but don't try to make it writable */
1560 fd = open(filename, flags & ~(O_RDWR|O_WRONLY), perms);
1565 g_message("%s: Error opening file %s: %s", __func__, filename,
1568 _wapi_set_last_path_error_from_errno (NULL, filename);
1571 return(INVALID_HANDLE_VALUE);
1574 if (fd >= _wapi_fd_reserve) {
1576 g_message ("%s: File descriptor is too big", __func__);
1579 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1584 return(INVALID_HANDLE_VALUE);
1587 ret = fstat (fd, &statbuf);
1590 g_message ("%s: fstat error of file %s: %s", __func__,
1591 filename, strerror (errno));
1593 _wapi_set_last_error_from_errno ();
1597 return(INVALID_HANDLE_VALUE);
1600 if (share_check (&statbuf, sharemode, fileaccess,
1601 &file_handle.share_info, fd) == FALSE) {
1602 SetLastError (ERROR_SHARING_VIOLATION);
1606 return (INVALID_HANDLE_VALUE);
1608 if (file_handle.share_info == NULL) {
1609 /* No space, so no more files can be opened */
1611 g_message ("%s: No space in the share table", __func__);
1614 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1618 return(INVALID_HANDLE_VALUE);
1621 file_handle.filename = filename;
1623 if(security!=NULL) {
1624 //file_handle->security_attributes=_wapi_handle_scratch_store (
1625 //security, sizeof(WapiSecurityAttributes));
1628 file_handle.fileaccess=fileaccess;
1629 file_handle.sharemode=sharemode;
1630 file_handle.attrs=attrs;
1632 #ifdef HAVE_POSIX_FADVISE
1633 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1634 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1635 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1636 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1640 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1642 if (S_ISFIFO (statbuf.st_mode)) {
1643 handle_type = WAPI_HANDLE_PIPE;
1644 } else if (S_ISCHR (statbuf.st_mode)) {
1645 handle_type = WAPI_HANDLE_CONSOLE;
1647 handle_type = WAPI_HANDLE_FILE;
1650 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1651 if (handle == _WAPI_HANDLE_INVALID) {
1652 g_warning ("%s: error creating file handle", __func__);
1656 SetLastError (ERROR_GEN_FAILURE);
1657 return(INVALID_HANDLE_VALUE);
1661 g_message("%s: returning handle %p", __func__, handle);
1669 * @name: a pointer to a NULL-terminated unicode string, that names
1670 * the file to be deleted.
1672 * Deletes file @name.
1674 * Return value: %TRUE on success, %FALSE otherwise.
1676 gboolean DeleteFile(const gunichar2 *name)
1680 gboolean ret = FALSE;
1684 g_message("%s: name is NULL", __func__);
1687 SetLastError (ERROR_INVALID_NAME);
1691 filename=mono_unicode_to_external(name);
1692 if(filename==NULL) {
1694 g_message("%s: unicode conversion returned NULL", __func__);
1697 SetLastError (ERROR_INVALID_NAME);
1701 retval = _wapi_unlink (filename);
1704 _wapi_set_last_path_error_from_errno (NULL, filename);
1716 * @name: a pointer to a NULL-terminated unicode string, that names
1717 * the file to be moved.
1718 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1719 * new name for the file.
1721 * Renames file @name to @dest_name.
1722 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1723 * when it is the same file as the source. In that case it silently succeeds.
1725 * Return value: %TRUE on success, %FALSE otherwise.
1727 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1729 gchar *utf8_name, *utf8_dest_name;
1731 struct stat stat_src, stat_dest;
1732 gboolean ret = FALSE;
1736 g_message("%s: name is NULL", __func__);
1739 SetLastError (ERROR_INVALID_NAME);
1743 utf8_name = mono_unicode_to_external (name);
1744 if (utf8_name == NULL) {
1746 g_message ("%s: unicode conversion returned NULL", __func__);
1749 SetLastError (ERROR_INVALID_NAME);
1753 if(dest_name==NULL) {
1755 g_message("%s: name is NULL", __func__);
1759 SetLastError (ERROR_INVALID_NAME);
1763 utf8_dest_name = mono_unicode_to_external (dest_name);
1764 if (utf8_dest_name == NULL) {
1766 g_message ("%s: unicode conversion returned NULL", __func__);
1770 SetLastError (ERROR_INVALID_NAME);
1775 * In C# land we check for the existence of src, but not for dest.
1776 * We check it here and return the failure if dest exists and is not
1777 * the same file as src.
1779 if (!_wapi_stat (utf8_dest_name, &stat_dest) &&
1780 !_wapi_stat (utf8_name, &stat_src)) {
1781 if (stat_dest.st_dev != stat_src.st_dev ||
1782 stat_dest.st_ino != stat_src.st_ino) {
1783 SetLastError (ERROR_ALREADY_EXISTS);
1788 result = _wapi_rename (utf8_name, utf8_dest_name);
1793 SetLastError (ERROR_ALREADY_EXISTS);
1797 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1802 g_free (utf8_dest_name);
1804 if (result != 0 && errno == EXDEV) {
1805 /* Try a copy to the new location, and delete the source */
1806 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1807 /* CopyFile will set the error */
1811 return(DeleteFile (name));
1823 * @name: a pointer to a NULL-terminated unicode string, that names
1824 * the file to be copied.
1825 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1826 * new name for the file.
1827 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1829 * Copies file @name to @dest_name
1831 * Return value: %TRUE on success, %FALSE otherwise.
1833 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1834 gboolean fail_if_exists)
1836 gchar *utf8_src, *utf8_dest;
1837 int src_fd, dest_fd;
1845 g_message("%s: name is NULL", __func__);
1848 SetLastError (ERROR_INVALID_NAME);
1852 utf8_src = mono_unicode_to_external (name);
1853 if (utf8_src == NULL) {
1855 g_message ("%s: unicode conversion of source returned NULL",
1859 SetLastError (ERROR_INVALID_PARAMETER);
1863 if(dest_name==NULL) {
1865 g_message("%s: name is NULL", __func__);
1869 SetLastError (ERROR_INVALID_NAME);
1873 utf8_dest = mono_unicode_to_external (dest_name);
1874 if (utf8_dest == NULL) {
1876 g_message ("%s: unicode conversion of dest returned NULL",
1880 SetLastError (ERROR_INVALID_PARAMETER);
1887 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
1889 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
1897 if (fstat (src_fd, &st) < 0) {
1898 _wapi_set_last_error_from_errno ();
1907 if (fail_if_exists) {
1908 dest_fd = open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL,
1911 dest_fd = open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
1913 /* O_TRUNC might cause a fail if the file
1916 dest_fd = open (utf8_dest, O_WRONLY | O_CREAT,
1919 /* Apparently this error is set if we
1920 * overwrite the dest file
1922 SetLastError (ERROR_ALREADY_EXISTS);
1926 _wapi_set_last_error_from_errno ();
1935 buf_size = st.st_blksize;
1936 buf = (char *) alloca (buf_size);
1939 remain = read (src_fd, buf, buf_size);
1942 if (errno == EINTR && !_wapi_thread_cur_apc_pending()) {
1946 _wapi_set_last_error_from_errno ();
1960 while (remain > 0) {
1961 if ((n = write (dest_fd, buf, remain)) < 0) {
1962 if (errno == EINTR && !_wapi_thread_cur_apc_pending())
1965 _wapi_set_last_error_from_errno ();
1967 g_message ("%s: write failed.", __func__);
1990 static gpointer stdhandle_create (int fd, const gchar *name)
1992 struct _WapiHandle_file file_handle = {0};
1997 g_message("%s: creating standard handle type %s, fd %d", __func__,
2001 /* Check if fd is valid */
2003 flags=fcntl(fd, F_GETFL);
2004 } while (flags == -1 && errno == EINTR);
2007 /* Invalid fd. Not really much point checking for EBADF
2011 g_message("%s: fcntl error on fd %d: %s", __func__, fd,
2015 _wapi_set_last_error_from_errno ();
2016 return(INVALID_HANDLE_VALUE);
2019 file_handle.filename = g_strdup(name);
2020 /* some default security attributes might be needed */
2021 file_handle.security_attributes=0;
2022 file_handle.fileaccess=convert_from_flags(flags);
2024 /* Apparently input handles can't be written to. (I don't
2025 * know if output or error handles can't be read from.)
2028 file_handle.fileaccess &= ~GENERIC_WRITE;
2031 file_handle.sharemode=0;
2032 file_handle.attrs=0;
2034 handle = _wapi_handle_new_fd (WAPI_HANDLE_CONSOLE, fd, &file_handle);
2035 if (handle == _WAPI_HANDLE_INVALID) {
2036 g_warning ("%s: error creating file handle", __func__);
2037 SetLastError (ERROR_GEN_FAILURE);
2038 return(INVALID_HANDLE_VALUE);
2042 g_message("%s: returning handle %p", __func__, handle);
2050 * @stdhandle: specifies the file descriptor
2052 * Returns a handle for stdin, stdout, or stderr. Always returns the
2053 * same handle for the same @stdhandle.
2055 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2058 static mono_mutex_t stdhandle_mutex = MONO_MUTEX_INITIALIZER;
2060 gpointer GetStdHandle(WapiStdHandle stdhandle)
2062 struct _WapiHandle_file *file_handle;
2069 case STD_INPUT_HANDLE:
2074 case STD_OUTPUT_HANDLE:
2079 case STD_ERROR_HANDLE:
2086 g_message("%s: unknown standard handle type", __func__);
2089 SetLastError (ERROR_INVALID_PARAMETER);
2090 return(INVALID_HANDLE_VALUE);
2093 handle = GINT_TO_POINTER (fd);
2095 pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2096 (void *)&stdhandle_mutex);
2097 thr_ret = mono_mutex_lock (&stdhandle_mutex);
2098 g_assert (thr_ret == 0);
2100 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2101 (gpointer *)&file_handle);
2103 /* Need to create this console handle */
2104 handle = stdhandle_create (fd, name);
2106 if (handle == INVALID_HANDLE_VALUE) {
2107 SetLastError (ERROR_NO_MORE_FILES);
2111 /* Add a reference to this handle */
2112 _wapi_handle_ref (handle);
2116 thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2117 g_assert (thr_ret == 0);
2118 pthread_cleanup_pop (0);
2125 * @handle: The file handle to read from. The handle must have
2126 * %GENERIC_READ access.
2127 * @buffer: The buffer to store read data in
2128 * @numbytes: The maximum number of bytes to read
2129 * @bytesread: The actual number of bytes read is stored here. This
2130 * value can be zero if the handle is positioned at the end of the
2132 * @overlapped: points to a required %WapiOverlapped structure if
2133 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2136 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2137 * function reads up to @numbytes bytes from the file from the current
2138 * file position, and stores them in @buffer. If there are not enough
2139 * bytes left in the file, just the amount available will be read.
2140 * The actual number of bytes read is stored in @bytesread.
2142 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2143 * file position is ignored and the read position is taken from data
2144 * in the @overlapped structure.
2146 * Return value: %TRUE if the read succeeds (even if no bytes were
2147 * read due to an attempt to read past the end of the file), %FALSE on
2150 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2151 guint32 *bytesread, WapiOverlapped *overlapped)
2153 WapiHandleType type;
2155 type = _wapi_handle_type (handle);
2157 if(io_ops[type].readfile==NULL) {
2158 SetLastError (ERROR_INVALID_HANDLE);
2162 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2168 * @handle: The file handle to write to. The handle must have
2169 * %GENERIC_WRITE access.
2170 * @buffer: The buffer to read data from.
2171 * @numbytes: The maximum number of bytes to write.
2172 * @byteswritten: The actual number of bytes written is stored here.
2173 * If the handle is positioned at the file end, the length of the file
2174 * is extended. This parameter may be %NULL.
2175 * @overlapped: points to a required %WapiOverlapped structure if
2176 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2179 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2180 * function writes up to @numbytes bytes from @buffer to the file at
2181 * the current file position. If @handle is positioned at the end of
2182 * the file, the file is extended. The actual number of bytes written
2183 * is stored in @byteswritten.
2185 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2186 * file position is ignored and the write position is taken from data
2187 * in the @overlapped structure.
2189 * Return value: %TRUE if the write succeeds, %FALSE on error.
2191 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2192 guint32 *byteswritten, WapiOverlapped *overlapped)
2194 WapiHandleType type;
2196 type = _wapi_handle_type (handle);
2198 if(io_ops[type].writefile==NULL) {
2199 SetLastError (ERROR_INVALID_HANDLE);
2203 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2209 * @handle: Handle to open file. The handle must have
2210 * %GENERIC_WRITE access.
2212 * Flushes buffers of the file and causes all unwritten data to
2215 * Return value: %TRUE on success, %FALSE otherwise.
2217 gboolean FlushFileBuffers(gpointer handle)
2219 WapiHandleType type;
2221 type = _wapi_handle_type (handle);
2223 if(io_ops[type].flushfile==NULL) {
2224 SetLastError (ERROR_INVALID_HANDLE);
2228 return(io_ops[type].flushfile (handle));
2233 * @handle: The file handle to set. The handle must have
2234 * %GENERIC_WRITE access.
2236 * Moves the end-of-file position to the current position of the file
2237 * pointer. This function is used to truncate or extend a file.
2239 * Return value: %TRUE on success, %FALSE otherwise.
2241 gboolean SetEndOfFile(gpointer handle)
2243 WapiHandleType type;
2245 type = _wapi_handle_type (handle);
2247 if (io_ops[type].setendoffile == NULL) {
2248 SetLastError (ERROR_INVALID_HANDLE);
2252 return(io_ops[type].setendoffile (handle));
2257 * @handle: The file handle to set. The handle must have
2258 * %GENERIC_READ or %GENERIC_WRITE access.
2259 * @movedistance: Low 32 bits of a signed value that specifies the
2260 * number of bytes to move the file pointer.
2261 * @highmovedistance: Pointer to the high 32 bits of a signed value
2262 * that specifies the number of bytes to move the file pointer, or
2264 * @method: The starting point for the file pointer move.
2266 * Sets the file pointer of an open file.
2268 * The distance to move the file pointer is calculated from
2269 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2270 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2271 * is the low 32 bits and @highmovedistance a pointer to the high 32
2272 * bits of a 64 bit signed value. A positive distance moves the file
2273 * pointer forward from the position specified by @method; a negative
2274 * distance moves the file pointer backward.
2276 * If the library is compiled without large file support,
2277 * @highmovedistance is ignored and its value is set to zero on a
2278 * successful return.
2280 * Return value: On success, the low 32 bits of the new file pointer.
2281 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2282 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2284 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2285 gint32 *highmovedistance, WapiSeekMethod method)
2287 WapiHandleType type;
2289 type = _wapi_handle_type (handle);
2291 if (io_ops[type].seek == NULL) {
2292 SetLastError (ERROR_INVALID_HANDLE);
2293 return(INVALID_SET_FILE_POINTER);
2296 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2302 * @handle: The file handle to test.
2304 * Finds the type of file @handle.
2306 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2307 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2308 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2309 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2311 WapiFileType GetFileType(gpointer handle)
2313 WapiHandleType type;
2315 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2316 SetLastError (ERROR_INVALID_HANDLE);
2317 return(FILE_TYPE_UNKNOWN);
2320 type = _wapi_handle_type (handle);
2322 if (io_ops[type].getfiletype == NULL) {
2323 SetLastError (ERROR_INVALID_HANDLE);
2324 return(FILE_TYPE_UNKNOWN);
2327 return(io_ops[type].getfiletype ());
2332 * @handle: The file handle to query. The handle must have
2333 * %GENERIC_READ or %GENERIC_WRITE access.
2334 * @highsize: If non-%NULL, the high 32 bits of the file size are
2337 * Retrieves the size of the file @handle.
2339 * If the library is compiled without large file support, @highsize
2340 * has its value set to zero on a successful return.
2342 * Return value: On success, the low 32 bits of the file size. If
2343 * @highsize is non-%NULL then the high 32 bits of the file size are
2344 * stored here. On failure %INVALID_FILE_SIZE is returned.
2346 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2348 WapiHandleType type;
2350 type = _wapi_handle_type (handle);
2352 if (io_ops[type].getfilesize == NULL) {
2353 SetLastError (ERROR_INVALID_HANDLE);
2354 return(INVALID_FILE_SIZE);
2357 return(io_ops[type].getfilesize (handle, highsize));
2362 * @handle: The file handle to query. The handle must have
2363 * %GENERIC_READ access.
2364 * @create_time: Points to a %WapiFileTime structure to receive the
2365 * number of ticks since the epoch that file was created. May be
2367 * @last_access: Points to a %WapiFileTime structure to receive the
2368 * number of ticks since the epoch when file was last accessed. May be
2370 * @last_write: Points to a %WapiFileTime structure to receive the
2371 * number of ticks since the epoch when file was last written to. May
2374 * Finds the number of ticks since the epoch that the file referenced
2375 * by @handle was created, last accessed and last modified. A tick is
2376 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2379 * Create time isn't recorded on POSIX file systems or reported by
2380 * stat(2), so that time is guessed by returning the oldest of the
2383 * Return value: %TRUE on success, %FALSE otherwise.
2385 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2386 WapiFileTime *last_access, WapiFileTime *last_write)
2388 WapiHandleType type;
2390 type = _wapi_handle_type (handle);
2392 if (io_ops[type].getfiletime == NULL) {
2393 SetLastError (ERROR_INVALID_HANDLE);
2397 return(io_ops[type].getfiletime (handle, create_time, last_access,
2403 * @handle: The file handle to set. The handle must have
2404 * %GENERIC_WRITE access.
2405 * @create_time: Points to a %WapiFileTime structure that contains the
2406 * number of ticks since the epoch that the file was created. May be
2408 * @last_access: Points to a %WapiFileTime structure that contains the
2409 * number of ticks since the epoch when the file was last accessed.
2411 * @last_write: Points to a %WapiFileTime structure that contains the
2412 * number of ticks since the epoch when the file was last written to.
2415 * Sets the number of ticks since the epoch that the file referenced
2416 * by @handle was created, last accessed or last modified. A tick is
2417 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2420 * Create time isn't recorded on POSIX file systems, and is ignored.
2422 * Return value: %TRUE on success, %FALSE otherwise.
2424 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2425 const WapiFileTime *last_access,
2426 const WapiFileTime *last_write)
2428 WapiHandleType type;
2430 type = _wapi_handle_type (handle);
2432 if (io_ops[type].setfiletime == NULL) {
2433 SetLastError (ERROR_INVALID_HANDLE);
2437 return(io_ops[type].setfiletime (handle, create_time, last_access,
2441 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2442 * January 1 1601 GMT
2445 #define TICKS_PER_MILLISECOND 10000L
2446 #define TICKS_PER_SECOND 10000000L
2447 #define TICKS_PER_MINUTE 600000000L
2448 #define TICKS_PER_HOUR 36000000000LL
2449 #define TICKS_PER_DAY 864000000000LL
2451 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2453 static const guint16 mon_yday[2][13]={
2454 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2455 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2459 * FileTimeToSystemTime:
2460 * @file_time: Points to a %WapiFileTime structure that contains the
2461 * number of ticks to convert.
2462 * @system_time: Points to a %WapiSystemTime structure to receive the
2465 * Converts a tick count into broken-out time values.
2467 * Return value: %TRUE on success, %FALSE otherwise.
2469 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2470 WapiSystemTime *system_time)
2472 gint64 file_ticks, totaldays, rem, y;
2475 if(system_time==NULL) {
2477 g_message("%s: system_time NULL", __func__);
2480 SetLastError (ERROR_INVALID_PARAMETER);
2484 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2485 file_time->dwLowDateTime;
2487 /* Really compares if file_ticks>=0x8000000000000000
2488 * (LLONG_MAX+1) but we're working with a signed value for the
2489 * year and day calculation to work later
2493 g_message("%s: file_time too big", __func__);
2496 SetLastError (ERROR_INVALID_PARAMETER);
2500 totaldays=(file_ticks / TICKS_PER_DAY);
2501 rem = file_ticks % TICKS_PER_DAY;
2503 g_message("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2506 system_time->wHour=rem/TICKS_PER_HOUR;
2507 rem %= TICKS_PER_HOUR;
2509 g_message("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2512 system_time->wMinute = rem / TICKS_PER_MINUTE;
2513 rem %= TICKS_PER_MINUTE;
2515 g_message("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2519 system_time->wSecond = rem / TICKS_PER_SECOND;
2520 rem %= TICKS_PER_SECOND;
2522 g_message("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2526 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2528 g_message("%s: Milliseconds: %d", __func__,
2529 system_time->wMilliseconds);
2532 /* January 1, 1601 was a Monday, according to Emacs calendar */
2533 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2535 g_message("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2538 /* This algorithm to find year and month given days from epoch
2543 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2544 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2546 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2547 /* Guess a corrected year, assuming 365 days per year */
2548 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2550 g_message("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2553 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2554 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2557 /* Adjust days and y to match the guessed year. */
2558 totaldays -= ((yg - y) * 365
2559 + LEAPS_THRU_END_OF (yg - 1)
2560 - LEAPS_THRU_END_OF (y - 1));
2562 g_message("%s: totaldays: %lld", __func__, totaldays);
2566 g_message("%s: y: %lld", __func__, y);
2570 system_time->wYear = y;
2572 g_message("%s: Year: %d", __func__, system_time->wYear);
2575 ip = mon_yday[isleap(y)];
2577 for(y=11; totaldays < ip[y]; --y) {
2582 g_message("%s: totaldays: %lld", __func__, totaldays);
2585 system_time->wMonth = y + 1;
2587 g_message("%s: Month: %d", __func__, system_time->wMonth);
2590 system_time->wDay = totaldays + 1;
2592 g_message("%s: Day: %d", __func__, system_time->wDay);
2599 file_compare (gconstpointer a, gconstpointer b)
2601 gchar *astr = *(gchar **) a;
2602 gchar *bstr = *(gchar **) b;
2604 return strcmp (astr, bstr);
2608 get_errno_from_g_file_error (gint error)
2612 case G_FILE_ERROR_ACCES:
2617 case G_FILE_ERROR_NAMETOOLONG:
2618 error = ENAMETOOLONG;
2622 case G_FILE_ERROR_NOENT:
2627 case G_FILE_ERROR_NOTDIR:
2632 case G_FILE_ERROR_NXIO:
2637 case G_FILE_ERROR_NODEV:
2642 case G_FILE_ERROR_ROFS:
2647 case G_FILE_ERROR_TXTBSY:
2652 case G_FILE_ERROR_FAULT:
2657 case G_FILE_ERROR_LOOP:
2662 case G_FILE_ERROR_NOSPC:
2667 case G_FILE_ERROR_NOMEM:
2672 case G_FILE_ERROR_MFILE:
2677 case G_FILE_ERROR_NFILE:
2682 case G_FILE_ERROR_BADF:
2687 case G_FILE_ERROR_INVAL:
2692 case G_FILE_ERROR_PIPE:
2697 case G_FILE_ERROR_AGAIN:
2702 case G_FILE_ERROR_INTR:
2707 case G_FILE_ERROR_IO:
2712 case G_FILE_ERROR_PERM:
2716 case G_FILE_ERROR_FAILED:
2717 error = ERROR_INVALID_PARAMETER;
2724 /* scandir using glib */
2726 mono_io_scandir (const gchar *dirname, const gchar *pattern, gchar ***namelist)
2728 GError *error = NULL;
2733 GPatternSpec *patspec;
2735 dir = _wapi_g_dir_open (dirname, 0, &error);
2737 /* g_dir_open returns ENOENT on directories on which we don't
2738 * have read/x permission */
2739 gint errnum = get_errno_from_g_file_error (error->code);
2740 g_error_free (error);
2741 if (errnum == ENOENT &&
2742 !_wapi_access (dirname, F_OK) &&
2743 _wapi_access (dirname, R_OK|X_OK)) {
2751 patspec = g_pattern_spec_new (pattern);
2752 names = g_ptr_array_new ();
2753 while ((name = g_dir_read_name (dir)) != NULL) {
2754 if (g_pattern_match_string (patspec, name))
2755 g_ptr_array_add (names, g_strdup (name));
2758 g_pattern_spec_free (patspec);
2760 result = names->len;
2762 g_ptr_array_sort (names, file_compare);
2763 g_ptr_array_set_size (names, result + 1);
2765 *namelist = (gchar **) g_ptr_array_free (names, FALSE);
2767 g_ptr_array_free (names, TRUE);
2773 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2775 struct _WapiHandle_find find_handle = {0};
2777 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2780 if (pattern == NULL) {
2782 g_message ("%s: pattern is NULL", __func__);
2785 SetLastError (ERROR_PATH_NOT_FOUND);
2786 return(INVALID_HANDLE_VALUE);
2789 utf8_pattern = mono_unicode_to_external (pattern);
2790 if (utf8_pattern == NULL) {
2792 g_message ("%s: unicode conversion returned NULL", __func__);
2795 SetLastError (ERROR_INVALID_NAME);
2796 return(INVALID_HANDLE_VALUE);
2800 g_message ("%s: looking for [%s]", __func__, utf8_pattern);
2803 /* Figure out which bit of the pattern is the directory */
2804 dir_part = _wapi_dirname (utf8_pattern);
2805 entry_part = _wapi_basename (utf8_pattern);
2808 /* Don't do this check for now, it breaks if directories
2809 * really do have metachars in their names (see bug 58116).
2810 * FIXME: Figure out a better solution to keep some checks...
2812 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2813 SetLastError (ERROR_INVALID_NAME);
2815 g_free (entry_part);
2816 g_free (utf8_pattern);
2817 return(INVALID_HANDLE_VALUE);
2821 /* The pattern can specify a directory or a set of files.
2823 * The pattern can have wildcard characters ? and *, but only
2824 * in the section after the last directory delimiter. (Return
2825 * ERROR_INVALID_NAME if there are wildcards in earlier path
2826 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2827 * means "match one character", "??" seems to mean "match one
2828 * or two characters", "???" seems to mean "match one, two or
2829 * three characters", etc. Windows will also try and match
2830 * the mangled "short name" of files, so 8 character patterns
2831 * with wildcards will show some surprising results.
2833 * All the written documentation I can find says that '?'
2834 * should only match one character, and doesn't mention '??',
2835 * '???' etc. I'm going to assume that the strict behaviour
2836 * (ie '???' means three and only three characters) is the
2837 * correct one, because that lets me use fnmatch(3) rather
2838 * than mess around with regexes.
2841 find_handle.namelist = NULL;
2842 result = mono_io_scandir (dir_part, entry_part, &find_handle.namelist);
2845 /* No files, which windows seems to call
2848 SetLastError (ERROR_FILE_NOT_FOUND);
2849 g_free (utf8_pattern);
2850 g_free (entry_part);
2852 return (INVALID_HANDLE_VALUE);
2857 gint errnum = errno;
2859 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2861 g_message ("%s: scandir error: %s", __func__,
2862 g_strerror (errnum));
2864 g_free (utf8_pattern);
2865 g_free (entry_part);
2867 return (INVALID_HANDLE_VALUE);
2870 g_free (utf8_pattern);
2871 g_free (entry_part);
2874 g_message ("%s: Got %d matches", __func__, result);
2877 find_handle.dir_part = dir_part;
2878 find_handle.num = result;
2879 find_handle.count = 0;
2881 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2882 if (handle == _WAPI_HANDLE_INVALID) {
2883 g_warning ("%s: error creating find handle", __func__);
2885 g_free (entry_part);
2886 g_free (utf8_pattern);
2887 SetLastError (ERROR_GEN_FAILURE);
2889 return(INVALID_HANDLE_VALUE);
2892 if (handle != INVALID_HANDLE_VALUE &&
2893 !FindNextFile (handle, find_data)) {
2895 SetLastError (ERROR_NO_MORE_FILES);
2896 handle = INVALID_HANDLE_VALUE;
2902 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2904 struct _WapiHandle_find *find_handle;
2908 gchar *utf8_filename, *utf8_basename;
2909 gunichar2 *utf16_basename;
2913 gboolean ret = FALSE;
2915 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2916 (gpointer *)&find_handle);
2918 g_warning ("%s: error looking up find handle %p", __func__,
2920 SetLastError (ERROR_INVALID_HANDLE);
2924 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2926 thr_ret = _wapi_handle_lock_handle (handle);
2927 g_assert (thr_ret == 0);
2930 if (find_handle->count >= find_handle->num) {
2931 SetLastError (ERROR_NO_MORE_FILES);
2935 /* stat next match */
2937 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2938 if (_wapi_lstat (filename, &buf) != 0) {
2940 g_message ("%s: stat failed: %s", __func__, filename);
2947 /* Check for dangling symlinks, and ignore them (principle of
2948 * least surprise, avoiding confusion where we report the file
2949 * exists, but when someone tries to open it we would report
2952 if(S_ISLNK (buf.st_mode)) {
2953 if(_wapi_stat (filename, &buf) != 0) {
2959 utf8_filename = mono_utf8_from_external (filename);
2960 if (utf8_filename == NULL) {
2961 /* We couldn't turn this filename into utf8 (eg the
2962 * encoding of the name wasn't convertible), so just
2971 g_message ("%s: Found [%s]", __func__, utf8_filename);
2974 /* fill data block */
2976 if (buf.st_mtime < buf.st_ctime)
2977 create_time = buf.st_mtime;
2979 create_time = buf.st_ctime;
2981 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf);
2983 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2984 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2985 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2987 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2988 find_data->nFileSizeHigh = 0;
2989 find_data->nFileSizeLow = 0;
2991 find_data->nFileSizeHigh = buf.st_size >> 32;
2992 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2995 find_data->dwReserved0 = 0;
2996 find_data->dwReserved1 = 0;
2998 utf8_basename = _wapi_basename (utf8_filename);
2999 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
3001 if(utf16_basename==NULL) {
3002 g_free (utf8_basename);
3003 g_free (utf8_filename);
3008 /* utf16 is 2 * utf8 */
3011 memset (find_data->cFileName, '\0', (MAX_PATH*2));
3013 /* Truncating a utf16 string like this might leave the last
3016 memcpy (find_data->cFileName, utf16_basename,
3017 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3019 find_data->cAlternateFileName [0] = 0; /* not used */
3021 g_free (utf8_basename);
3022 g_free (utf8_filename);
3023 g_free (utf16_basename);
3026 thr_ret = _wapi_handle_unlock_handle (handle);
3027 g_assert (thr_ret == 0);
3028 pthread_cleanup_pop (0);
3035 * @wapi_handle: the find handle to close.
3037 * Closes find handle @wapi_handle
3039 * Return value: %TRUE on success, %FALSE otherwise.
3041 gboolean FindClose (gpointer handle)
3043 struct _WapiHandle_find *find_handle;
3047 if (handle == NULL) {
3048 SetLastError (ERROR_INVALID_HANDLE);
3052 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
3053 (gpointer *)&find_handle);
3055 g_warning ("%s: error looking up find handle %p", __func__,
3057 SetLastError (ERROR_INVALID_HANDLE);
3061 pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
3063 thr_ret = _wapi_handle_lock_handle (handle);
3064 g_assert (thr_ret == 0);
3066 g_strfreev (find_handle->namelist);
3067 g_free (find_handle->dir_part);
3069 thr_ret = _wapi_handle_unlock_handle (handle);
3070 g_assert (thr_ret == 0);
3071 pthread_cleanup_pop (0);
3073 _wapi_handle_unref (handle);
3080 * @name: a pointer to a NULL-terminated unicode string, that names
3081 * the directory to be created.
3082 * @security: ignored for now
3084 * Creates directory @name
3086 * Return value: %TRUE on success, %FALSE otherwise.
3088 gboolean CreateDirectory (const gunichar2 *name,
3089 WapiSecurityAttributes *security)
3096 g_message("%s: name is NULL", __func__);
3099 SetLastError (ERROR_INVALID_NAME);
3103 utf8_name = mono_unicode_to_external (name);
3104 if (utf8_name == NULL) {
3106 g_message ("%s: unicode conversion returned NULL", __func__);
3109 SetLastError (ERROR_INVALID_NAME);
3113 result = _wapi_mkdir (utf8_name, 0777);
3120 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3127 * @name: a pointer to a NULL-terminated unicode string, that names
3128 * the directory to be removed.
3130 * Removes directory @name
3132 * Return value: %TRUE on success, %FALSE otherwise.
3134 gboolean RemoveDirectory (const gunichar2 *name)
3141 g_message("%s: name is NULL", __func__);
3144 SetLastError (ERROR_INVALID_NAME);
3148 utf8_name = mono_unicode_to_external (name);
3149 if (utf8_name == NULL) {
3151 g_message ("%s: unicode conversion returned NULL", __func__);
3154 SetLastError (ERROR_INVALID_NAME);
3158 result = _wapi_rmdir (utf8_name);
3160 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3171 * GetFileAttributes:
3172 * @name: a pointer to a NULL-terminated unicode filename.
3174 * Gets the attributes for @name;
3176 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3178 guint32 GetFileAttributes (const gunichar2 *name)
3187 g_message("%s: name is NULL", __func__);
3190 SetLastError (ERROR_INVALID_NAME);
3194 utf8_name = mono_unicode_to_external (name);
3195 if (utf8_name == NULL) {
3197 g_message ("%s: unicode conversion returned NULL", __func__);
3200 SetLastError (ERROR_INVALID_PARAMETER);
3201 return (INVALID_FILE_ATTRIBUTES);
3204 result = _wapi_stat (utf8_name, &buf);
3205 if (result == -1 && errno == ENOENT) {
3206 /* Might be a dangling symlink... */
3207 result = _wapi_lstat (utf8_name, &buf);
3211 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3213 return (INVALID_FILE_ATTRIBUTES);
3216 ret = _wapi_stat_to_file_attributes (utf8_name, &buf);
3223 * GetFileAttributesEx:
3224 * @name: a pointer to a NULL-terminated unicode filename.
3225 * @level: must be GetFileExInfoStandard
3226 * @info: pointer to a WapiFileAttributesData structure
3228 * Gets attributes, size and filetimes for @name;
3230 * Return value: %TRUE on success, %FALSE on failure
3232 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3235 WapiFileAttributesData *data;
3241 if (level != GetFileExInfoStandard) {
3243 g_message ("%s: info level %d not supported.", __func__,
3247 SetLastError (ERROR_INVALID_PARAMETER);
3253 g_message("%s: name is NULL", __func__);
3256 SetLastError (ERROR_INVALID_NAME);
3260 utf8_name = mono_unicode_to_external (name);
3261 if (utf8_name == NULL) {
3263 g_message ("%s: unicode conversion returned NULL", __func__);
3266 SetLastError (ERROR_INVALID_PARAMETER);
3270 result = _wapi_stat (utf8_name, &buf);
3271 if (result == -1 && errno == ENOENT) {
3272 /* Might be a dangling symlink... */
3273 result = _wapi_lstat (utf8_name, &buf);
3277 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3282 /* fill data block */
3284 data = (WapiFileAttributesData *)info;
3286 if (buf.st_mtime < buf.st_ctime)
3287 create_time = buf.st_mtime;
3289 create_time = buf.st_ctime;
3291 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3296 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3297 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3298 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3300 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3301 data->nFileSizeHigh = 0;
3302 data->nFileSizeLow = 0;
3305 data->nFileSizeHigh = buf.st_size >> 32;
3306 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3314 * @name: name of file
3315 * @attrs: attributes to set
3317 * Changes the attributes on a named file.
3319 * Return value: %TRUE on success, %FALSE on failure.
3321 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3323 /* FIXME: think of something clever to do on unix */
3329 * Currently we only handle one *internal* case, with a value that is
3330 * not standard: 0x80000000, which means `set executable bit'
3335 g_message("%s: name is NULL", __func__);
3338 SetLastError (ERROR_INVALID_NAME);
3342 utf8_name = mono_unicode_to_external (name);
3343 if (utf8_name == NULL) {
3345 g_message ("%s: unicode conversion returned NULL", __func__);
3348 SetLastError (ERROR_INVALID_NAME);
3352 result = _wapi_stat (utf8_name, &buf);
3354 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3359 /* Contrary to the documentation, ms allows NORMAL to be
3360 * specified along with other attributes, so dont bother to
3361 * catch that case here.
3363 if (attrs & FILE_ATTRIBUTE_READONLY) {
3364 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3366 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3369 /* Ignore the other attributes for now */
3371 if (attrs & 0x80000000){
3372 mode_t exec_mask = 0;
3374 if ((buf.st_mode & S_IRUSR) != 0)
3375 exec_mask |= S_IXUSR;
3377 if ((buf.st_mode & S_IRGRP) != 0)
3378 exec_mask |= S_IXGRP;
3380 if ((buf.st_mode & S_IROTH) != 0)
3381 exec_mask |= S_IXOTH;
3383 result = chmod (utf8_name, buf.st_mode | exec_mask);
3385 /* Don't bother to reset executable (might need to change this
3395 * GetCurrentDirectory
3396 * @length: size of the buffer
3397 * @buffer: pointer to buffer that recieves path
3399 * Retrieves the current directory for the current process.
3401 * Return value: number of characters in buffer on success, zero on failure
3403 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3406 gunichar2 *utf16_path;
3410 path = g_get_current_dir ();
3414 utf16_path=mono_unicode_from_external (path, &bytes);
3416 /* if buffer too small, return number of characters required.
3417 * this is plain dumb.
3420 count = (bytes/2)+1;
3421 if (count > length) {
3423 g_free (utf16_path);
3428 /* Add the terminator */
3429 memset (buffer, '\0', bytes+2);
3430 memcpy (buffer, utf16_path, bytes);
3432 g_free (utf16_path);
3439 * SetCurrentDirectory
3440 * @path: path to new directory
3442 * Changes the directory path for the current process.
3444 * Return value: %TRUE on success, %FALSE on failure.
3446 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3452 SetLastError (ERROR_INVALID_PARAMETER);
3456 utf8_path = mono_unicode_to_external (path);
3457 if (_wapi_chdir (utf8_path) != 0) {
3458 _wapi_set_last_error_from_errno ();
3468 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3469 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3471 struct _WapiHandle_file pipe_read_handle = {0};
3472 struct _WapiHandle_file pipe_write_handle = {0};
3473 gpointer read_handle;
3474 gpointer write_handle;
3478 mono_once (&io_ops_once, io_ops_init);
3481 g_message ("%s: Creating pipe", __func__);
3487 g_message ("%s: Error creating pipe: %s", __func__,
3491 _wapi_set_last_error_from_errno ();
3495 if (filedes[0] >= _wapi_fd_reserve ||
3496 filedes[1] >= _wapi_fd_reserve) {
3498 g_message ("%s: File descriptor is too big", __func__);
3501 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3509 /* filedes[0] is open for reading, filedes[1] for writing */
3511 pipe_read_handle.fileaccess = GENERIC_READ;
3512 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3514 if (read_handle == _WAPI_HANDLE_INVALID) {
3515 g_warning ("%s: error creating pipe read handle", __func__);
3518 SetLastError (ERROR_GEN_FAILURE);
3523 pipe_write_handle.fileaccess = GENERIC_WRITE;
3524 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3525 &pipe_write_handle);
3526 if (write_handle == _WAPI_HANDLE_INVALID) {
3527 g_warning ("%s: error creating pipe write handle", __func__);
3528 _wapi_handle_unref (read_handle);
3532 SetLastError (ERROR_GEN_FAILURE);
3537 *readpipe = read_handle;
3538 *writepipe = write_handle;
3541 g_message ("%s: Returning pipe: read handle %p, write handle %p",
3542 __func__, read_handle, write_handle);
3548 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3550 gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3551 gunichar2 *tmpdir16=NULL;
3556 if(tmpdir[strlen (tmpdir)]!='/') {
3558 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3561 tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3562 if(tmpdir16==NULL) {
3570 g_message ("%s: Size %d smaller than needed (%ld)",
3571 __func__, len, dirlen+1);
3576 /* Add the terminator */
3577 memset (buf, '\0', bytes+2);
3578 memcpy (buf, tmpdir16, bytes);
3584 if(tmpdir16!=NULL) {
3593 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3596 gunichar2 *ptr, *dir;
3597 glong length, total = 0;
3601 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3606 /* Sigh, mntent and friends don't work well.
3607 * It stops on the first line that doesn't begin with a '/'.
3608 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3609 fp = fopen ("/etc/mtab", "rt");
3611 fp = fopen ("/etc/mnttab", "rt");
3617 while (fgets (buffer, 512, fp) != NULL) {
3621 splitted = g_strsplit (buffer, " ", 0);
3622 if (!*splitted || !*(splitted + 1)) {
3623 g_strfreev (splitted);
3627 dir = g_utf8_to_utf16 (*(splitted + 1), -1, &length, NULL, NULL);
3628 g_strfreev (splitted);
3629 if (total + length + 1 > len) {
3631 return len * 2; /* guess */
3634 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3636 total += length + 1;
3641 /* Commented out, does not work with my mtab!!! - Gonz */
3642 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3646 gunichar2 *ptr, *dir;
3647 glong len, total = 0;
3650 fp = setmntent ("/etc/mtab", "rt");
3652 fp = setmntent ("/etc/mnttab", "rt");
3658 while ((mnt = getmntent (fp)) != NULL) {
3659 g_print ("GOT %s\n", mnt->mnt_dir);
3660 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3661 if (total + len + 1 > len) {
3662 return len * 2; /* guess */
3665 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3676 static gboolean _wapi_lock_file_region (int fd, off_t offset, off_t length)
3678 struct flock lock_data;
3681 lock_data.l_type = F_WRLCK;
3682 lock_data.l_whence = SEEK_SET;
3683 lock_data.l_start = offset;
3684 lock_data.l_len = length;
3687 ret = fcntl (fd, F_SETLK, &lock_data);
3688 } while(ret == -1 && errno == EINTR);
3691 g_message ("%s: fcntl returns %d", __func__, ret);
3696 * if locks are not available (NFS for example),
3701 || errno == EOPNOTSUPP
3710 SetLastError (ERROR_LOCK_VIOLATION);
3717 static gboolean _wapi_unlock_file_region (int fd, off_t offset, off_t length)
3719 struct flock lock_data;
3722 lock_data.l_type = F_UNLCK;
3723 lock_data.l_whence = SEEK_SET;
3724 lock_data.l_start = offset;
3725 lock_data.l_len = length;
3728 ret = fcntl (fd, F_SETLK, &lock_data);
3729 } while(ret == -1 && errno == EINTR);
3732 g_message ("%s: fcntl returns %d", __func__, ret);
3737 * if locks are not available (NFS for example),
3742 || errno == EOPNOTSUPP
3751 SetLastError (ERROR_LOCK_VIOLATION);
3758 gboolean LockFile (gpointer handle, guint32 offset_low, guint32 offset_high,
3759 guint32 length_low, guint32 length_high)
3761 struct _WapiHandle_file *file_handle;
3763 off_t offset, length;
3764 int fd = GPOINTER_TO_UINT(handle);
3766 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
3767 (gpointer *)&file_handle);
3769 g_warning ("%s: error looking up file handle %p", __func__,
3771 SetLastError (ERROR_INVALID_HANDLE);
3775 if (!(file_handle->fileaccess & GENERIC_READ) &&
3776 !(file_handle->fileaccess & GENERIC_WRITE) &&
3777 !(file_handle->fileaccess & GENERIC_ALL)) {
3779 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
3781 SetLastError (ERROR_ACCESS_DENIED);
3785 #ifdef HAVE_LARGE_FILE_SUPPORT
3786 offset = ((gint64)offset_high << 32) | offset_low;
3787 length = ((gint64)length_high << 32) | length_low;
3790 g_message ("%s: Locking handle %p, offset %lld, length %lld", __func__,
3791 handle, offset, length);
3794 offset = offset_low;
3795 length = length_low;
3798 g_message ("%s: Locking handle %p, offset %ld, length %ld", __func__,
3799 handle, offset, length);
3803 return(_wapi_lock_file_region (fd, offset, length));
3806 gboolean UnlockFile (gpointer handle, guint32 offset_low,
3807 guint32 offset_high, guint32 length_low,
3808 guint32 length_high)
3810 struct _WapiHandle_file *file_handle;
3812 off_t offset, length;
3813 int fd = GPOINTER_TO_UINT(handle);
3815 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
3816 (gpointer *)&file_handle);
3818 g_warning ("%s: error looking up file handle %p", __func__,
3820 SetLastError (ERROR_INVALID_HANDLE);
3824 if (!(file_handle->fileaccess & GENERIC_READ) &&
3825 !(file_handle->fileaccess & GENERIC_WRITE) &&
3826 !(file_handle->fileaccess & GENERIC_ALL)) {
3828 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
3830 SetLastError (ERROR_ACCESS_DENIED);
3834 #ifdef HAVE_LARGE_FILE_SUPPORT
3835 offset = ((gint64)offset_high << 32) | offset_low;
3836 length = ((gint64)length_high << 32) | length_low;
3839 g_message ("%s: Unlocking handle %p, offset %lld, length %lld",
3840 __func__, handle, offset, length);
3843 offset = offset_low;
3844 length = length_low;
3847 g_message ("%s: Unlocking handle %p, offset %ld, length %ld", __func__,
3848 handle, offset, length);
3852 return(_wapi_unlock_file_region (fd, offset, length));