2 * io.c: File, console and find handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002 Ximian, Inc.
8 * Copyright (c) 2002-2006 Novell, Inc.
9 * Copyright 2011 Xamarin Inc (http://www.xamarin.com).
19 #ifdef HAVE_SYS_STATVFS_H
20 #include <sys/statvfs.h>
22 #if defined(HAVE_SYS_STATFS_H)
23 #include <sys/statfs.h>
25 #if defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H)
26 #include <sys/param.h>
27 #include <sys/mount.h>
29 #include <sys/types.h>
33 #include <sys/ioctl.h>
35 #include <mono/utils/linux_magic.h>
38 #include <mono/io-layer/wapi.h>
39 #include <mono/io-layer/wapi-private.h>
40 #include <mono/io-layer/handles-private.h>
41 #include <mono/io-layer/io-private.h>
42 #include <mono/io-layer/timefuncs-private.h>
43 #include <mono/io-layer/thread-private.h>
44 #include <mono/io-layer/io-portability.h>
45 #include <mono/io-layer/io-trace.h>
46 #include <mono/utils/strenc.h>
47 #include <mono/utils/mono-once.h>
48 #include <mono/utils/mono-logger-internals.h>
50 static void file_close (gpointer handle, gpointer data);
51 static WapiFileType file_getfiletype(void);
52 static gboolean file_read(gpointer handle, gpointer buffer,
53 guint32 numbytes, guint32 *bytesread,
54 WapiOverlapped *overlapped);
55 static gboolean file_write(gpointer handle, gconstpointer buffer,
56 guint32 numbytes, guint32 *byteswritten,
57 WapiOverlapped *overlapped);
58 static gboolean file_flush(gpointer handle);
59 static guint32 file_seek(gpointer handle, gint32 movedistance,
60 gint32 *highmovedistance, WapiSeekMethod method);
61 static gboolean file_setendoffile(gpointer handle);
62 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
63 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
64 WapiFileTime *last_access,
65 WapiFileTime *last_write);
66 static gboolean file_setfiletime(gpointer handle,
67 const WapiFileTime *create_time,
68 const WapiFileTime *last_access,
69 const WapiFileTime *last_write);
70 static guint32 GetDriveTypeFromPath (const gchar *utf8_root_path_name);
72 /* File handle is only signalled for overlapped IO */
73 struct _WapiHandleOps _wapi_file_ops = {
74 file_close, /* close */
78 NULL, /* special_wait */
82 void _wapi_file_details (gpointer handle_info)
84 struct _WapiHandle_file *file = (struct _WapiHandle_file *)handle_info;
86 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
88 file->fileaccess&GENERIC_READ?'R':'.',
89 file->fileaccess&GENERIC_WRITE?'W':'.',
90 file->fileaccess&GENERIC_EXECUTE?'X':'.',
91 file->sharemode&FILE_SHARE_READ?'R':'.',
92 file->sharemode&FILE_SHARE_WRITE?'W':'.',
93 file->sharemode&FILE_SHARE_DELETE?'D':'.',
97 static void console_close (gpointer handle, gpointer data);
98 static WapiFileType console_getfiletype(void);
99 static gboolean console_read(gpointer handle, gpointer buffer,
100 guint32 numbytes, guint32 *bytesread,
101 WapiOverlapped *overlapped);
102 static gboolean console_write(gpointer handle, gconstpointer buffer,
103 guint32 numbytes, guint32 *byteswritten,
104 WapiOverlapped *overlapped);
106 /* Console is mostly the same as file, except it can block waiting for
109 struct _WapiHandleOps _wapi_console_ops = {
110 console_close, /* close */
114 NULL, /* special_wait */
118 void _wapi_console_details (gpointer handle_info)
120 _wapi_file_details (handle_info);
123 /* Find handle has no ops.
125 struct _WapiHandleOps _wapi_find_ops = {
130 NULL, /* special_wait */
134 static void pipe_close (gpointer handle, gpointer data);
135 static WapiFileType pipe_getfiletype (void);
136 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
137 guint32 *bytesread, WapiOverlapped *overlapped);
138 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
139 guint32 numbytes, guint32 *byteswritten,
140 WapiOverlapped *overlapped);
144 struct _WapiHandleOps _wapi_pipe_ops = {
145 pipe_close, /* close */
149 NULL, /* special_wait */
153 void _wapi_pipe_details (gpointer handle_info)
155 _wapi_file_details (handle_info);
158 static const struct {
159 /* File, console and pipe handles */
160 WapiFileType (*getfiletype)(void);
162 /* File, console and pipe handles */
163 gboolean (*readfile)(gpointer handle, gpointer buffer,
164 guint32 numbytes, guint32 *bytesread,
165 WapiOverlapped *overlapped);
166 gboolean (*writefile)(gpointer handle, gconstpointer buffer,
167 guint32 numbytes, guint32 *byteswritten,
168 WapiOverlapped *overlapped);
169 gboolean (*flushfile)(gpointer handle);
172 guint32 (*seek)(gpointer handle, gint32 movedistance,
173 gint32 *highmovedistance, WapiSeekMethod method);
174 gboolean (*setendoffile)(gpointer handle);
175 guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
176 gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
177 WapiFileTime *last_access,
178 WapiFileTime *last_write);
179 gboolean (*setfiletime)(gpointer handle,
180 const WapiFileTime *create_time,
181 const WapiFileTime *last_access,
182 const WapiFileTime *last_write);
183 } io_ops[WAPI_HANDLE_COUNT]={
184 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
187 file_read, file_write,
188 file_flush, file_seek,
194 {console_getfiletype,
197 NULL, NULL, NULL, NULL, NULL, NULL},
199 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
201 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
203 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
205 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
206 /* socket (will need at least read and write) */
207 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
209 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
211 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
216 NULL, NULL, NULL, NULL, NULL, NULL},
219 static mono_once_t io_ops_once=MONO_ONCE_INIT;
220 static gboolean lock_while_writing = FALSE;
222 static void io_ops_init (void)
224 /* _wapi_handle_register_capabilities (WAPI_HANDLE_FILE, */
225 /* WAPI_HANDLE_CAP_WAIT); */
226 /* _wapi_handle_register_capabilities (WAPI_HANDLE_CONSOLE, */
227 /* WAPI_HANDLE_CAP_WAIT); */
229 if (g_getenv ("MONO_STRICT_IO_EMULATION") != NULL) {
230 lock_while_writing = TRUE;
234 /* Some utility functions.
238 * Check if a file is writable by the current user.
240 * This is is a best effort kind of thing. It assumes a reasonable sane set
241 * of permissions by the underlying OS.
243 * We assume that basic unix permission bits are authoritative. Which might not
244 * be the case under systems with extended permissions systems (posix ACLs, SELinux, OSX/iOS sandboxing, etc)
246 * The choice of access as the fallback is due to the expected lower overhead compared to trying to open the file.
248 * The only expected problem with using access are for root, setuid or setgid programs as access is not consistent
249 * under those situations. It's to be expected that this should not happen in practice as those bits are very dangerous
250 * and should not be used with a dynamic runtime.
253 is_file_writable (struct stat *st, const char *path)
255 /* Is it globally writable? */
256 if (st->st_mode & S_IWOTH)
259 /* Am I the owner? */
260 if ((st->st_uid == geteuid ()) && (st->st_mode & S_IWUSR))
263 /* Am I in the same group? */
264 if ((st->st_gid == getegid ()) && (st->st_mode & S_IWGRP))
267 /* Fallback to using access(2). It's not ideal as it might not take into consideration euid/egid
268 * but it's the only sane option we have on unix.
270 return access (path, W_OK) == 0;
274 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
281 /* FIXME: this could definitely be better, but there seems to
282 * be no pattern to the attributes that are set
285 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
286 if (S_ISSOCK (buf->st_mode))
287 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
289 filename = _wapi_basename (pathname);
291 if (S_ISDIR (buf->st_mode)) {
292 attrs = FILE_ATTRIBUTE_DIRECTORY;
293 if (!is_file_writable (buf, pathname)) {
294 attrs |= FILE_ATTRIBUTE_READONLY;
296 if (filename[0] == '.') {
297 attrs |= FILE_ATTRIBUTE_HIDDEN;
300 if (!is_file_writable (buf, pathname)) {
301 attrs = FILE_ATTRIBUTE_READONLY;
303 if (filename[0] == '.') {
304 attrs |= FILE_ATTRIBUTE_HIDDEN;
306 } else if (filename[0] == '.') {
307 attrs = FILE_ATTRIBUTE_HIDDEN;
309 attrs = FILE_ATTRIBUTE_NORMAL;
314 if (S_ISLNK (lbuf->st_mode)) {
315 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
325 _wapi_set_last_error_from_errno (void)
327 SetLastError (_wapi_get_win32_file_error (errno));
330 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
333 if (errno == ENOENT) {
334 /* Check the path - if it's a missing directory then
335 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
341 dirname = _wapi_dirname (path);
343 dirname = g_strdup (dir);
346 if (_wapi_access (dirname, F_OK) == 0) {
347 SetLastError (ERROR_FILE_NOT_FOUND);
349 SetLastError (ERROR_PATH_NOT_FOUND);
354 _wapi_set_last_error_from_errno ();
360 static void file_close (gpointer handle, gpointer data)
362 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
363 int fd = file_handle->fd;
365 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing file handle %p [%s]", __func__, handle,
366 file_handle->filename);
368 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
369 _wapi_unlink (file_handle->filename);
371 g_free (file_handle->filename);
373 if (file_handle->share_info)
374 _wapi_handle_share_release (file_handle->share_info);
379 static WapiFileType file_getfiletype(void)
381 return(FILE_TYPE_DISK);
384 static gboolean file_read(gpointer handle, gpointer buffer,
385 guint32 numbytes, guint32 *bytesread,
386 WapiOverlapped *overlapped)
388 struct _WapiHandle_file *file_handle;
392 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
393 (gpointer *)&file_handle);
395 g_warning ("%s: error looking up file handle %p", __func__,
397 SetLastError (ERROR_INVALID_HANDLE);
401 fd = file_handle->fd;
402 if(bytesread!=NULL) {
406 if(!(file_handle->fileaccess & GENERIC_READ) &&
407 !(file_handle->fileaccess & GENERIC_ALL)) {
408 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
409 __func__, handle, file_handle->fileaccess);
411 SetLastError (ERROR_ACCESS_DENIED);
416 ret = read (fd, buffer, numbytes);
417 } while (ret == -1 && errno == EINTR &&
418 !_wapi_thread_cur_apc_pending());
423 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
424 handle, strerror(err));
425 SetLastError (_wapi_get_win32_file_error (err));
429 if (bytesread != NULL) {
436 static gboolean file_write(gpointer handle, gconstpointer buffer,
437 guint32 numbytes, guint32 *byteswritten,
438 WapiOverlapped *overlapped G_GNUC_UNUSED)
440 struct _WapiHandle_file *file_handle;
443 off_t current_pos = 0;
445 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
446 (gpointer *)&file_handle);
448 g_warning ("%s: error looking up file handle %p", __func__,
450 SetLastError (ERROR_INVALID_HANDLE);
454 fd = file_handle->fd;
456 if(byteswritten!=NULL) {
460 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
461 !(file_handle->fileaccess & GENERIC_ALL)) {
462 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
464 SetLastError (ERROR_ACCESS_DENIED);
468 if (lock_while_writing) {
469 /* Need to lock the region we're about to write to,
470 * because we only do advisory locking on POSIX
473 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
474 if (current_pos == -1) {
475 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
476 handle, strerror (errno));
477 _wapi_set_last_error_from_errno ();
481 if (_wapi_lock_file_region (fd, current_pos,
482 numbytes) == FALSE) {
483 /* The error has already been set */
489 ret = write (fd, buffer, numbytes);
490 } while (ret == -1 && errno == EINTR &&
491 !_wapi_thread_cur_apc_pending());
493 if (lock_while_writing) {
494 _wapi_unlock_file_region (fd, current_pos, numbytes);
498 if (errno == EINTR) {
501 _wapi_set_last_error_from_errno ();
503 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
504 __func__, handle, strerror(errno));
509 if (byteswritten != NULL) {
515 static gboolean file_flush(gpointer handle)
517 struct _WapiHandle_file *file_handle;
521 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
522 (gpointer *)&file_handle);
524 g_warning ("%s: error looking up file handle %p", __func__,
526 SetLastError (ERROR_INVALID_HANDLE);
530 fd = file_handle->fd;
532 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
533 !(file_handle->fileaccess & GENERIC_ALL)) {
534 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
536 SetLastError (ERROR_ACCESS_DENIED);
542 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fsync of handle %p error: %s", __func__, handle,
545 _wapi_set_last_error_from_errno ();
552 static guint32 file_seek(gpointer handle, gint32 movedistance,
553 gint32 *highmovedistance, WapiSeekMethod method)
555 struct _WapiHandle_file *file_handle;
557 gint64 offset, newpos;
561 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
562 (gpointer *)&file_handle);
564 g_warning ("%s: error looking up file handle %p", __func__,
566 SetLastError (ERROR_INVALID_HANDLE);
567 return(INVALID_SET_FILE_POINTER);
570 fd = file_handle->fd;
572 if(!(file_handle->fileaccess & GENERIC_READ) &&
573 !(file_handle->fileaccess & GENERIC_WRITE) &&
574 !(file_handle->fileaccess & GENERIC_ALL)) {
575 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
577 SetLastError (ERROR_ACCESS_DENIED);
578 return(INVALID_SET_FILE_POINTER);
592 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: invalid seek type %d", __func__, method);
594 SetLastError (ERROR_INVALID_PARAMETER);
595 return(INVALID_SET_FILE_POINTER);
598 #ifdef HAVE_LARGE_FILE_SUPPORT
599 if(highmovedistance==NULL) {
601 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting offset to %lld (low %d)", __func__,
602 offset, movedistance);
604 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
606 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting offset to %lld 0x%llx (high %d 0x%x, low %d 0x%x)", __func__, offset, offset, *highmovedistance, *highmovedistance, movedistance, movedistance);
612 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: moving handle %p by %lld bytes from %d", __func__,
613 handle, (long long)offset, whence);
615 #ifdef PLATFORM_ANDROID
616 /* bionic doesn't support -D_FILE_OFFSET_BITS=64 */
617 newpos=lseek64(fd, offset, whence);
619 newpos=lseek(fd, offset, whence);
622 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek on handle %p returned error %s",
623 __func__, handle, strerror(errno));
625 _wapi_set_last_error_from_errno ();
626 return(INVALID_SET_FILE_POINTER);
629 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek returns %lld", __func__, newpos);
631 #ifdef HAVE_LARGE_FILE_SUPPORT
632 ret=newpos & 0xFFFFFFFF;
633 if(highmovedistance!=NULL) {
634 *highmovedistance=newpos>>32;
638 if(highmovedistance!=NULL) {
639 /* Accurate, but potentially dodgy :-) */
644 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: move of handle %p returning %d/%d", __func__,
645 handle, ret, highmovedistance==NULL?0:*highmovedistance);
650 static gboolean file_setendoffile(gpointer handle)
652 struct _WapiHandle_file *file_handle;
658 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
659 (gpointer *)&file_handle);
661 g_warning ("%s: error looking up file handle %p", __func__,
663 SetLastError (ERROR_INVALID_HANDLE);
666 fd = file_handle->fd;
668 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
669 !(file_handle->fileaccess & GENERIC_ALL)) {
670 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
672 SetLastError (ERROR_ACCESS_DENIED);
676 /* Find the current file position, and the file length. If
677 * the file position is greater than the length, write to
678 * extend the file with a hole. If the file position is less
679 * than the length, truncate the file.
682 ret=fstat(fd, &statbuf);
684 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
685 handle, strerror(errno));
687 _wapi_set_last_error_from_errno ();
691 pos=lseek(fd, (off_t)0, SEEK_CUR);
693 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
694 handle, strerror(errno));
696 _wapi_set_last_error_from_errno ();
700 #ifdef FTRUNCATE_DOESNT_EXTEND
701 off_t size = statbuf.st_size;
702 /* I haven't bothered to write the configure.ac stuff for this
703 * because I don't know if any platform needs it. I'm leaving
704 * this code just in case though
707 /* Extend the file. Use write() here, because some
708 * manuals say that ftruncate() behaviour is undefined
709 * when the file needs extending. The POSIX spec says
710 * that on XSI-conformant systems it extends, so if
711 * every system we care about conforms, then we can
715 ret = write (fd, "", 1);
716 } while (ret == -1 && errno == EINTR &&
717 !_wapi_thread_cur_apc_pending());
720 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
722 _wapi_set_last_error_from_errno ();
726 /* And put the file position back after the write */
727 ret = lseek (fd, pos, SEEK_SET);
729 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p second lseek failed: %s",
730 __func__, handle, strerror(errno));
732 _wapi_set_last_error_from_errno ();
738 /* Native Client has no ftruncate function, even in standalone sel_ldr. */
739 #ifndef __native_client__
740 /* always truncate, because the extend write() adds an extra
741 * byte to the end of the file
744 ret=ftruncate(fd, pos);
746 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
748 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ftruncate failed: %s", __func__,
749 handle, strerror(errno));
751 _wapi_set_last_error_from_errno ();
759 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
761 struct _WapiHandle_file *file_handle;
768 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
769 (gpointer *)&file_handle);
771 g_warning ("%s: error looking up file handle %p", __func__,
773 SetLastError (ERROR_INVALID_HANDLE);
774 return(INVALID_FILE_SIZE);
776 fd = file_handle->fd;
778 if(!(file_handle->fileaccess & GENERIC_READ) &&
779 !(file_handle->fileaccess & GENERIC_WRITE) &&
780 !(file_handle->fileaccess & GENERIC_ALL)) {
781 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
783 SetLastError (ERROR_ACCESS_DENIED);
784 return(INVALID_FILE_SIZE);
787 /* If the file has a size with the low bits 0xFFFFFFFF the
788 * caller can't tell if this is an error, so clear the error
791 SetLastError (ERROR_SUCCESS);
793 ret = fstat(fd, &statbuf);
795 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
796 handle, strerror(errno));
798 _wapi_set_last_error_from_errno ();
799 return(INVALID_FILE_SIZE);
802 /* fstat indicates block devices as zero-length, so go a different path */
804 if (S_ISBLK(statbuf.st_mode)) {
806 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
807 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ioctl BLKGETSIZE64 failed: %s",
808 __func__, handle, strerror(errno));
810 _wapi_set_last_error_from_errno ();
811 return(INVALID_FILE_SIZE);
814 size = bigsize & 0xFFFFFFFF;
815 if (highsize != NULL) {
816 *highsize = bigsize>>32;
819 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning block device size %d/%d",
820 __func__, size, *highsize);
826 #ifdef HAVE_LARGE_FILE_SUPPORT
827 size = statbuf.st_size & 0xFFFFFFFF;
828 if (highsize != NULL) {
829 *highsize = statbuf.st_size>>32;
832 if (highsize != NULL) {
833 /* Accurate, but potentially dodgy :-) */
836 size = statbuf.st_size;
839 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning size %d/%d", __func__, size, *highsize);
844 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
845 WapiFileTime *last_access,
846 WapiFileTime *last_write)
848 struct _WapiHandle_file *file_handle;
851 guint64 create_ticks, access_ticks, write_ticks;
854 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
855 (gpointer *)&file_handle);
857 g_warning ("%s: error looking up file handle %p", __func__,
859 SetLastError (ERROR_INVALID_HANDLE);
862 fd = file_handle->fd;
864 if(!(file_handle->fileaccess & GENERIC_READ) &&
865 !(file_handle->fileaccess & GENERIC_ALL)) {
866 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
867 __func__, handle, file_handle->fileaccess);
869 SetLastError (ERROR_ACCESS_DENIED);
873 ret=fstat(fd, &statbuf);
875 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
878 _wapi_set_last_error_from_errno ();
882 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: atime: %ld ctime: %ld mtime: %ld", __func__,
883 statbuf.st_atime, statbuf.st_ctime,
886 /* Try and guess a meaningful create time by using the older
889 /* The magic constant comes from msdn documentation
890 * "Converting a time_t Value to a File Time"
892 if(statbuf.st_atime < statbuf.st_ctime) {
893 create_ticks=((guint64)statbuf.st_atime*10000000)
894 + 116444736000000000ULL;
896 create_ticks=((guint64)statbuf.st_ctime*10000000)
897 + 116444736000000000ULL;
900 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
901 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
903 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
904 access_ticks, create_ticks, write_ticks);
906 if(create_time!=NULL) {
907 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
908 create_time->dwHighDateTime = create_ticks >> 32;
911 if(last_access!=NULL) {
912 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
913 last_access->dwHighDateTime = access_ticks >> 32;
916 if(last_write!=NULL) {
917 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
918 last_write->dwHighDateTime = write_ticks >> 32;
924 static gboolean file_setfiletime(gpointer handle,
925 const WapiFileTime *create_time G_GNUC_UNUSED,
926 const WapiFileTime *last_access,
927 const WapiFileTime *last_write)
929 struct _WapiHandle_file *file_handle;
931 struct utimbuf utbuf;
933 guint64 access_ticks, write_ticks;
936 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
937 (gpointer *)&file_handle);
939 g_warning ("%s: error looking up file handle %p", __func__,
941 SetLastError (ERROR_INVALID_HANDLE);
944 fd = file_handle->fd;
946 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
947 !(file_handle->fileaccess & GENERIC_ALL)) {
948 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
950 SetLastError (ERROR_ACCESS_DENIED);
954 if(file_handle->filename == NULL) {
955 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p unknown filename", __func__, handle);
957 SetLastError (ERROR_INVALID_HANDLE);
961 /* Get the current times, so we can put the same times back in
962 * the event that one of the FileTime structs is NULL
964 ret=fstat (fd, &statbuf);
966 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
969 SetLastError (ERROR_INVALID_PARAMETER);
973 if(last_access!=NULL) {
974 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
975 last_access->dwLowDateTime;
976 /* This is (time_t)0. We can actually go to INT_MIN,
977 * but this will do for now.
979 if (access_ticks < 116444736000000000ULL) {
980 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set access time too early",
982 SetLastError (ERROR_INVALID_PARAMETER);
986 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
988 utbuf.actime=statbuf.st_atime;
991 if(last_write!=NULL) {
992 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
993 last_write->dwLowDateTime;
994 /* This is (time_t)0. We can actually go to INT_MIN,
995 * but this will do for now.
997 if (write_ticks < 116444736000000000ULL) {
998 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set write time too early",
1000 SetLastError (ERROR_INVALID_PARAMETER);
1004 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1006 utbuf.modtime=statbuf.st_mtime;
1009 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting handle %p access %ld write %ld", __func__,
1010 handle, utbuf.actime, utbuf.modtime);
1012 ret = _wapi_utime (file_handle->filename, &utbuf);
1014 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p [%s] utime failed: %s", __func__,
1015 handle, file_handle->filename, strerror(errno));
1017 SetLastError (ERROR_INVALID_PARAMETER);
1024 static void console_close (gpointer handle, gpointer data)
1026 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1027 int fd = console_handle->fd;
1029 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing console handle %p", __func__, handle);
1031 g_free (console_handle->filename);
1037 static WapiFileType console_getfiletype(void)
1039 return(FILE_TYPE_CHAR);
1042 static gboolean console_read(gpointer handle, gpointer buffer,
1043 guint32 numbytes, guint32 *bytesread,
1044 WapiOverlapped *overlapped G_GNUC_UNUSED)
1046 struct _WapiHandle_file *console_handle;
1050 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1051 (gpointer *)&console_handle);
1053 g_warning ("%s: error looking up console handle %p", __func__,
1055 SetLastError (ERROR_INVALID_HANDLE);
1058 fd = console_handle->fd;
1060 if(bytesread!=NULL) {
1064 if(!(console_handle->fileaccess & GENERIC_READ) &&
1065 !(console_handle->fileaccess & GENERIC_ALL)) {
1066 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1067 __func__, handle, console_handle->fileaccess);
1069 SetLastError (ERROR_ACCESS_DENIED);
1074 ret=read(fd, buffer, numbytes);
1075 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1078 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__, handle,
1081 _wapi_set_last_error_from_errno ();
1085 if(bytesread!=NULL) {
1092 static gboolean console_write(gpointer handle, gconstpointer buffer,
1093 guint32 numbytes, guint32 *byteswritten,
1094 WapiOverlapped *overlapped G_GNUC_UNUSED)
1096 struct _WapiHandle_file *console_handle;
1100 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1101 (gpointer *)&console_handle);
1103 g_warning ("%s: error looking up console handle %p", __func__,
1105 SetLastError (ERROR_INVALID_HANDLE);
1108 fd = console_handle->fd;
1110 if(byteswritten!=NULL) {
1114 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1115 !(console_handle->fileaccess & GENERIC_ALL)) {
1116 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, console_handle->fileaccess);
1118 SetLastError (ERROR_ACCESS_DENIED);
1123 ret = write(fd, buffer, numbytes);
1124 } while (ret == -1 && errno == EINTR &&
1125 !_wapi_thread_cur_apc_pending());
1128 if (errno == EINTR) {
1131 _wapi_set_last_error_from_errno ();
1133 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
1134 __func__, handle, strerror(errno));
1139 if(byteswritten!=NULL) {
1146 static void pipe_close (gpointer handle, gpointer data)
1148 struct _WapiHandle_file *pipe_handle = (struct _WapiHandle_file*)data;
1149 int fd = pipe_handle->fd;
1151 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing pipe handle %p", __func__, handle);
1153 /* No filename with pipe handles */
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;
1171 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1172 (gpointer *)&pipe_handle);
1174 g_warning ("%s: error looking up pipe handle %p", __func__,
1176 SetLastError (ERROR_INVALID_HANDLE);
1179 fd = pipe_handle->fd;
1181 if(bytesread!=NULL) {
1185 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1186 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1187 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1188 __func__, handle, pipe_handle->fileaccess);
1190 SetLastError (ERROR_ACCESS_DENIED);
1194 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: reading up to %d bytes from pipe %p", __func__,
1198 ret=read(fd, buffer, numbytes);
1199 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1202 if (errno == EINTR) {
1205 _wapi_set_last_error_from_errno ();
1207 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
1208 handle, strerror(errno));
1214 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read %d bytes from pipe", __func__, ret);
1216 if(bytesread!=NULL) {
1223 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1224 guint32 numbytes, guint32 *byteswritten,
1225 WapiOverlapped *overlapped G_GNUC_UNUSED)
1227 struct _WapiHandle_file *pipe_handle;
1231 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1232 (gpointer *)&pipe_handle);
1234 g_warning ("%s: error looking up pipe handle %p", __func__,
1236 SetLastError (ERROR_INVALID_HANDLE);
1239 fd = pipe_handle->fd;
1241 if(byteswritten!=NULL) {
1245 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1246 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1247 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, pipe_handle->fileaccess);
1249 SetLastError (ERROR_ACCESS_DENIED);
1253 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1257 ret = write (fd, buffer, numbytes);
1258 } while (ret == -1 && errno == EINTR &&
1259 !_wapi_thread_cur_apc_pending());
1262 if (errno == EINTR) {
1265 _wapi_set_last_error_from_errno ();
1267 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s", __func__,
1268 handle, strerror(errno));
1273 if(byteswritten!=NULL) {
1280 static int convert_flags(guint32 fileaccess, guint32 createmode)
1284 switch(fileaccess) {
1291 case GENERIC_READ|GENERIC_WRITE:
1295 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown access type 0x%x", __func__,
1300 switch(createmode) {
1302 flags|=O_CREAT|O_EXCL;
1305 flags|=O_CREAT|O_TRUNC;
1312 case TRUNCATE_EXISTING:
1316 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown create mode 0x%x", __func__,
1325 static mode_t convert_perms(guint32 sharemode)
1329 if(sharemode&FILE_SHARE_READ) {
1332 if(sharemode&FILE_SHARE_WRITE) {
1340 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1342 struct _WapiFileShare **share_info)
1344 gboolean file_already_shared;
1345 guint32 file_existing_share, file_existing_access;
1347 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);
1349 if (file_already_shared) {
1350 /* The reference to this share info was incremented
1351 * when we looked it up, so be careful to put it back
1352 * if we conclude we can't use this file.
1354 if (file_existing_share == 0) {
1355 /* Quick and easy, no possibility to share */
1356 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
1358 _wapi_handle_share_release (*share_info);
1363 if (((file_existing_share == FILE_SHARE_READ) &&
1364 (fileaccess != GENERIC_READ)) ||
1365 ((file_existing_share == FILE_SHARE_WRITE) &&
1366 (fileaccess != GENERIC_WRITE))) {
1367 /* New access mode doesn't match up */
1368 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
1370 _wapi_handle_share_release (*share_info);
1375 if (((file_existing_access & GENERIC_READ) &&
1376 !(sharemode & FILE_SHARE_READ)) ||
1377 ((file_existing_access & GENERIC_WRITE) &&
1378 !(sharemode & FILE_SHARE_WRITE))) {
1379 /* New share mode doesn't match up */
1380 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Access mode prevents open: requested share: 0x%x, file has access: 0x%x", __func__, sharemode, file_existing_access);
1382 _wapi_handle_share_release (*share_info);
1387 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
1395 share_allows_delete (struct stat *statbuf, struct _WapiFileShare **share_info)
1397 gboolean file_already_shared;
1398 guint32 file_existing_share, file_existing_access;
1400 file_already_shared = _wapi_handle_get_or_set_share (statbuf->st_dev, statbuf->st_ino, FILE_SHARE_DELETE, GENERIC_READ, &file_existing_share, &file_existing_access, share_info);
1402 if (file_already_shared) {
1403 /* The reference to this share info was incremented
1404 * when we looked it up, so be careful to put it back
1405 * if we conclude we can't use this file.
1407 if (file_existing_share == 0) {
1408 /* Quick and easy, no possibility to share */
1409 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, (*share_info)->access);
1411 _wapi_handle_share_release (*share_info);
1416 if (!(file_existing_share & FILE_SHARE_DELETE)) {
1417 /* New access mode doesn't match up */
1418 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, (*share_info)->access, file_existing_share);
1420 _wapi_handle_share_release (*share_info);
1425 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
1430 static gboolean share_check (struct stat *statbuf, guint32 sharemode,
1432 struct _WapiFileShare **share_info, int fd)
1434 if (share_allows_open (statbuf, sharemode, fileaccess,
1435 share_info) == TRUE) {
1439 /* Got a share violation. Double check that the file is still
1440 * open by someone, in case a process crashed while still
1441 * holding a file handle. This will also cope with someone
1442 * using Mono.Posix to close the file. This is cheaper and
1443 * less intrusive to other processes than initiating a handle
1447 _wapi_handle_check_share (*share_info, fd);
1448 if (share_allows_open (statbuf, sharemode, fileaccess,
1449 share_info) == TRUE) {
1453 return(share_allows_open (statbuf, sharemode, fileaccess, share_info));
1458 * @name: a pointer to a NULL-terminated unicode string, that names
1459 * the file or other object to create.
1460 * @fileaccess: specifies the file access mode
1461 * @sharemode: whether the file should be shared. This parameter is
1462 * currently ignored.
1463 * @security: Ignored for now.
1464 * @createmode: specifies whether to create a new file, whether to
1465 * overwrite an existing file, whether to truncate the file, etc.
1466 * @attrs: specifies file attributes and flags. On win32 attributes
1467 * are characteristics of the file, not the handle, and are ignored
1468 * when an existing file is opened. Flags give the library hints on
1469 * how to process a file to optimise performance.
1470 * @template: the handle of an open %GENERIC_READ file that specifies
1471 * attributes to apply to a newly created file, ignoring @attrs.
1472 * Normally this parameter is NULL. This parameter is ignored when an
1473 * existing file is opened.
1475 * Creates a new file handle. This only applies to normal files:
1476 * pipes are handled by CreatePipe(), and console handles are created
1477 * with GetStdHandle().
1479 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1481 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1482 guint32 sharemode, WapiSecurityAttributes *security,
1483 guint32 createmode, guint32 attrs,
1484 gpointer template_ G_GNUC_UNUSED)
1486 struct _WapiHandle_file file_handle = {0};
1488 int flags=convert_flags(fileaccess, createmode);
1489 /*mode_t perms=convert_perms(sharemode);*/
1490 /* we don't use sharemode, because that relates to sharing of
1491 * the file when the file is open and is already handled by
1492 * other code, perms instead are the on-disk permissions and
1493 * this is a sane default.
1498 WapiHandleType handle_type;
1499 struct stat statbuf;
1501 mono_once (&io_ops_once, io_ops_init);
1503 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1506 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1507 SetLastError (ERROR_ENCRYPTION_FAILED);
1508 return INVALID_HANDLE_VALUE;
1512 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1514 SetLastError (ERROR_INVALID_NAME);
1515 return(INVALID_HANDLE_VALUE);
1518 filename = mono_unicode_to_external (name);
1519 if (filename == NULL) {
1520 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1522 SetLastError (ERROR_INVALID_NAME);
1523 return(INVALID_HANDLE_VALUE);
1526 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Opening %s with share 0x%x and access 0x%x", __func__,
1527 filename, sharemode, fileaccess);
1529 fd = _wapi_open (filename, flags, perms);
1531 /* If we were trying to open a directory with write permissions
1532 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1533 * EISDIR. However, this is a bit bogus because calls to
1534 * manipulate the directory (e.g. SetFileTime) will still work on
1535 * the directory because they use other API calls
1536 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1537 * to open the directory again without write permission.
1539 if (fd == -1 && errno == EISDIR)
1541 /* Try again but don't try to make it writable */
1542 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1546 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s: %s", __func__, filename,
1548 _wapi_set_last_path_error_from_errno (NULL, filename);
1551 return(INVALID_HANDLE_VALUE);
1554 if (fd >= _wapi_fd_reserve) {
1555 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
1557 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1562 return(INVALID_HANDLE_VALUE);
1565 ret = fstat (fd, &statbuf);
1567 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fstat error of file %s: %s", __func__,
1568 filename, strerror (errno));
1569 _wapi_set_last_error_from_errno ();
1573 return(INVALID_HANDLE_VALUE);
1575 #ifdef __native_client__
1576 /* Workaround: Native Client currently returns the same fake inode
1577 * for all files, so do a simple hash on the filename so we don't
1578 * use the same share info for each file.
1580 statbuf.st_ino = g_str_hash(filename);
1583 if (share_check (&statbuf, sharemode, fileaccess,
1584 &file_handle.share_info, fd) == FALSE) {
1585 SetLastError (ERROR_SHARING_VIOLATION);
1589 return (INVALID_HANDLE_VALUE);
1591 if (file_handle.share_info == NULL) {
1592 /* No space, so no more files can be opened */
1593 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No space in the share table", __func__);
1595 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1599 return(INVALID_HANDLE_VALUE);
1602 file_handle.filename = filename;
1604 if(security!=NULL) {
1605 //file_handle->security_attributes=_wapi_handle_scratch_store (
1606 //security, sizeof(WapiSecurityAttributes));
1609 file_handle.fd = fd;
1610 file_handle.fileaccess=fileaccess;
1611 file_handle.sharemode=sharemode;
1612 file_handle.attrs=attrs;
1614 #ifdef HAVE_POSIX_FADVISE
1615 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1616 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1617 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1618 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1622 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1624 if (S_ISFIFO (statbuf.st_mode)) {
1625 handle_type = WAPI_HANDLE_PIPE;
1626 } else if (S_ISCHR (statbuf.st_mode)) {
1627 handle_type = WAPI_HANDLE_CONSOLE;
1629 handle_type = WAPI_HANDLE_FILE;
1632 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1633 if (handle == _WAPI_HANDLE_INVALID) {
1634 g_warning ("%s: error creating file handle", __func__);
1638 SetLastError (ERROR_GEN_FAILURE);
1639 return(INVALID_HANDLE_VALUE);
1642 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p", __func__, handle);
1649 * @name: a pointer to a NULL-terminated unicode string, that names
1650 * the file to be deleted.
1652 * Deletes file @name.
1654 * Return value: %TRUE on success, %FALSE otherwise.
1656 gboolean DeleteFile(const gunichar2 *name)
1660 gboolean ret = FALSE;
1663 struct stat statbuf;
1664 struct _WapiFileShare *shareinfo;
1668 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1670 SetLastError (ERROR_INVALID_NAME);
1674 filename=mono_unicode_to_external(name);
1675 if(filename==NULL) {
1676 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1678 SetLastError (ERROR_INVALID_NAME);
1682 attrs = GetFileAttributes (name);
1683 if (attrs == INVALID_FILE_ATTRIBUTES) {
1684 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file attributes error", __func__);
1685 /* Error set by GetFileAttributes() */
1691 /* Check to make sure sharing allows us to open the file for
1692 * writing. See bug 323389.
1694 * Do the checks that don't need an open file descriptor, for
1695 * simplicity's sake. If we really have to do the full checks
1696 * then we can implement that later.
1698 if (_wapi_stat (filename, &statbuf) < 0) {
1699 _wapi_set_last_path_error_from_errno (NULL, filename);
1704 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1705 &shareinfo) == FALSE) {
1706 SetLastError (ERROR_SHARING_VIOLATION);
1711 _wapi_handle_share_release (shareinfo);
1714 retval = _wapi_unlink (filename);
1717 _wapi_set_last_path_error_from_errno (NULL, filename);
1729 * @name: a pointer to a NULL-terminated unicode string, that names
1730 * the file to be moved.
1731 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1732 * new name for the file.
1734 * Renames file @name to @dest_name.
1735 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1736 * when it is the same file as the source. In that case it silently succeeds.
1738 * Return value: %TRUE on success, %FALSE otherwise.
1740 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1742 gchar *utf8_name, *utf8_dest_name;
1743 int result, errno_copy;
1744 struct stat stat_src, stat_dest;
1745 gboolean ret = FALSE;
1746 struct _WapiFileShare *shareinfo;
1749 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1751 SetLastError (ERROR_INVALID_NAME);
1755 utf8_name = mono_unicode_to_external (name);
1756 if (utf8_name == NULL) {
1757 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1759 SetLastError (ERROR_INVALID_NAME);
1763 if(dest_name==NULL) {
1764 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1767 SetLastError (ERROR_INVALID_NAME);
1771 utf8_dest_name = mono_unicode_to_external (dest_name);
1772 if (utf8_dest_name == NULL) {
1773 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1776 SetLastError (ERROR_INVALID_NAME);
1781 * In C# land we check for the existence of src, but not for dest.
1782 * We check it here and return the failure if dest exists and is not
1783 * the same file as src.
1785 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1786 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1787 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1789 g_free (utf8_dest_name);
1794 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1795 if (stat_dest.st_dev != stat_src.st_dev ||
1796 stat_dest.st_ino != stat_src.st_ino) {
1798 g_free (utf8_dest_name);
1799 SetLastError (ERROR_ALREADY_EXISTS);
1804 /* Check to make that we have delete sharing permission.
1805 * See https://bugzilla.xamarin.com/show_bug.cgi?id=17009
1807 * Do the checks that don't need an open file descriptor, for
1808 * simplicity's sake. If we really have to do the full checks
1809 * then we can implement that later.
1811 if (share_allows_delete (&stat_src, &shareinfo) == FALSE) {
1812 SetLastError (ERROR_SHARING_VIOLATION);
1816 _wapi_handle_share_release (shareinfo);
1818 result = _wapi_rename (utf8_name, utf8_dest_name);
1822 switch(errno_copy) {
1824 SetLastError (ERROR_ALREADY_EXISTS);
1828 /* Ignore here, it is dealt with below */
1832 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1837 g_free (utf8_dest_name);
1839 if (result != 0 && errno_copy == EXDEV) {
1840 if (S_ISDIR (stat_src.st_mode)) {
1841 SetLastError (ERROR_NOT_SAME_DEVICE);
1844 /* Try a copy to the new location, and delete the source */
1845 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1846 /* CopyFile will set the error */
1850 return(DeleteFile (name));
1861 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1865 int buf_size = st_src->st_blksize;
1867 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1868 buf = (char *) malloc (buf_size);
1871 remain = read (src_fd, buf, buf_size);
1873 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1877 _wapi_set_last_error_from_errno ();
1887 while (remain > 0) {
1888 if ((n = write (dest_fd, wbuf, remain)) < 0) {
1889 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1893 _wapi_set_last_error_from_errno ();
1894 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write failed.", __func__);
1910 * @name: a pointer to a NULL-terminated unicode string, that names
1911 * the file to be copied.
1912 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1913 * new name for the file.
1914 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1916 * Copies file @name to @dest_name
1918 * Return value: %TRUE on success, %FALSE otherwise.
1920 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1921 gboolean fail_if_exists)
1923 gchar *utf8_src, *utf8_dest;
1924 int src_fd, dest_fd;
1925 struct stat st, dest_st;
1926 struct utimbuf dest_time;
1927 gboolean ret = TRUE;
1931 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1933 SetLastError (ERROR_INVALID_NAME);
1937 utf8_src = mono_unicode_to_external (name);
1938 if (utf8_src == NULL) {
1939 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of source returned NULL",
1942 SetLastError (ERROR_INVALID_PARAMETER);
1946 if(dest_name==NULL) {
1947 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: dest is NULL", __func__);
1950 SetLastError (ERROR_INVALID_NAME);
1954 utf8_dest = mono_unicode_to_external (dest_name);
1955 if (utf8_dest == NULL) {
1956 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of dest returned NULL",
1959 SetLastError (ERROR_INVALID_PARAMETER);
1966 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
1968 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
1976 if (fstat (src_fd, &st) < 0) {
1977 _wapi_set_last_error_from_errno ();
1986 /* Before trying to open/create the dest, we need to report a 'file busy'
1987 * error if src and dest are actually the same file. We do the check here to take
1988 * advantage of the IOMAP capability */
1989 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
1990 st.st_ino == dest_st.st_ino) {
1996 SetLastError (ERROR_SHARING_VIOLATION);
2000 if (fail_if_exists) {
2001 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2003 /* FIXME: it kinda sucks that this code path potentially scans
2004 * the directory twice due to the weird SetLastError()
2006 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2008 /* The file does not exist, try creating it */
2009 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2011 /* Apparently this error is set if we
2012 * overwrite the dest file
2014 SetLastError (ERROR_ALREADY_EXISTS);
2018 _wapi_set_last_error_from_errno ();
2027 if (!write_file (src_fd, dest_fd, &st, TRUE))
2033 dest_time.modtime = st.st_mtime;
2034 dest_time.actime = st.st_atime;
2035 ret_utime = utime (utf8_dest, &dest_time);
2036 if (ret_utime == -1)
2037 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file [%s] utime failed: %s", __func__, utf8_dest, strerror(errno));
2046 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2051 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: %s is NULL", __func__, arg_name);
2052 SetLastError (ERROR_INVALID_NAME);
2056 utf8_ret = mono_unicode_to_external (arg);
2057 if (utf8_ret == NULL) {
2058 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of %s returned NULL",
2059 __func__, arg_name);
2060 SetLastError (ERROR_INVALID_PARAMETER);
2068 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2069 const gunichar2 *backupFileName, guint32 replaceFlags,
2070 gpointer exclude, gpointer reserved)
2072 int result, backup_fd = -1,replaced_fd = -1;
2073 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2074 struct stat stBackup;
2075 gboolean ret = FALSE;
2077 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2079 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2080 goto replace_cleanup;
2081 if (backupFileName != NULL) {
2082 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2083 goto replace_cleanup;
2086 if (utf8_backupFileName) {
2087 // Open the backup file for read so we can restore the file if an error occurs.
2088 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2089 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2091 goto replace_cleanup;
2094 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2096 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2097 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2098 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2099 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2102 if (replaced_fd == -1)
2103 goto replace_cleanup;
2105 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2108 goto replace_cleanup;
2114 g_free (utf8_replacedFileName);
2115 g_free (utf8_replacementFileName);
2116 g_free (utf8_backupFileName);
2117 if (backup_fd != -1)
2119 if (replaced_fd != -1)
2120 close (replaced_fd);
2126 * @stdhandle: specifies the file descriptor
2128 * Returns a handle for stdin, stdout, or stderr. Always returns the
2129 * same handle for the same @stdhandle.
2131 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2134 static mono_mutex_t stdhandle_mutex;
2136 gpointer GetStdHandle(WapiStdHandle stdhandle)
2138 struct _WapiHandle_file *file_handle;
2145 case STD_INPUT_HANDLE:
2150 case STD_OUTPUT_HANDLE:
2155 case STD_ERROR_HANDLE:
2161 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unknown standard handle type", __func__);
2163 SetLastError (ERROR_INVALID_PARAMETER);
2164 return(INVALID_HANDLE_VALUE);
2167 handle = GINT_TO_POINTER (fd);
2169 thr_ret = mono_os_mutex_lock (&stdhandle_mutex);
2170 g_assert (thr_ret == 0);
2172 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2173 (gpointer *)&file_handle);
2175 /* Need to create this console handle */
2176 handle = _wapi_stdhandle_create (fd, name);
2178 if (handle == INVALID_HANDLE_VALUE) {
2179 SetLastError (ERROR_NO_MORE_FILES);
2183 /* Add a reference to this handle */
2184 _wapi_handle_ref (handle);
2188 thr_ret = mono_os_mutex_unlock (&stdhandle_mutex);
2189 g_assert (thr_ret == 0);
2196 * @handle: The file handle to read from. The handle must have
2197 * %GENERIC_READ access.
2198 * @buffer: The buffer to store read data in
2199 * @numbytes: The maximum number of bytes to read
2200 * @bytesread: The actual number of bytes read is stored here. This
2201 * value can be zero if the handle is positioned at the end of the
2203 * @overlapped: points to a required %WapiOverlapped structure if
2204 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2207 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2208 * function reads up to @numbytes bytes from the file from the current
2209 * file position, and stores them in @buffer. If there are not enough
2210 * bytes left in the file, just the amount available will be read.
2211 * The actual number of bytes read is stored in @bytesread.
2213 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2214 * file position is ignored and the read position is taken from data
2215 * in the @overlapped structure.
2217 * Return value: %TRUE if the read succeeds (even if no bytes were
2218 * read due to an attempt to read past the end of the file), %FALSE on
2221 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2222 guint32 *bytesread, WapiOverlapped *overlapped)
2224 WapiHandleType type;
2226 type = _wapi_handle_type (handle);
2228 if(io_ops[type].readfile==NULL) {
2229 SetLastError (ERROR_INVALID_HANDLE);
2233 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2239 * @handle: The file handle to write to. The handle must have
2240 * %GENERIC_WRITE access.
2241 * @buffer: The buffer to read data from.
2242 * @numbytes: The maximum number of bytes to write.
2243 * @byteswritten: The actual number of bytes written is stored here.
2244 * If the handle is positioned at the file end, the length of the file
2245 * is extended. This parameter may be %NULL.
2246 * @overlapped: points to a required %WapiOverlapped structure if
2247 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2250 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2251 * function writes up to @numbytes bytes from @buffer to the file at
2252 * the current file position. If @handle is positioned at the end of
2253 * the file, the file is extended. The actual number of bytes written
2254 * is stored in @byteswritten.
2256 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2257 * file position is ignored and the write position is taken from data
2258 * in the @overlapped structure.
2260 * Return value: %TRUE if the write succeeds, %FALSE on error.
2262 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2263 guint32 *byteswritten, WapiOverlapped *overlapped)
2265 WapiHandleType type;
2267 type = _wapi_handle_type (handle);
2269 if(io_ops[type].writefile==NULL) {
2270 SetLastError (ERROR_INVALID_HANDLE);
2274 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2280 * @handle: Handle to open file. The handle must have
2281 * %GENERIC_WRITE access.
2283 * Flushes buffers of the file and causes all unwritten data to
2286 * Return value: %TRUE on success, %FALSE otherwise.
2288 gboolean FlushFileBuffers(gpointer handle)
2290 WapiHandleType type;
2292 type = _wapi_handle_type (handle);
2294 if(io_ops[type].flushfile==NULL) {
2295 SetLastError (ERROR_INVALID_HANDLE);
2299 return(io_ops[type].flushfile (handle));
2304 * @handle: The file handle to set. The handle must have
2305 * %GENERIC_WRITE access.
2307 * Moves the end-of-file position to the current position of the file
2308 * pointer. This function is used to truncate or extend a file.
2310 * Return value: %TRUE on success, %FALSE otherwise.
2312 gboolean SetEndOfFile(gpointer handle)
2314 WapiHandleType type;
2316 type = _wapi_handle_type (handle);
2318 if (io_ops[type].setendoffile == NULL) {
2319 SetLastError (ERROR_INVALID_HANDLE);
2323 return(io_ops[type].setendoffile (handle));
2328 * @handle: The file handle to set. The handle must have
2329 * %GENERIC_READ or %GENERIC_WRITE access.
2330 * @movedistance: Low 32 bits of a signed value that specifies the
2331 * number of bytes to move the file pointer.
2332 * @highmovedistance: Pointer to the high 32 bits of a signed value
2333 * that specifies the number of bytes to move the file pointer, or
2335 * @method: The starting point for the file pointer move.
2337 * Sets the file pointer of an open file.
2339 * The distance to move the file pointer is calculated from
2340 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2341 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2342 * is the low 32 bits and @highmovedistance a pointer to the high 32
2343 * bits of a 64 bit signed value. A positive distance moves the file
2344 * pointer forward from the position specified by @method; a negative
2345 * distance moves the file pointer backward.
2347 * If the library is compiled without large file support,
2348 * @highmovedistance is ignored and its value is set to zero on a
2349 * successful return.
2351 * Return value: On success, the low 32 bits of the new file pointer.
2352 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2353 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2355 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2356 gint32 *highmovedistance, WapiSeekMethod method)
2358 WapiHandleType type;
2360 type = _wapi_handle_type (handle);
2362 if (io_ops[type].seek == NULL) {
2363 SetLastError (ERROR_INVALID_HANDLE);
2364 return(INVALID_SET_FILE_POINTER);
2367 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2373 * @handle: The file handle to test.
2375 * Finds the type of file @handle.
2377 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2378 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2379 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2380 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2382 WapiFileType GetFileType(gpointer handle)
2384 WapiHandleType type;
2386 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2387 SetLastError (ERROR_INVALID_HANDLE);
2388 return(FILE_TYPE_UNKNOWN);
2391 type = _wapi_handle_type (handle);
2393 if (io_ops[type].getfiletype == NULL) {
2394 SetLastError (ERROR_INVALID_HANDLE);
2395 return(FILE_TYPE_UNKNOWN);
2398 return(io_ops[type].getfiletype ());
2403 * @handle: The file handle to query. The handle must have
2404 * %GENERIC_READ or %GENERIC_WRITE access.
2405 * @highsize: If non-%NULL, the high 32 bits of the file size are
2408 * Retrieves the size of the file @handle.
2410 * If the library is compiled without large file support, @highsize
2411 * has its value set to zero on a successful return.
2413 * Return value: On success, the low 32 bits of the file size. If
2414 * @highsize is non-%NULL then the high 32 bits of the file size are
2415 * stored here. On failure %INVALID_FILE_SIZE is returned.
2417 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2419 WapiHandleType type;
2421 type = _wapi_handle_type (handle);
2423 if (io_ops[type].getfilesize == NULL) {
2424 SetLastError (ERROR_INVALID_HANDLE);
2425 return(INVALID_FILE_SIZE);
2428 return(io_ops[type].getfilesize (handle, highsize));
2433 * @handle: The file handle to query. The handle must have
2434 * %GENERIC_READ access.
2435 * @create_time: Points to a %WapiFileTime structure to receive the
2436 * number of ticks since the epoch that file was created. May be
2438 * @last_access: Points to a %WapiFileTime structure to receive the
2439 * number of ticks since the epoch when file was last accessed. May be
2441 * @last_write: Points to a %WapiFileTime structure to receive the
2442 * number of ticks since the epoch when file was last written to. May
2445 * Finds the number of ticks since the epoch that the file referenced
2446 * by @handle was created, last accessed and last modified. A tick is
2447 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2450 * Create time isn't recorded on POSIX file systems or reported by
2451 * stat(2), so that time is guessed by returning the oldest of the
2454 * Return value: %TRUE on success, %FALSE otherwise.
2456 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2457 WapiFileTime *last_access, WapiFileTime *last_write)
2459 WapiHandleType type;
2461 type = _wapi_handle_type (handle);
2463 if (io_ops[type].getfiletime == NULL) {
2464 SetLastError (ERROR_INVALID_HANDLE);
2468 return(io_ops[type].getfiletime (handle, create_time, last_access,
2474 * @handle: The file handle to set. The handle must have
2475 * %GENERIC_WRITE access.
2476 * @create_time: Points to a %WapiFileTime structure that contains the
2477 * number of ticks since the epoch that the file was created. May be
2479 * @last_access: Points to a %WapiFileTime structure that contains the
2480 * number of ticks since the epoch when the file was last accessed.
2482 * @last_write: Points to a %WapiFileTime structure that contains the
2483 * number of ticks since the epoch when the file was last written to.
2486 * Sets the number of ticks since the epoch that the file referenced
2487 * by @handle was created, last accessed or last modified. A tick is
2488 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2491 * Create time isn't recorded on POSIX file systems, and is ignored.
2493 * Return value: %TRUE on success, %FALSE otherwise.
2495 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2496 const WapiFileTime *last_access,
2497 const WapiFileTime *last_write)
2499 WapiHandleType type;
2501 type = _wapi_handle_type (handle);
2503 if (io_ops[type].setfiletime == NULL) {
2504 SetLastError (ERROR_INVALID_HANDLE);
2508 return(io_ops[type].setfiletime (handle, create_time, last_access,
2512 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2513 * January 1 1601 GMT
2516 #define TICKS_PER_MILLISECOND 10000L
2517 #define TICKS_PER_SECOND 10000000L
2518 #define TICKS_PER_MINUTE 600000000L
2519 #define TICKS_PER_HOUR 36000000000LL
2520 #define TICKS_PER_DAY 864000000000LL
2522 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2524 static const guint16 mon_yday[2][13]={
2525 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2526 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2530 * FileTimeToSystemTime:
2531 * @file_time: Points to a %WapiFileTime structure that contains the
2532 * number of ticks to convert.
2533 * @system_time: Points to a %WapiSystemTime structure to receive the
2536 * Converts a tick count into broken-out time values.
2538 * Return value: %TRUE on success, %FALSE otherwise.
2540 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2541 WapiSystemTime *system_time)
2543 gint64 file_ticks, totaldays, rem, y;
2546 if(system_time==NULL) {
2547 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: system_time NULL", __func__);
2549 SetLastError (ERROR_INVALID_PARAMETER);
2553 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2554 file_time->dwLowDateTime;
2556 /* Really compares if file_ticks>=0x8000000000000000
2557 * (LLONG_MAX+1) but we're working with a signed value for the
2558 * year and day calculation to work later
2561 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file_time too big", __func__);
2563 SetLastError (ERROR_INVALID_PARAMETER);
2567 totaldays=(file_ticks / TICKS_PER_DAY);
2568 rem = file_ticks % TICKS_PER_DAY;
2569 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2571 system_time->wHour=rem/TICKS_PER_HOUR;
2572 rem %= TICKS_PER_HOUR;
2573 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2575 system_time->wMinute = rem / TICKS_PER_MINUTE;
2576 rem %= TICKS_PER_MINUTE;
2577 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2580 system_time->wSecond = rem / TICKS_PER_SECOND;
2581 rem %= TICKS_PER_SECOND;
2582 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2585 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2586 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Milliseconds: %d", __func__,
2587 system_time->wMilliseconds);
2589 /* January 1, 1601 was a Monday, according to Emacs calendar */
2590 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2591 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2593 /* This algorithm to find year and month given days from epoch
2598 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2599 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2601 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2602 /* Guess a corrected year, assuming 365 days per year */
2603 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2604 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld yg: %lld y: %lld", __func__,
2607 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2608 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2610 /* Adjust days and y to match the guessed year. */
2611 totaldays -= ((yg - y) * 365
2612 + LEAPS_THRU_END_OF (yg - 1)
2613 - LEAPS_THRU_END_OF (y - 1));
2614 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2616 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: y: %lld", __func__, y);
2619 system_time->wYear = y;
2620 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Year: %d", __func__, system_time->wYear);
2622 ip = mon_yday[isleap(y)];
2624 for(y=11; totaldays < ip[y]; --y) {
2628 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2630 system_time->wMonth = y + 1;
2631 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Month: %d", __func__, system_time->wMonth);
2633 system_time->wDay = totaldays + 1;
2634 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day: %d", __func__, system_time->wDay);
2639 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2641 struct _WapiHandle_find find_handle = {0};
2643 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2646 if (pattern == NULL) {
2647 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: pattern is NULL", __func__);
2649 SetLastError (ERROR_PATH_NOT_FOUND);
2650 return(INVALID_HANDLE_VALUE);
2653 utf8_pattern = mono_unicode_to_external (pattern);
2654 if (utf8_pattern == NULL) {
2655 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2657 SetLastError (ERROR_INVALID_NAME);
2658 return(INVALID_HANDLE_VALUE);
2661 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for [%s]", __func__, utf8_pattern);
2663 /* Figure out which bit of the pattern is the directory */
2664 dir_part = _wapi_dirname (utf8_pattern);
2665 entry_part = _wapi_basename (utf8_pattern);
2668 /* Don't do this check for now, it breaks if directories
2669 * really do have metachars in their names (see bug 58116).
2670 * FIXME: Figure out a better solution to keep some checks...
2672 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2673 SetLastError (ERROR_INVALID_NAME);
2675 g_free (entry_part);
2676 g_free (utf8_pattern);
2677 return(INVALID_HANDLE_VALUE);
2681 /* The pattern can specify a directory or a set of files.
2683 * The pattern can have wildcard characters ? and *, but only
2684 * in the section after the last directory delimiter. (Return
2685 * ERROR_INVALID_NAME if there are wildcards in earlier path
2686 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2687 * means "match one character", "??" seems to mean "match one
2688 * or two characters", "???" seems to mean "match one, two or
2689 * three characters", etc. Windows will also try and match
2690 * the mangled "short name" of files, so 8 character patterns
2691 * with wildcards will show some surprising results.
2693 * All the written documentation I can find says that '?'
2694 * should only match one character, and doesn't mention '??',
2695 * '???' etc. I'm going to assume that the strict behaviour
2696 * (ie '???' means three and only three characters) is the
2697 * correct one, because that lets me use fnmatch(3) rather
2698 * than mess around with regexes.
2701 find_handle.namelist = NULL;
2702 result = _wapi_io_scandir (dir_part, entry_part,
2703 &find_handle.namelist);
2706 /* No files, which windows seems to call
2709 SetLastError (ERROR_FILE_NOT_FOUND);
2710 g_free (utf8_pattern);
2711 g_free (entry_part);
2713 return (INVALID_HANDLE_VALUE);
2717 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2718 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: scandir error: %s", __func__, g_strerror (errno));
2719 g_free (utf8_pattern);
2720 g_free (entry_part);
2722 return (INVALID_HANDLE_VALUE);
2725 g_free (utf8_pattern);
2726 g_free (entry_part);
2728 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Got %d matches", __func__, result);
2730 find_handle.dir_part = dir_part;
2731 find_handle.num = result;
2732 find_handle.count = 0;
2734 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2735 if (handle == _WAPI_HANDLE_INVALID) {
2736 g_warning ("%s: error creating find handle", __func__);
2738 g_free (entry_part);
2739 g_free (utf8_pattern);
2740 SetLastError (ERROR_GEN_FAILURE);
2742 return(INVALID_HANDLE_VALUE);
2745 if (handle != INVALID_HANDLE_VALUE &&
2746 !FindNextFile (handle, find_data)) {
2748 SetLastError (ERROR_NO_MORE_FILES);
2749 handle = INVALID_HANDLE_VALUE;
2755 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2757 struct _WapiHandle_find *find_handle;
2759 struct stat buf, linkbuf;
2762 gchar *utf8_filename, *utf8_basename;
2763 gunichar2 *utf16_basename;
2767 gboolean ret = FALSE;
2769 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2770 (gpointer *)&find_handle);
2772 g_warning ("%s: error looking up find handle %p", __func__,
2774 SetLastError (ERROR_INVALID_HANDLE);
2778 thr_ret = _wapi_handle_lock_handle (handle);
2779 g_assert (thr_ret == 0);
2782 if (find_handle->count >= find_handle->num) {
2783 SetLastError (ERROR_NO_MORE_FILES);
2787 /* stat next match */
2789 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2791 result = _wapi_stat (filename, &buf);
2792 if (result == -1 && errno == ENOENT) {
2793 /* Might be a dangling symlink */
2794 result = _wapi_lstat (filename, &buf);
2798 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: stat failed: %s", __func__, filename);
2804 #ifndef __native_client__
2805 result = _wapi_lstat (filename, &linkbuf);
2807 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lstat failed: %s", __func__, filename);
2814 utf8_filename = mono_utf8_from_external (filename);
2815 if (utf8_filename == NULL) {
2816 /* We couldn't turn this filename into utf8 (eg the
2817 * encoding of the name wasn't convertible), so just
2820 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2827 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Found [%s]", __func__, utf8_filename);
2829 /* fill data block */
2831 if (buf.st_mtime < buf.st_ctime)
2832 create_time = buf.st_mtime;
2834 create_time = buf.st_ctime;
2836 #ifdef __native_client__
2837 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, NULL);
2839 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2842 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2843 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2844 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2846 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2847 find_data->nFileSizeHigh = 0;
2848 find_data->nFileSizeLow = 0;
2850 find_data->nFileSizeHigh = buf.st_size >> 32;
2851 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2854 find_data->dwReserved0 = 0;
2855 find_data->dwReserved1 = 0;
2857 utf8_basename = _wapi_basename (utf8_filename);
2858 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2860 if(utf16_basename==NULL) {
2861 g_free (utf8_basename);
2862 g_free (utf8_filename);
2867 /* utf16 is 2 * utf8 */
2870 memset (find_data->cFileName, '\0', (MAX_PATH*2));
2872 /* Truncating a utf16 string like this might leave the last
2875 memcpy (find_data->cFileName, utf16_basename,
2876 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
2878 find_data->cAlternateFileName [0] = 0; /* not used */
2880 g_free (utf8_basename);
2881 g_free (utf8_filename);
2882 g_free (utf16_basename);
2885 thr_ret = _wapi_handle_unlock_handle (handle);
2886 g_assert (thr_ret == 0);
2893 * @wapi_handle: the find handle to close.
2895 * Closes find handle @wapi_handle
2897 * Return value: %TRUE on success, %FALSE otherwise.
2899 gboolean FindClose (gpointer handle)
2901 struct _WapiHandle_find *find_handle;
2905 if (handle == NULL) {
2906 SetLastError (ERROR_INVALID_HANDLE);
2910 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2911 (gpointer *)&find_handle);
2913 g_warning ("%s: error looking up find handle %p", __func__,
2915 SetLastError (ERROR_INVALID_HANDLE);
2919 thr_ret = _wapi_handle_lock_handle (handle);
2920 g_assert (thr_ret == 0);
2922 g_strfreev (find_handle->namelist);
2923 g_free (find_handle->dir_part);
2925 thr_ret = _wapi_handle_unlock_handle (handle);
2926 g_assert (thr_ret == 0);
2928 _wapi_handle_unref (handle);
2935 * @name: a pointer to a NULL-terminated unicode string, that names
2936 * the directory to be created.
2937 * @security: ignored for now
2939 * Creates directory @name
2941 * Return value: %TRUE on success, %FALSE otherwise.
2943 gboolean CreateDirectory (const gunichar2 *name,
2944 WapiSecurityAttributes *security)
2950 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2952 SetLastError (ERROR_INVALID_NAME);
2956 utf8_name = mono_unicode_to_external (name);
2957 if (utf8_name == NULL) {
2958 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2960 SetLastError (ERROR_INVALID_NAME);
2964 result = _wapi_mkdir (utf8_name, 0777);
2971 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2978 * @name: a pointer to a NULL-terminated unicode string, that names
2979 * the directory to be removed.
2981 * Removes directory @name
2983 * Return value: %TRUE on success, %FALSE otherwise.
2985 gboolean RemoveDirectory (const gunichar2 *name)
2991 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2993 SetLastError (ERROR_INVALID_NAME);
2997 utf8_name = mono_unicode_to_external (name);
2998 if (utf8_name == NULL) {
2999 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3001 SetLastError (ERROR_INVALID_NAME);
3005 result = _wapi_rmdir (utf8_name);
3007 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3018 * GetFileAttributes:
3019 * @name: a pointer to a NULL-terminated unicode filename.
3021 * Gets the attributes for @name;
3023 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3025 guint32 GetFileAttributes (const gunichar2 *name)
3028 struct stat buf, linkbuf;
3033 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3035 SetLastError (ERROR_INVALID_NAME);
3039 utf8_name = mono_unicode_to_external (name);
3040 if (utf8_name == NULL) {
3041 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3043 SetLastError (ERROR_INVALID_PARAMETER);
3044 return (INVALID_FILE_ATTRIBUTES);
3047 result = _wapi_stat (utf8_name, &buf);
3048 if (result == -1 && errno == ENOENT) {
3049 /* Might be a dangling symlink... */
3050 result = _wapi_lstat (utf8_name, &buf);
3054 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3056 return (INVALID_FILE_ATTRIBUTES);
3059 #ifndef __native_client__
3060 result = _wapi_lstat (utf8_name, &linkbuf);
3062 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3064 return (INVALID_FILE_ATTRIBUTES);
3068 #ifdef __native_client__
3069 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, NULL);
3071 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3080 * GetFileAttributesEx:
3081 * @name: a pointer to a NULL-terminated unicode filename.
3082 * @level: must be GetFileExInfoStandard
3083 * @info: pointer to a WapiFileAttributesData structure
3085 * Gets attributes, size and filetimes for @name;
3087 * Return value: %TRUE on success, %FALSE on failure
3089 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3092 WapiFileAttributesData *data;
3094 struct stat buf, linkbuf;
3098 if (level != GetFileExInfoStandard) {
3099 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: info level %d not supported.", __func__,
3102 SetLastError (ERROR_INVALID_PARAMETER);
3107 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3109 SetLastError (ERROR_INVALID_NAME);
3113 utf8_name = mono_unicode_to_external (name);
3114 if (utf8_name == NULL) {
3115 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3117 SetLastError (ERROR_INVALID_PARAMETER);
3121 result = _wapi_stat (utf8_name, &buf);
3122 if (result == -1 && errno == ENOENT) {
3123 /* Might be a dangling symlink... */
3124 result = _wapi_lstat (utf8_name, &buf);
3128 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3133 result = _wapi_lstat (utf8_name, &linkbuf);
3135 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3140 /* fill data block */
3142 data = (WapiFileAttributesData *)info;
3144 if (buf.st_mtime < buf.st_ctime)
3145 create_time = buf.st_mtime;
3147 create_time = buf.st_ctime;
3149 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3155 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3156 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3157 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3159 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3160 data->nFileSizeHigh = 0;
3161 data->nFileSizeLow = 0;
3164 data->nFileSizeHigh = buf.st_size >> 32;
3165 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3173 * @name: name of file
3174 * @attrs: attributes to set
3176 * Changes the attributes on a named file.
3178 * Return value: %TRUE on success, %FALSE on failure.
3180 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3182 /* FIXME: think of something clever to do on unix */
3188 * Currently we only handle one *internal* case, with a value that is
3189 * not standard: 0x80000000, which means `set executable bit'
3193 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3195 SetLastError (ERROR_INVALID_NAME);
3199 utf8_name = mono_unicode_to_external (name);
3200 if (utf8_name == NULL) {
3201 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3203 SetLastError (ERROR_INVALID_NAME);
3207 result = _wapi_stat (utf8_name, &buf);
3208 if (result == -1 && errno == ENOENT) {
3209 /* Might be a dangling symlink... */
3210 result = _wapi_lstat (utf8_name, &buf);
3214 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3219 /* Contrary to the documentation, ms allows NORMAL to be
3220 * specified along with other attributes, so dont bother to
3221 * catch that case here.
3223 if (attrs & FILE_ATTRIBUTE_READONLY) {
3224 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWUSR | S_IWOTH | S_IWGRP));
3226 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWUSR);
3229 /* Ignore the other attributes for now */
3231 if (attrs & 0x80000000){
3232 mode_t exec_mask = 0;
3234 if ((buf.st_mode & S_IRUSR) != 0)
3235 exec_mask |= S_IXUSR;
3237 if ((buf.st_mode & S_IRGRP) != 0)
3238 exec_mask |= S_IXGRP;
3240 if ((buf.st_mode & S_IROTH) != 0)
3241 exec_mask |= S_IXOTH;
3243 result = chmod (utf8_name, buf.st_mode | exec_mask);
3245 /* Don't bother to reset executable (might need to change this
3255 * GetCurrentDirectory
3256 * @length: size of the buffer
3257 * @buffer: pointer to buffer that recieves path
3259 * Retrieves the current directory for the current process.
3261 * Return value: number of characters in buffer on success, zero on failure
3263 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3265 gunichar2 *utf16_path;
3269 #ifdef __native_client__
3270 gchar *path = g_get_current_dir ();
3271 if (length < strlen(path) + 1 || path == NULL)
3273 memcpy (buffer, path, strlen(path) + 1);
3275 if (getcwd ((char*)buffer, length) == NULL) {
3276 if (errno == ERANGE) { /*buffer length is not big enough */
3277 gchar *path = g_get_current_dir (); /*FIXME g_get_current_dir doesn't work with broken paths and calling it just to know the path length is silly*/
3280 utf16_path = mono_unicode_from_external (path, &bytes);
3281 g_free (utf16_path);
3285 _wapi_set_last_error_from_errno ();
3290 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3291 count = (bytes/2)+1;
3292 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3294 /* Add the terminator */
3295 memset (buffer, '\0', bytes+2);
3296 memcpy (buffer, utf16_path, bytes);
3298 g_free (utf16_path);
3304 * SetCurrentDirectory
3305 * @path: path to new directory
3307 * Changes the directory path for the current process.
3309 * Return value: %TRUE on success, %FALSE on failure.
3311 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3317 SetLastError (ERROR_INVALID_PARAMETER);
3321 utf8_path = mono_unicode_to_external (path);
3322 if (_wapi_chdir (utf8_path) != 0) {
3323 _wapi_set_last_error_from_errno ();
3333 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3334 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3336 struct _WapiHandle_file pipe_read_handle = {0};
3337 struct _WapiHandle_file pipe_write_handle = {0};
3338 gpointer read_handle;
3339 gpointer write_handle;
3343 mono_once (&io_ops_once, io_ops_init);
3345 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Creating pipe", __func__);
3349 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error creating pipe: %s", __func__,
3352 _wapi_set_last_error_from_errno ();
3356 if (filedes[0] >= _wapi_fd_reserve ||
3357 filedes[1] >= _wapi_fd_reserve) {
3358 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
3360 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3368 /* filedes[0] is open for reading, filedes[1] for writing */
3370 pipe_read_handle.fd = filedes [0];
3371 pipe_read_handle.fileaccess = GENERIC_READ;
3372 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3374 if (read_handle == _WAPI_HANDLE_INVALID) {
3375 g_warning ("%s: error creating pipe read handle", __func__);
3378 SetLastError (ERROR_GEN_FAILURE);
3383 pipe_write_handle.fd = filedes [1];
3384 pipe_write_handle.fileaccess = GENERIC_WRITE;
3385 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3386 &pipe_write_handle);
3387 if (write_handle == _WAPI_HANDLE_INVALID) {
3388 g_warning ("%s: error creating pipe write handle", __func__);
3389 _wapi_handle_unref (read_handle);
3393 SetLastError (ERROR_GEN_FAILURE);
3398 *readpipe = read_handle;
3399 *writepipe = write_handle;
3401 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning pipe: read handle %p, write handle %p",
3402 __func__, read_handle, write_handle);
3407 #ifdef HAVE_GETFSSTAT
3408 /* Darwin has getfsstat */
3409 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3411 struct statfs *stats;
3414 glong length, total = 0;
3416 n = getfsstat (NULL, 0, MNT_NOWAIT);
3419 size = n * sizeof (struct statfs);
3420 stats = (struct statfs *) g_malloc (size);
3423 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3427 for (i = 0; i < n; i++){
3428 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3429 if (total + length < len){
3430 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3431 buf [total+length] = 0;
3434 total += length + 1;
3443 /* In-place octal sequence replacement */
3445 unescape_octal (gchar *str)
3454 while (*rptr != '\0') {
3455 if (*rptr == '\\') {
3458 c = (*(rptr++) - '0') << 6;
3459 c += (*(rptr++) - '0') << 3;
3460 c += *(rptr++) - '0';
3462 } else if (wptr != rptr) {
3470 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3473 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3474 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3475 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3480 guint32 buffer_index;
3481 guint32 mountpoint_index;
3482 guint32 field_number;
3483 guint32 allocated_size;
3484 guint32 fsname_index;
3485 guint32 fstype_index;
3486 gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3487 gchar *mountpoint_allocated;
3488 gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3489 gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3490 gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3493 gboolean check_mount_source;
3494 } LinuxMountInfoParseState;
3496 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3497 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3498 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3499 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3501 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3505 LinuxMountInfoParseState state;
3506 gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3508 memset (buf, 0, len * sizeof (gunichar2));
3509 fd = open ("/proc/self/mountinfo", O_RDONLY);
3511 parser = GetLogicalDriveStrings_MountInfo;
3513 fd = open ("/proc/mounts", O_RDONLY);
3515 parser = GetLogicalDriveStrings_Mounts;
3519 ret = GetLogicalDriveStrings_Mtab (len, buf);
3523 memset (&state, 0, sizeof (LinuxMountInfoParseState));
3524 state.field_number = 1;
3525 state.delimiter = ' ';
3527 while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3528 state.buffer_index = 0;
3530 while ((*parser)(len, buf, &state)) {
3531 if (state.buffer [state.buffer_index] == '\n') {
3532 gboolean quit = add_drive_string (len, buf, &state);
3533 state.field_number = 1;
3534 state.buffer_index++;
3535 if (state.mountpoint_allocated) {
3536 g_free (state.mountpoint_allocated);
3537 state.mountpoint_allocated = NULL;
3554 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3558 if (state->field_number == 1)
3559 state->check_mount_source = TRUE;
3561 while (state->buffer_index < (guint32)state->nbytes) {
3562 if (state->buffer [state->buffer_index] == state->delimiter) {
3563 state->field_number++;
3564 switch (state->field_number) {
3566 state->mountpoint_index = 0;
3570 if (state->mountpoint_allocated)
3571 state->mountpoint_allocated [state->mountpoint_index] = 0;
3573 state->mountpoint [state->mountpoint_index] = 0;
3577 ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3579 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3581 state->buffer_index = state->nbytes;
3584 state->buffer_index++;
3586 } else if (state->buffer [state->buffer_index] == '\n')
3589 switch (state->field_number) {
3591 if (state->check_mount_source) {
3592 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3593 /* We can ignore the rest, it's a device
3595 state->check_mount_source = FALSE;
3596 state->fsname [state->fsname_index++] = '/';
3599 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3600 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3605 append_to_mountpoint (state);
3609 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3610 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3614 state->buffer_index++;
3620 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3622 while (state->buffer_index < (guint32)state->nbytes) {
3623 if (state->buffer [state->buffer_index] == state->delimiter) {
3624 state->field_number++;
3625 switch (state->field_number) {
3627 state->mountpoint_index = 0;
3631 if (state->mountpoint_allocated)
3632 state->mountpoint_allocated [state->mountpoint_index] = 0;
3634 state->mountpoint [state->mountpoint_index] = 0;
3638 state->delimiter = '-';
3642 state->delimiter = ' ';
3646 state->check_mount_source = TRUE;
3649 state->buffer_index++;
3651 } else if (state->buffer [state->buffer_index] == '\n')
3654 switch (state->field_number) {
3656 append_to_mountpoint (state);
3660 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3661 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3665 if (state->check_mount_source) {
3666 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3667 /* We can ignore the rest, it's a device
3669 state->check_mount_source = FALSE;
3670 state->fsname [state->fsname_index++] = '/';
3673 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3674 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3679 state->buffer_index++;
3686 append_to_mountpoint (LinuxMountInfoParseState *state)
3688 gchar ch = state->buffer [state->buffer_index];
3689 if (state->mountpoint_allocated) {
3690 if (state->mountpoint_index >= state->allocated_size) {
3691 guint32 newsize = (state->allocated_size << 1) + 1;
3692 gchar *newbuf = (gchar *)g_malloc0 (newsize * sizeof (gchar));
3694 memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3695 g_free (state->mountpoint_allocated);
3696 state->mountpoint_allocated = newbuf;
3697 state->allocated_size = newsize;
3699 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3701 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3702 state->allocated_size = (state->mountpoint_index << 1) + 1;
3703 state->mountpoint_allocated = (gchar *)g_malloc0 (state->allocated_size * sizeof (gchar));
3704 memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3705 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3707 state->mountpoint [state->mountpoint_index++] = ch;
3712 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3714 gboolean quit = FALSE;
3715 gboolean ignore_entry;
3717 if (state->fsname_index == 1 && state->fsname [0] == '/')
3718 ignore_entry = FALSE;
3719 else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0)
3720 ignore_entry = TRUE;
3721 else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3722 /* Ignore GNOME's gvfs */
3723 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3724 ignore_entry = TRUE;
3726 ignore_entry = FALSE;
3727 } else if (state->fstype_index == 3 && memcmp ("nfs", state->fstype, state->fstype_index) == 0)
3728 ignore_entry = FALSE;
3730 ignore_entry = TRUE;
3732 if (!ignore_entry) {
3735 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3737 unescape_octal (mountpoint);
3738 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3739 if (state->total + length + 1 > len) {
3741 state->total = len * 2;
3744 memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3745 state->total += length;
3749 state->fsname_index = 0;
3750 state->fstype_index = 0;
3756 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3758 return GetLogicalDriveStrings_Mtab (len, buf);
3762 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3765 gunichar2 *ptr, *dir;
3766 glong length, total = 0;
3770 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3775 /* Sigh, mntent and friends don't work well.
3776 * It stops on the first line that doesn't begin with a '/'.
3777 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3778 fp = fopen ("/etc/mtab", "rt");
3780 fp = fopen ("/etc/mnttab", "rt");
3786 while (fgets (buffer, 512, fp) != NULL) {
3790 splitted = g_strsplit (buffer, " ", 0);
3791 if (!*splitted || !*(splitted + 1)) {
3792 g_strfreev (splitted);
3796 unescape_octal (*(splitted + 1));
3797 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3798 g_strfreev (splitted);
3799 if (total + length + 1 > len) {
3802 return len * 2; /* guess */
3805 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3807 total += length + 1;
3812 /* Commented out, does not work with my mtab!!! - Gonz */
3813 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3817 gunichar2 *ptr, *dir;
3818 glong len, total = 0;
3821 fp = setmntent ("/etc/mtab", "rt");
3823 fp = setmntent ("/etc/mnttab", "rt");
3829 while ((mnt = getmntent (fp)) != NULL) {
3830 g_print ("GOT %s\n", mnt->mnt_dir);
3831 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3832 if (total + len + 1 > len) {
3833 return len * 2; /* guess */
3836 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3848 #if defined(HAVE_STATVFS) || defined(HAVE_STATFS)
3849 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3850 WapiULargeInteger *total_number_of_bytes,
3851 WapiULargeInteger *total_number_of_free_bytes)
3854 struct statvfs fsstat;
3855 #elif defined(HAVE_STATFS)
3856 struct statfs fsstat;
3858 gboolean isreadonly;
3859 gchar *utf8_path_name;
3861 unsigned long block_size;
3863 if (path_name == NULL) {
3864 utf8_path_name = g_strdup (g_get_current_dir());
3865 if (utf8_path_name == NULL) {
3866 SetLastError (ERROR_DIRECTORY);
3871 utf8_path_name = mono_unicode_to_external (path_name);
3872 if (utf8_path_name == NULL) {
3873 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3875 SetLastError (ERROR_INVALID_NAME);
3882 ret = statvfs (utf8_path_name, &fsstat);
3883 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
3884 block_size = fsstat.f_frsize;
3885 #elif defined(HAVE_STATFS)
3886 ret = statfs (utf8_path_name, &fsstat);
3887 #if defined (MNT_RDONLY)
3888 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
3889 #elif defined (MS_RDONLY)
3890 isreadonly = ((fsstat.f_flags & MS_RDONLY) == MS_RDONLY);
3892 block_size = fsstat.f_bsize;
3894 } while(ret == -1 && errno == EINTR);
3896 g_free(utf8_path_name);
3899 _wapi_set_last_error_from_errno ();
3900 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: statvfs failed: %s", __func__, strerror (errno));
3904 /* total number of free bytes for non-root */
3905 if (free_bytes_avail != NULL) {
3907 free_bytes_avail->QuadPart = 0;
3910 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
3914 /* total number of bytes available for non-root */
3915 if (total_number_of_bytes != NULL) {
3916 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
3919 /* total number of bytes available for root */
3920 if (total_number_of_free_bytes != NULL) {
3922 total_number_of_free_bytes->QuadPart = 0;
3925 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
3932 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3933 WapiULargeInteger *total_number_of_bytes,
3934 WapiULargeInteger *total_number_of_free_bytes)
3936 if (free_bytes_avail != NULL) {
3937 free_bytes_avail->QuadPart = (guint64) -1;
3940 if (total_number_of_bytes != NULL) {
3941 total_number_of_bytes->QuadPart = (guint64) -1;
3944 if (total_number_of_free_bytes != NULL) {
3945 total_number_of_free_bytes->QuadPart = (guint64) -1;
3953 * General Unix support
3958 const long fstypeid;
3960 const gchar* fstype;
3963 static _wapi_drive_type _wapi_drive_types[] = {
3965 { DRIVE_REMOTE, "afp" },
3966 { DRIVE_REMOTE, "autofs" },
3967 { DRIVE_CDROM, "cddafs" },
3968 { DRIVE_CDROM, "cd9660" },
3969 { DRIVE_RAMDISK, "devfs" },
3970 { DRIVE_FIXED, "exfat" },
3971 { DRIVE_RAMDISK, "fdesc" },
3972 { DRIVE_REMOTE, "ftp" },
3973 { DRIVE_FIXED, "hfs" },
3974 { DRIVE_FIXED, "msdos" },
3975 { DRIVE_REMOTE, "nfs" },
3976 { DRIVE_FIXED, "ntfs" },
3977 { DRIVE_REMOTE, "smbfs" },
3978 { DRIVE_FIXED, "udf" },
3979 { DRIVE_REMOTE, "webdav" },
3980 { DRIVE_UNKNOWN, NULL }
3982 { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
3983 { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
3984 { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
3985 { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
3986 { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
3987 { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
3988 { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
3989 { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
3990 { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
3991 { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
3992 { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
3993 { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
3994 { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
3995 { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
3996 { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
3997 { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
3998 { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
3999 { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4000 { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4001 { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4002 { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4003 { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4004 { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4005 { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4006 { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4007 { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4008 { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4009 { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4010 { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4011 { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4012 { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4013 { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4014 { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4015 { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4016 { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4017 { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4018 { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4019 { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4020 { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4021 { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4022 { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4023 { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4024 { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4025 { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4026 { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4027 { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4028 { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4029 { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4030 { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4031 { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4032 { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4033 { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4034 { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4035 { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4036 { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4037 { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4038 { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4039 { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4040 { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4041 { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4042 { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4043 { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4044 { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4045 { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4046 { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4047 { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4048 { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4049 { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4050 { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4051 { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4052 { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4053 { DRIVE_UNKNOWN, 0, NULL}
4055 { DRIVE_RAMDISK, "ramfs" },
4056 { DRIVE_RAMDISK, "tmpfs" },
4057 { DRIVE_RAMDISK, "proc" },
4058 { DRIVE_RAMDISK, "sysfs" },
4059 { DRIVE_RAMDISK, "debugfs" },
4060 { DRIVE_RAMDISK, "devpts" },
4061 { DRIVE_RAMDISK, "securityfs" },
4062 { DRIVE_CDROM, "iso9660" },
4063 { DRIVE_FIXED, "ext2" },
4064 { DRIVE_FIXED, "ext3" },
4065 { DRIVE_FIXED, "ext4" },
4066 { DRIVE_FIXED, "sysv" },
4067 { DRIVE_FIXED, "reiserfs" },
4068 { DRIVE_FIXED, "ufs" },
4069 { DRIVE_FIXED, "vfat" },
4070 { DRIVE_FIXED, "msdos" },
4071 { DRIVE_FIXED, "udf" },
4072 { DRIVE_FIXED, "hfs" },
4073 { DRIVE_FIXED, "hpfs" },
4074 { DRIVE_FIXED, "qnx4" },
4075 { DRIVE_FIXED, "ntfs" },
4076 { DRIVE_FIXED, "ntfs-3g" },
4077 { DRIVE_REMOTE, "smbfs" },
4078 { DRIVE_REMOTE, "fuse" },
4079 { DRIVE_REMOTE, "nfs" },
4080 { DRIVE_REMOTE, "nfs4" },
4081 { DRIVE_REMOTE, "cifs" },
4082 { DRIVE_REMOTE, "ncpfs" },
4083 { DRIVE_REMOTE, "coda" },
4084 { DRIVE_REMOTE, "afs" },
4085 { DRIVE_UNKNOWN, NULL }
4090 static guint32 _wapi_get_drive_type(long f_type)
4092 _wapi_drive_type *current;
4094 current = &_wapi_drive_types[0];
4095 while (current->drive_type != DRIVE_UNKNOWN) {
4096 if (current->fstypeid == f_type)
4097 return current->drive_type;
4101 return DRIVE_UNKNOWN;
4104 static guint32 _wapi_get_drive_type(const gchar* fstype)
4106 _wapi_drive_type *current;
4108 current = &_wapi_drive_types[0];
4109 while (current->drive_type != DRIVE_UNKNOWN) {
4110 if (strcmp (current->fstype, fstype) == 0)
4116 return current->drive_type;
4120 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4122 GetDriveTypeFromPath (const char *utf8_root_path_name)
4126 if (statfs (utf8_root_path_name, &buf) == -1)
4127 return DRIVE_UNKNOWN;
4129 return _wapi_get_drive_type (buf.f_fstypename);
4131 return _wapi_get_drive_type (buf.f_type);
4136 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4143 fp = fopen ("/etc/mtab", "rt");
4145 fp = fopen ("/etc/mnttab", "rt");
4147 return(DRIVE_UNKNOWN);
4150 drive_type = DRIVE_NO_ROOT_DIR;
4151 while (fgets (buffer, 512, fp) != NULL) {
4152 splitted = g_strsplit (buffer, " ", 0);
4153 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4154 g_strfreev (splitted);
4158 /* compare given root_path_name with the one from mtab,
4159 if length of utf8_root_path_name is zero it must be the root dir */
4160 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4161 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4162 drive_type = _wapi_get_drive_type (*(splitted + 2));
4163 /* it is possible this path might be mounted again with
4164 a known type...keep looking */
4165 if (drive_type != DRIVE_UNKNOWN) {
4166 g_strfreev (splitted);
4171 g_strfreev (splitted);
4179 guint32 GetDriveType(const gunichar2 *root_path_name)
4181 gchar *utf8_root_path_name;
4184 if (root_path_name == NULL) {
4185 utf8_root_path_name = g_strdup (g_get_current_dir());
4186 if (utf8_root_path_name == NULL) {
4187 return(DRIVE_NO_ROOT_DIR);
4191 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4192 if (utf8_root_path_name == NULL) {
4193 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4194 return(DRIVE_NO_ROOT_DIR);
4197 /* strip trailing slash for compare below */
4198 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4199 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4202 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4203 g_free (utf8_root_path_name);
4205 return (drive_type);
4208 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__) || defined(__FreeBSD_kernel__)
4210 get_fstypename (gchar *utfpath)
4212 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4215 _wapi_drive_type *current;
4217 if (statfs (utfpath, &stat) == -1)
4220 return g_strdup (stat.f_fstypename);
4222 current = &_wapi_drive_types[0];
4223 while (current->drive_type != DRIVE_UNKNOWN) {
4224 if (stat.f_type == current->fstypeid)
4225 return g_strdup (current->fstype);
4235 /* Linux has struct statfs which has a different layout */
4237 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4241 gboolean status = FALSE;
4244 // We only support getting the file system type
4245 if (fsbuffer == NULL)
4248 utfpath = mono_unicode_to_external (path);
4249 if ((fstypename = get_fstypename (utfpath)) != NULL){
4250 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4251 if (ret != NULL && len < fsbuffersize){
4252 memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4258 g_free (fstypename);
4267 _wapi_io_init (void)
4269 mono_os_mutex_init (&stdhandle_mutex);