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 generally 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)
256 // OS X Finder "locked" or `ls -lO` "uchg".
257 // This only covers one of several cases where an OS X file could be unwritable through special flags.
258 if (st->st_flags & (UF_IMMUTABLE|SF_IMMUTABLE))
262 /* Is it globally writable? */
263 if (st->st_mode & S_IWOTH)
266 /* Am I the owner? */
267 if ((st->st_uid == geteuid ()) && (st->st_mode & S_IWUSR))
270 /* Am I in the same group? */
271 if ((st->st_gid == getegid ()) && (st->st_mode & S_IWGRP))
274 /* Fallback to using access(2). It's not ideal as it might not take into consideration euid/egid
275 * but it's the only sane option we have on unix.
277 return access (path, W_OK) == 0;
281 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
288 /* FIXME: this could definitely be better, but there seems to
289 * be no pattern to the attributes that are set
292 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
293 if (S_ISSOCK (buf->st_mode))
294 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
296 filename = _wapi_basename (pathname);
298 if (S_ISDIR (buf->st_mode)) {
299 attrs = FILE_ATTRIBUTE_DIRECTORY;
300 if (!is_file_writable (buf, pathname)) {
301 attrs |= FILE_ATTRIBUTE_READONLY;
303 if (filename[0] == '.') {
304 attrs |= FILE_ATTRIBUTE_HIDDEN;
307 if (!is_file_writable (buf, pathname)) {
308 attrs = FILE_ATTRIBUTE_READONLY;
310 if (filename[0] == '.') {
311 attrs |= FILE_ATTRIBUTE_HIDDEN;
313 } else if (filename[0] == '.') {
314 attrs = FILE_ATTRIBUTE_HIDDEN;
316 attrs = FILE_ATTRIBUTE_NORMAL;
321 if (S_ISLNK (lbuf->st_mode)) {
322 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
332 _wapi_set_last_error_from_errno (void)
334 SetLastError (_wapi_get_win32_file_error (errno));
337 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
340 if (errno == ENOENT) {
341 /* Check the path - if it's a missing directory then
342 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
348 dirname = _wapi_dirname (path);
350 dirname = g_strdup (dir);
353 if (_wapi_access (dirname, F_OK) == 0) {
354 SetLastError (ERROR_FILE_NOT_FOUND);
356 SetLastError (ERROR_PATH_NOT_FOUND);
361 _wapi_set_last_error_from_errno ();
367 static void file_close (gpointer handle, gpointer data)
369 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
370 int fd = file_handle->fd;
372 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing file handle %p [%s]", __func__, handle,
373 file_handle->filename);
375 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
376 _wapi_unlink (file_handle->filename);
378 g_free (file_handle->filename);
380 if (file_handle->share_info)
381 _wapi_handle_share_release (file_handle->share_info);
386 static WapiFileType file_getfiletype(void)
388 return(FILE_TYPE_DISK);
391 static gboolean file_read(gpointer handle, gpointer buffer,
392 guint32 numbytes, guint32 *bytesread,
393 WapiOverlapped *overlapped)
395 struct _WapiHandle_file *file_handle;
399 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
400 (gpointer *)&file_handle);
402 g_warning ("%s: error looking up file handle %p", __func__,
404 SetLastError (ERROR_INVALID_HANDLE);
408 fd = file_handle->fd;
409 if(bytesread!=NULL) {
413 if(!(file_handle->fileaccess & GENERIC_READ) &&
414 !(file_handle->fileaccess & GENERIC_ALL)) {
415 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
416 __func__, handle, file_handle->fileaccess);
418 SetLastError (ERROR_ACCESS_DENIED);
423 ret = read (fd, buffer, numbytes);
424 } while (ret == -1 && errno == EINTR &&
425 !_wapi_thread_cur_apc_pending());
430 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
431 handle, strerror(err));
432 SetLastError (_wapi_get_win32_file_error (err));
436 if (bytesread != NULL) {
443 static gboolean file_write(gpointer handle, gconstpointer buffer,
444 guint32 numbytes, guint32 *byteswritten,
445 WapiOverlapped *overlapped G_GNUC_UNUSED)
447 struct _WapiHandle_file *file_handle;
450 off_t current_pos = 0;
452 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
453 (gpointer *)&file_handle);
455 g_warning ("%s: error looking up file handle %p", __func__,
457 SetLastError (ERROR_INVALID_HANDLE);
461 fd = file_handle->fd;
463 if(byteswritten!=NULL) {
467 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
468 !(file_handle->fileaccess & GENERIC_ALL)) {
469 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);
471 SetLastError (ERROR_ACCESS_DENIED);
475 if (lock_while_writing) {
476 /* Need to lock the region we're about to write to,
477 * because we only do advisory locking on POSIX
480 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
481 if (current_pos == -1) {
482 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
483 handle, strerror (errno));
484 _wapi_set_last_error_from_errno ();
488 if (_wapi_lock_file_region (fd, current_pos,
489 numbytes) == FALSE) {
490 /* The error has already been set */
496 ret = write (fd, buffer, numbytes);
497 } while (ret == -1 && errno == EINTR &&
498 !_wapi_thread_cur_apc_pending());
500 if (lock_while_writing) {
501 _wapi_unlock_file_region (fd, current_pos, numbytes);
505 if (errno == EINTR) {
508 _wapi_set_last_error_from_errno ();
510 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
511 __func__, handle, strerror(errno));
516 if (byteswritten != NULL) {
522 static gboolean file_flush(gpointer handle)
524 struct _WapiHandle_file *file_handle;
528 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
529 (gpointer *)&file_handle);
531 g_warning ("%s: error looking up file handle %p", __func__,
533 SetLastError (ERROR_INVALID_HANDLE);
537 fd = file_handle->fd;
539 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
540 !(file_handle->fileaccess & GENERIC_ALL)) {
541 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);
543 SetLastError (ERROR_ACCESS_DENIED);
549 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fsync of handle %p error: %s", __func__, handle,
552 _wapi_set_last_error_from_errno ();
559 static guint32 file_seek(gpointer handle, gint32 movedistance,
560 gint32 *highmovedistance, WapiSeekMethod method)
562 struct _WapiHandle_file *file_handle;
564 gint64 offset, newpos;
568 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
569 (gpointer *)&file_handle);
571 g_warning ("%s: error looking up file handle %p", __func__,
573 SetLastError (ERROR_INVALID_HANDLE);
574 return(INVALID_SET_FILE_POINTER);
577 fd = file_handle->fd;
579 if(!(file_handle->fileaccess & GENERIC_READ) &&
580 !(file_handle->fileaccess & GENERIC_WRITE) &&
581 !(file_handle->fileaccess & GENERIC_ALL)) {
582 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);
584 SetLastError (ERROR_ACCESS_DENIED);
585 return(INVALID_SET_FILE_POINTER);
599 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: invalid seek type %d", __func__, method);
601 SetLastError (ERROR_INVALID_PARAMETER);
602 return(INVALID_SET_FILE_POINTER);
605 #ifdef HAVE_LARGE_FILE_SUPPORT
606 if(highmovedistance==NULL) {
608 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting offset to %lld (low %d)", __func__,
609 offset, movedistance);
611 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
613 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);
619 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: moving handle %p by %lld bytes from %d", __func__,
620 handle, (long long)offset, whence);
622 #ifdef PLATFORM_ANDROID
623 /* bionic doesn't support -D_FILE_OFFSET_BITS=64 */
624 newpos=lseek64(fd, offset, whence);
626 newpos=lseek(fd, offset, whence);
629 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek on handle %p returned error %s",
630 __func__, handle, strerror(errno));
632 _wapi_set_last_error_from_errno ();
633 return(INVALID_SET_FILE_POINTER);
636 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek returns %lld", __func__, newpos);
638 #ifdef HAVE_LARGE_FILE_SUPPORT
639 ret=newpos & 0xFFFFFFFF;
640 if(highmovedistance!=NULL) {
641 *highmovedistance=newpos>>32;
645 if(highmovedistance!=NULL) {
646 /* Accurate, but potentially dodgy :-) */
651 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: move of handle %p returning %d/%d", __func__,
652 handle, ret, highmovedistance==NULL?0:*highmovedistance);
657 static gboolean file_setendoffile(gpointer handle)
659 struct _WapiHandle_file *file_handle;
665 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
666 (gpointer *)&file_handle);
668 g_warning ("%s: error looking up file handle %p", __func__,
670 SetLastError (ERROR_INVALID_HANDLE);
673 fd = file_handle->fd;
675 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
676 !(file_handle->fileaccess & GENERIC_ALL)) {
677 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);
679 SetLastError (ERROR_ACCESS_DENIED);
683 /* Find the current file position, and the file length. If
684 * the file position is greater than the length, write to
685 * extend the file with a hole. If the file position is less
686 * than the length, truncate the file.
689 ret=fstat(fd, &statbuf);
691 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
692 handle, strerror(errno));
694 _wapi_set_last_error_from_errno ();
698 pos=lseek(fd, (off_t)0, SEEK_CUR);
700 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
701 handle, strerror(errno));
703 _wapi_set_last_error_from_errno ();
707 #ifdef FTRUNCATE_DOESNT_EXTEND
708 off_t size = statbuf.st_size;
709 /* I haven't bothered to write the configure.ac stuff for this
710 * because I don't know if any platform needs it. I'm leaving
711 * this code just in case though
714 /* Extend the file. Use write() here, because some
715 * manuals say that ftruncate() behaviour is undefined
716 * when the file needs extending. The POSIX spec says
717 * that on XSI-conformant systems it extends, so if
718 * every system we care about conforms, then we can
722 ret = write (fd, "", 1);
723 } while (ret == -1 && errno == EINTR &&
724 !_wapi_thread_cur_apc_pending());
727 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
729 _wapi_set_last_error_from_errno ();
733 /* And put the file position back after the write */
734 ret = lseek (fd, pos, SEEK_SET);
736 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p second lseek failed: %s",
737 __func__, handle, strerror(errno));
739 _wapi_set_last_error_from_errno ();
745 /* Native Client has no ftruncate function, even in standalone sel_ldr. */
746 #ifndef __native_client__
747 /* always truncate, because the extend write() adds an extra
748 * byte to the end of the file
751 ret=ftruncate(fd, pos);
753 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
755 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ftruncate failed: %s", __func__,
756 handle, strerror(errno));
758 _wapi_set_last_error_from_errno ();
766 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
768 struct _WapiHandle_file *file_handle;
775 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
776 (gpointer *)&file_handle);
778 g_warning ("%s: error looking up file handle %p", __func__,
780 SetLastError (ERROR_INVALID_HANDLE);
781 return(INVALID_FILE_SIZE);
783 fd = file_handle->fd;
785 if(!(file_handle->fileaccess & GENERIC_READ) &&
786 !(file_handle->fileaccess & GENERIC_WRITE) &&
787 !(file_handle->fileaccess & GENERIC_ALL)) {
788 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);
790 SetLastError (ERROR_ACCESS_DENIED);
791 return(INVALID_FILE_SIZE);
794 /* If the file has a size with the low bits 0xFFFFFFFF the
795 * caller can't tell if this is an error, so clear the error
798 SetLastError (ERROR_SUCCESS);
800 ret = fstat(fd, &statbuf);
802 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
803 handle, strerror(errno));
805 _wapi_set_last_error_from_errno ();
806 return(INVALID_FILE_SIZE);
809 /* fstat indicates block devices as zero-length, so go a different path */
811 if (S_ISBLK(statbuf.st_mode)) {
813 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
814 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ioctl BLKGETSIZE64 failed: %s",
815 __func__, handle, strerror(errno));
817 _wapi_set_last_error_from_errno ();
818 return(INVALID_FILE_SIZE);
821 size = bigsize & 0xFFFFFFFF;
822 if (highsize != NULL) {
823 *highsize = bigsize>>32;
826 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning block device size %d/%d",
827 __func__, size, *highsize);
833 #ifdef HAVE_LARGE_FILE_SUPPORT
834 size = statbuf.st_size & 0xFFFFFFFF;
835 if (highsize != NULL) {
836 *highsize = statbuf.st_size>>32;
839 if (highsize != NULL) {
840 /* Accurate, but potentially dodgy :-) */
843 size = statbuf.st_size;
846 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning size %d/%d", __func__, size, *highsize);
851 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
852 WapiFileTime *last_access,
853 WapiFileTime *last_write)
855 struct _WapiHandle_file *file_handle;
858 guint64 create_ticks, access_ticks, write_ticks;
861 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
862 (gpointer *)&file_handle);
864 g_warning ("%s: error looking up file handle %p", __func__,
866 SetLastError (ERROR_INVALID_HANDLE);
869 fd = file_handle->fd;
871 if(!(file_handle->fileaccess & GENERIC_READ) &&
872 !(file_handle->fileaccess & GENERIC_ALL)) {
873 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
874 __func__, handle, file_handle->fileaccess);
876 SetLastError (ERROR_ACCESS_DENIED);
880 ret=fstat(fd, &statbuf);
882 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
885 _wapi_set_last_error_from_errno ();
889 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: atime: %ld ctime: %ld mtime: %ld", __func__,
890 statbuf.st_atime, statbuf.st_ctime,
893 /* Try and guess a meaningful create time by using the older
896 /* The magic constant comes from msdn documentation
897 * "Converting a time_t Value to a File Time"
899 if(statbuf.st_atime < statbuf.st_ctime) {
900 create_ticks=((guint64)statbuf.st_atime*10000000)
901 + 116444736000000000ULL;
903 create_ticks=((guint64)statbuf.st_ctime*10000000)
904 + 116444736000000000ULL;
907 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
908 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
910 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
911 access_ticks, create_ticks, write_ticks);
913 if(create_time!=NULL) {
914 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
915 create_time->dwHighDateTime = create_ticks >> 32;
918 if(last_access!=NULL) {
919 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
920 last_access->dwHighDateTime = access_ticks >> 32;
923 if(last_write!=NULL) {
924 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
925 last_write->dwHighDateTime = write_ticks >> 32;
931 static gboolean file_setfiletime(gpointer handle,
932 const WapiFileTime *create_time G_GNUC_UNUSED,
933 const WapiFileTime *last_access,
934 const WapiFileTime *last_write)
936 struct _WapiHandle_file *file_handle;
938 struct utimbuf utbuf;
940 guint64 access_ticks, write_ticks;
943 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
944 (gpointer *)&file_handle);
946 g_warning ("%s: error looking up file handle %p", __func__,
948 SetLastError (ERROR_INVALID_HANDLE);
951 fd = file_handle->fd;
953 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
954 !(file_handle->fileaccess & GENERIC_ALL)) {
955 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);
957 SetLastError (ERROR_ACCESS_DENIED);
961 if(file_handle->filename == NULL) {
962 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p unknown filename", __func__, handle);
964 SetLastError (ERROR_INVALID_HANDLE);
968 /* Get the current times, so we can put the same times back in
969 * the event that one of the FileTime structs is NULL
971 ret=fstat (fd, &statbuf);
973 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
976 SetLastError (ERROR_INVALID_PARAMETER);
980 if(last_access!=NULL) {
981 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
982 last_access->dwLowDateTime;
983 /* This is (time_t)0. We can actually go to INT_MIN,
984 * but this will do for now.
986 if (access_ticks < 116444736000000000ULL) {
987 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set access time too early",
989 SetLastError (ERROR_INVALID_PARAMETER);
993 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
995 utbuf.actime=statbuf.st_atime;
998 if(last_write!=NULL) {
999 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
1000 last_write->dwLowDateTime;
1001 /* This is (time_t)0. We can actually go to INT_MIN,
1002 * but this will do for now.
1004 if (write_ticks < 116444736000000000ULL) {
1005 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set write time too early",
1007 SetLastError (ERROR_INVALID_PARAMETER);
1011 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1013 utbuf.modtime=statbuf.st_mtime;
1016 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting handle %p access %ld write %ld", __func__,
1017 handle, utbuf.actime, utbuf.modtime);
1019 ret = _wapi_utime (file_handle->filename, &utbuf);
1021 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p [%s] utime failed: %s", __func__,
1022 handle, file_handle->filename, strerror(errno));
1024 SetLastError (ERROR_INVALID_PARAMETER);
1031 static void console_close (gpointer handle, gpointer data)
1033 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1034 int fd = console_handle->fd;
1036 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing console handle %p", __func__, handle);
1038 g_free (console_handle->filename);
1041 if (console_handle->share_info)
1042 _wapi_handle_share_release (console_handle->share_info);
1047 static WapiFileType console_getfiletype(void)
1049 return(FILE_TYPE_CHAR);
1052 static gboolean console_read(gpointer handle, gpointer buffer,
1053 guint32 numbytes, guint32 *bytesread,
1054 WapiOverlapped *overlapped G_GNUC_UNUSED)
1056 struct _WapiHandle_file *console_handle;
1060 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1061 (gpointer *)&console_handle);
1063 g_warning ("%s: error looking up console handle %p", __func__,
1065 SetLastError (ERROR_INVALID_HANDLE);
1068 fd = console_handle->fd;
1070 if(bytesread!=NULL) {
1074 if(!(console_handle->fileaccess & GENERIC_READ) &&
1075 !(console_handle->fileaccess & GENERIC_ALL)) {
1076 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1077 __func__, handle, console_handle->fileaccess);
1079 SetLastError (ERROR_ACCESS_DENIED);
1084 ret=read(fd, buffer, numbytes);
1085 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1088 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__, handle,
1091 _wapi_set_last_error_from_errno ();
1095 if(bytesread!=NULL) {
1102 static gboolean console_write(gpointer handle, gconstpointer buffer,
1103 guint32 numbytes, guint32 *byteswritten,
1104 WapiOverlapped *overlapped G_GNUC_UNUSED)
1106 struct _WapiHandle_file *console_handle;
1110 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1111 (gpointer *)&console_handle);
1113 g_warning ("%s: error looking up console handle %p", __func__,
1115 SetLastError (ERROR_INVALID_HANDLE);
1118 fd = console_handle->fd;
1120 if(byteswritten!=NULL) {
1124 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1125 !(console_handle->fileaccess & GENERIC_ALL)) {
1126 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);
1128 SetLastError (ERROR_ACCESS_DENIED);
1133 ret = write(fd, buffer, numbytes);
1134 } while (ret == -1 && errno == EINTR &&
1135 !_wapi_thread_cur_apc_pending());
1138 if (errno == EINTR) {
1141 _wapi_set_last_error_from_errno ();
1143 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
1144 __func__, handle, strerror(errno));
1149 if(byteswritten!=NULL) {
1156 static void pipe_close (gpointer handle, gpointer data)
1158 struct _WapiHandle_file *pipe_handle = (struct _WapiHandle_file*)data;
1159 int fd = pipe_handle->fd;
1161 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing pipe handle %p", __func__, handle);
1163 /* No filename with pipe handles */
1165 if (pipe_handle->share_info)
1166 _wapi_handle_share_release (pipe_handle->share_info);
1171 static WapiFileType pipe_getfiletype(void)
1173 return(FILE_TYPE_PIPE);
1176 static gboolean pipe_read (gpointer handle, gpointer buffer,
1177 guint32 numbytes, guint32 *bytesread,
1178 WapiOverlapped *overlapped G_GNUC_UNUSED)
1180 struct _WapiHandle_file *pipe_handle;
1184 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1185 (gpointer *)&pipe_handle);
1187 g_warning ("%s: error looking up pipe handle %p", __func__,
1189 SetLastError (ERROR_INVALID_HANDLE);
1192 fd = pipe_handle->fd;
1194 if(bytesread!=NULL) {
1198 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1199 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1200 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1201 __func__, handle, pipe_handle->fileaccess);
1203 SetLastError (ERROR_ACCESS_DENIED);
1207 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: reading up to %d bytes from pipe %p", __func__,
1211 ret=read(fd, buffer, numbytes);
1212 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1215 if (errno == EINTR) {
1218 _wapi_set_last_error_from_errno ();
1220 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
1221 handle, strerror(errno));
1227 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read %d bytes from pipe %p", __func__, ret, handle);
1229 if(bytesread!=NULL) {
1236 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1237 guint32 numbytes, guint32 *byteswritten,
1238 WapiOverlapped *overlapped G_GNUC_UNUSED)
1240 struct _WapiHandle_file *pipe_handle;
1244 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1245 (gpointer *)&pipe_handle);
1247 g_warning ("%s: error looking up pipe handle %p", __func__,
1249 SetLastError (ERROR_INVALID_HANDLE);
1252 fd = pipe_handle->fd;
1254 if(byteswritten!=NULL) {
1258 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1259 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1260 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);
1262 SetLastError (ERROR_ACCESS_DENIED);
1266 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1270 ret = write (fd, buffer, numbytes);
1271 } while (ret == -1 && errno == EINTR &&
1272 !_wapi_thread_cur_apc_pending());
1275 if (errno == EINTR) {
1278 _wapi_set_last_error_from_errno ();
1280 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s", __func__,
1281 handle, strerror(errno));
1286 if(byteswritten!=NULL) {
1293 static int convert_flags(guint32 fileaccess, guint32 createmode)
1297 switch(fileaccess) {
1304 case GENERIC_READ|GENERIC_WRITE:
1308 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown access type 0x%x", __func__,
1313 switch(createmode) {
1315 flags|=O_CREAT|O_EXCL;
1318 flags|=O_CREAT|O_TRUNC;
1325 case TRUNCATE_EXISTING:
1329 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown create mode 0x%x", __func__,
1338 static mode_t convert_perms(guint32 sharemode)
1342 if(sharemode&FILE_SHARE_READ) {
1345 if(sharemode&FILE_SHARE_WRITE) {
1353 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1355 struct _WapiFileShare **share_info)
1357 gboolean file_already_shared;
1358 guint32 file_existing_share, file_existing_access;
1360 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);
1362 if (file_already_shared) {
1363 /* The reference to this share info was incremented
1364 * when we looked it up, so be careful to put it back
1365 * if we conclude we can't use this file.
1367 if (file_existing_share == 0) {
1368 /* Quick and easy, no possibility to share */
1369 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);
1371 _wapi_handle_share_release (*share_info);
1376 if (((file_existing_share == FILE_SHARE_READ) &&
1377 (fileaccess != GENERIC_READ)) ||
1378 ((file_existing_share == FILE_SHARE_WRITE) &&
1379 (fileaccess != GENERIC_WRITE))) {
1380 /* New access mode doesn't match up */
1381 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);
1383 _wapi_handle_share_release (*share_info);
1388 if (((file_existing_access & GENERIC_READ) &&
1389 !(sharemode & FILE_SHARE_READ)) ||
1390 ((file_existing_access & GENERIC_WRITE) &&
1391 !(sharemode & FILE_SHARE_WRITE))) {
1392 /* New share mode doesn't match up */
1393 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);
1395 _wapi_handle_share_release (*share_info);
1400 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
1408 share_allows_delete (struct stat *statbuf, struct _WapiFileShare **share_info)
1410 gboolean file_already_shared;
1411 guint32 file_existing_share, file_existing_access;
1413 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);
1415 if (file_already_shared) {
1416 /* The reference to this share info was incremented
1417 * when we looked it up, so be careful to put it back
1418 * if we conclude we can't use this file.
1420 if (file_existing_share == 0) {
1421 /* Quick and easy, no possibility to share */
1422 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);
1424 _wapi_handle_share_release (*share_info);
1429 if (!(file_existing_share & FILE_SHARE_DELETE)) {
1430 /* New access mode doesn't match up */
1431 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);
1433 _wapi_handle_share_release (*share_info);
1438 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
1443 static gboolean share_check (struct stat *statbuf, guint32 sharemode,
1445 struct _WapiFileShare **share_info, int fd)
1447 if (share_allows_open (statbuf, sharemode, fileaccess,
1448 share_info) == TRUE) {
1452 /* Got a share violation. Double check that the file is still
1453 * open by someone, in case a process crashed while still
1454 * holding a file handle. This will also cope with someone
1455 * using Mono.Posix to close the file. This is cheaper and
1456 * less intrusive to other processes than initiating a handle
1460 _wapi_handle_check_share (*share_info, fd);
1461 if (share_allows_open (statbuf, sharemode, fileaccess,
1462 share_info) == TRUE) {
1466 return(share_allows_open (statbuf, sharemode, fileaccess, share_info));
1471 * @name: a pointer to a NULL-terminated unicode string, that names
1472 * the file or other object to create.
1473 * @fileaccess: specifies the file access mode
1474 * @sharemode: whether the file should be shared. This parameter is
1475 * currently ignored.
1476 * @security: Ignored for now.
1477 * @createmode: specifies whether to create a new file, whether to
1478 * overwrite an existing file, whether to truncate the file, etc.
1479 * @attrs: specifies file attributes and flags. On win32 attributes
1480 * are characteristics of the file, not the handle, and are ignored
1481 * when an existing file is opened. Flags give the library hints on
1482 * how to process a file to optimise performance.
1483 * @template: the handle of an open %GENERIC_READ file that specifies
1484 * attributes to apply to a newly created file, ignoring @attrs.
1485 * Normally this parameter is NULL. This parameter is ignored when an
1486 * existing file is opened.
1488 * Creates a new file handle. This only applies to normal files:
1489 * pipes are handled by CreatePipe(), and console handles are created
1490 * with GetStdHandle().
1492 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1494 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1495 guint32 sharemode, WapiSecurityAttributes *security,
1496 guint32 createmode, guint32 attrs,
1497 gpointer template_ G_GNUC_UNUSED)
1499 struct _WapiHandle_file file_handle = {0};
1501 int flags=convert_flags(fileaccess, createmode);
1502 /*mode_t perms=convert_perms(sharemode);*/
1503 /* we don't use sharemode, because that relates to sharing of
1504 * the file when the file is open and is already handled by
1505 * other code, perms instead are the on-disk permissions and
1506 * this is a sane default.
1511 WapiHandleType handle_type;
1512 struct stat statbuf;
1514 mono_once (&io_ops_once, io_ops_init);
1516 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1519 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1520 SetLastError (ERROR_ENCRYPTION_FAILED);
1521 return INVALID_HANDLE_VALUE;
1525 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1527 SetLastError (ERROR_INVALID_NAME);
1528 return(INVALID_HANDLE_VALUE);
1531 filename = mono_unicode_to_external (name);
1532 if (filename == NULL) {
1533 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1535 SetLastError (ERROR_INVALID_NAME);
1536 return(INVALID_HANDLE_VALUE);
1539 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Opening %s with share 0x%x and access 0x%x", __func__,
1540 filename, sharemode, fileaccess);
1542 fd = _wapi_open (filename, flags, perms);
1544 /* If we were trying to open a directory with write permissions
1545 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1546 * EISDIR. However, this is a bit bogus because calls to
1547 * manipulate the directory (e.g. SetFileTime) will still work on
1548 * the directory because they use other API calls
1549 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1550 * to open the directory again without write permission.
1552 if (fd == -1 && errno == EISDIR)
1554 /* Try again but don't try to make it writable */
1555 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1559 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s: %s", __func__, filename,
1561 _wapi_set_last_path_error_from_errno (NULL, filename);
1564 return(INVALID_HANDLE_VALUE);
1567 if (fd >= _wapi_fd_reserve) {
1568 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
1570 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1575 return(INVALID_HANDLE_VALUE);
1578 ret = fstat (fd, &statbuf);
1580 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fstat error of file %s: %s", __func__,
1581 filename, strerror (errno));
1582 _wapi_set_last_error_from_errno ();
1586 return(INVALID_HANDLE_VALUE);
1588 #ifdef __native_client__
1589 /* Workaround: Native Client currently returns the same fake inode
1590 * for all files, so do a simple hash on the filename so we don't
1591 * use the same share info for each file.
1593 statbuf.st_ino = g_str_hash(filename);
1596 if (share_check (&statbuf, sharemode, fileaccess,
1597 &file_handle.share_info, fd) == FALSE) {
1598 SetLastError (ERROR_SHARING_VIOLATION);
1602 return (INVALID_HANDLE_VALUE);
1604 if (file_handle.share_info == NULL) {
1605 /* No space, so no more files can be opened */
1606 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No space in the share table", __func__);
1608 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1612 return(INVALID_HANDLE_VALUE);
1615 file_handle.filename = filename;
1617 if(security!=NULL) {
1618 //file_handle->security_attributes=_wapi_handle_scratch_store (
1619 //security, sizeof(WapiSecurityAttributes));
1622 file_handle.fd = fd;
1623 file_handle.fileaccess=fileaccess;
1624 file_handle.sharemode=sharemode;
1625 file_handle.attrs=attrs;
1627 #ifdef HAVE_POSIX_FADVISE
1628 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1629 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1630 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1631 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1635 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1637 if (S_ISFIFO (statbuf.st_mode)) {
1638 handle_type = WAPI_HANDLE_PIPE;
1639 } else if (S_ISCHR (statbuf.st_mode)) {
1640 handle_type = WAPI_HANDLE_CONSOLE;
1642 handle_type = WAPI_HANDLE_FILE;
1645 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1646 if (handle == _WAPI_HANDLE_INVALID) {
1647 g_warning ("%s: error creating file handle", __func__);
1651 SetLastError (ERROR_GEN_FAILURE);
1652 return(INVALID_HANDLE_VALUE);
1655 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p", __func__, handle);
1662 * @name: a pointer to a NULL-terminated unicode string, that names
1663 * the file to be deleted.
1665 * Deletes file @name.
1667 * Return value: %TRUE on success, %FALSE otherwise.
1669 gboolean DeleteFile(const gunichar2 *name)
1673 gboolean ret = FALSE;
1676 struct stat statbuf;
1677 struct _WapiFileShare *shareinfo;
1681 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1683 SetLastError (ERROR_INVALID_NAME);
1687 filename=mono_unicode_to_external(name);
1688 if(filename==NULL) {
1689 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1691 SetLastError (ERROR_INVALID_NAME);
1695 attrs = GetFileAttributes (name);
1696 if (attrs == INVALID_FILE_ATTRIBUTES) {
1697 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file attributes error", __func__);
1698 /* Error set by GetFileAttributes() */
1704 /* Check to make sure sharing allows us to open the file for
1705 * writing. See bug 323389.
1707 * Do the checks that don't need an open file descriptor, for
1708 * simplicity's sake. If we really have to do the full checks
1709 * then we can implement that later.
1711 if (_wapi_stat (filename, &statbuf) < 0) {
1712 _wapi_set_last_path_error_from_errno (NULL, filename);
1717 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1718 &shareinfo) == FALSE) {
1719 SetLastError (ERROR_SHARING_VIOLATION);
1724 _wapi_handle_share_release (shareinfo);
1727 retval = _wapi_unlink (filename);
1730 _wapi_set_last_path_error_from_errno (NULL, filename);
1742 * @name: a pointer to a NULL-terminated unicode string, that names
1743 * the file to be moved.
1744 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1745 * new name for the file.
1747 * Renames file @name to @dest_name.
1748 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1749 * when it is the same file as the source. In that case it silently succeeds.
1751 * Return value: %TRUE on success, %FALSE otherwise.
1753 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1755 gchar *utf8_name, *utf8_dest_name;
1756 int result, errno_copy;
1757 struct stat stat_src, stat_dest;
1758 gboolean ret = FALSE;
1759 struct _WapiFileShare *shareinfo;
1762 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1764 SetLastError (ERROR_INVALID_NAME);
1768 utf8_name = mono_unicode_to_external (name);
1769 if (utf8_name == NULL) {
1770 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1772 SetLastError (ERROR_INVALID_NAME);
1776 if(dest_name==NULL) {
1777 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1780 SetLastError (ERROR_INVALID_NAME);
1784 utf8_dest_name = mono_unicode_to_external (dest_name);
1785 if (utf8_dest_name == NULL) {
1786 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1789 SetLastError (ERROR_INVALID_NAME);
1794 * In C# land we check for the existence of src, but not for dest.
1795 * We check it here and return the failure if dest exists and is not
1796 * the same file as src.
1798 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1799 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1800 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1802 g_free (utf8_dest_name);
1807 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1808 if (stat_dest.st_dev != stat_src.st_dev ||
1809 stat_dest.st_ino != stat_src.st_ino) {
1811 g_free (utf8_dest_name);
1812 SetLastError (ERROR_ALREADY_EXISTS);
1817 /* Check to make that we have delete sharing permission.
1818 * See https://bugzilla.xamarin.com/show_bug.cgi?id=17009
1820 * Do the checks that don't need an open file descriptor, for
1821 * simplicity's sake. If we really have to do the full checks
1822 * then we can implement that later.
1824 if (share_allows_delete (&stat_src, &shareinfo) == FALSE) {
1825 SetLastError (ERROR_SHARING_VIOLATION);
1829 _wapi_handle_share_release (shareinfo);
1831 result = _wapi_rename (utf8_name, utf8_dest_name);
1835 switch(errno_copy) {
1837 SetLastError (ERROR_ALREADY_EXISTS);
1841 /* Ignore here, it is dealt with below */
1845 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1850 g_free (utf8_dest_name);
1852 if (result != 0 && errno_copy == EXDEV) {
1853 if (S_ISDIR (stat_src.st_mode)) {
1854 SetLastError (ERROR_NOT_SAME_DEVICE);
1857 /* Try a copy to the new location, and delete the source */
1858 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1859 /* CopyFile will set the error */
1863 return(DeleteFile (name));
1874 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1878 int buf_size = st_src->st_blksize;
1880 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1881 buf = (char *) malloc (buf_size);
1884 remain = read (src_fd, buf, buf_size);
1886 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1890 _wapi_set_last_error_from_errno ();
1900 while (remain > 0) {
1901 if ((n = write (dest_fd, wbuf, remain)) < 0) {
1902 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1906 _wapi_set_last_error_from_errno ();
1907 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write failed.", __func__);
1923 * @name: a pointer to a NULL-terminated unicode string, that names
1924 * the file to be copied.
1925 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1926 * new name for the file.
1927 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1929 * Copies file @name to @dest_name
1931 * Return value: %TRUE on success, %FALSE otherwise.
1933 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1934 gboolean fail_if_exists)
1936 gchar *utf8_src, *utf8_dest;
1937 int src_fd, dest_fd;
1938 struct stat st, dest_st;
1939 struct utimbuf dest_time;
1940 gboolean ret = TRUE;
1944 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1946 SetLastError (ERROR_INVALID_NAME);
1950 utf8_src = mono_unicode_to_external (name);
1951 if (utf8_src == NULL) {
1952 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of source returned NULL",
1955 SetLastError (ERROR_INVALID_PARAMETER);
1959 if(dest_name==NULL) {
1960 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: dest is NULL", __func__);
1963 SetLastError (ERROR_INVALID_NAME);
1967 utf8_dest = mono_unicode_to_external (dest_name);
1968 if (utf8_dest == NULL) {
1969 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of dest returned NULL",
1972 SetLastError (ERROR_INVALID_PARAMETER);
1979 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
1981 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
1989 if (fstat (src_fd, &st) < 0) {
1990 _wapi_set_last_error_from_errno ();
1999 /* Before trying to open/create the dest, we need to report a 'file busy'
2000 * error if src and dest are actually the same file. We do the check here to take
2001 * advantage of the IOMAP capability */
2002 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
2003 st.st_ino == dest_st.st_ino) {
2009 SetLastError (ERROR_SHARING_VIOLATION);
2013 if (fail_if_exists) {
2014 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2016 /* FIXME: it kinda sucks that this code path potentially scans
2017 * the directory twice due to the weird SetLastError()
2019 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2021 /* The file does not exist, try creating it */
2022 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2024 /* Apparently this error is set if we
2025 * overwrite the dest file
2027 SetLastError (ERROR_ALREADY_EXISTS);
2031 _wapi_set_last_error_from_errno ();
2040 if (!write_file (src_fd, dest_fd, &st, TRUE))
2046 dest_time.modtime = st.st_mtime;
2047 dest_time.actime = st.st_atime;
2048 ret_utime = utime (utf8_dest, &dest_time);
2049 if (ret_utime == -1)
2050 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file [%s] utime failed: %s", __func__, utf8_dest, strerror(errno));
2059 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2064 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: %s is NULL", __func__, arg_name);
2065 SetLastError (ERROR_INVALID_NAME);
2069 utf8_ret = mono_unicode_to_external (arg);
2070 if (utf8_ret == NULL) {
2071 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of %s returned NULL",
2072 __func__, arg_name);
2073 SetLastError (ERROR_INVALID_PARAMETER);
2081 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2082 const gunichar2 *backupFileName, guint32 replaceFlags,
2083 gpointer exclude, gpointer reserved)
2085 int result, backup_fd = -1,replaced_fd = -1;
2086 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2087 struct stat stBackup;
2088 gboolean ret = FALSE;
2090 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2092 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2093 goto replace_cleanup;
2094 if (backupFileName != NULL) {
2095 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2096 goto replace_cleanup;
2099 if (utf8_backupFileName) {
2100 // Open the backup file for read so we can restore the file if an error occurs.
2101 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2102 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2104 goto replace_cleanup;
2107 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2109 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2110 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2111 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2112 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2115 if (replaced_fd == -1)
2116 goto replace_cleanup;
2118 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2121 goto replace_cleanup;
2127 g_free (utf8_replacedFileName);
2128 g_free (utf8_replacementFileName);
2129 g_free (utf8_backupFileName);
2130 if (backup_fd != -1)
2132 if (replaced_fd != -1)
2133 close (replaced_fd);
2139 * @stdhandle: specifies the file descriptor
2141 * Returns a handle for stdin, stdout, or stderr. Always returns the
2142 * same handle for the same @stdhandle.
2144 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2147 static mono_mutex_t stdhandle_mutex;
2149 gpointer GetStdHandle(WapiStdHandle stdhandle)
2151 struct _WapiHandle_file *file_handle;
2158 case STD_INPUT_HANDLE:
2163 case STD_OUTPUT_HANDLE:
2168 case STD_ERROR_HANDLE:
2174 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unknown standard handle type", __func__);
2176 SetLastError (ERROR_INVALID_PARAMETER);
2177 return(INVALID_HANDLE_VALUE);
2180 handle = GINT_TO_POINTER (fd);
2182 thr_ret = mono_os_mutex_lock (&stdhandle_mutex);
2183 g_assert (thr_ret == 0);
2185 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2186 (gpointer *)&file_handle);
2188 /* Need to create this console handle */
2189 handle = _wapi_stdhandle_create (fd, name);
2191 if (handle == INVALID_HANDLE_VALUE) {
2192 SetLastError (ERROR_NO_MORE_FILES);
2196 /* Add a reference to this handle */
2197 _wapi_handle_ref (handle);
2201 thr_ret = mono_os_mutex_unlock (&stdhandle_mutex);
2202 g_assert (thr_ret == 0);
2209 * @handle: The file handle to read from. The handle must have
2210 * %GENERIC_READ access.
2211 * @buffer: The buffer to store read data in
2212 * @numbytes: The maximum number of bytes to read
2213 * @bytesread: The actual number of bytes read is stored here. This
2214 * value can be zero if the handle is positioned at the end of the
2216 * @overlapped: points to a required %WapiOverlapped structure if
2217 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2220 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2221 * function reads up to @numbytes bytes from the file from the current
2222 * file position, and stores them in @buffer. If there are not enough
2223 * bytes left in the file, just the amount available will be read.
2224 * The actual number of bytes read is stored in @bytesread.
2226 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2227 * file position is ignored and the read position is taken from data
2228 * in the @overlapped structure.
2230 * Return value: %TRUE if the read succeeds (even if no bytes were
2231 * read due to an attempt to read past the end of the file), %FALSE on
2234 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2235 guint32 *bytesread, WapiOverlapped *overlapped)
2237 WapiHandleType type;
2239 type = _wapi_handle_type (handle);
2241 if(io_ops[type].readfile==NULL) {
2242 SetLastError (ERROR_INVALID_HANDLE);
2246 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2252 * @handle: The file handle to write to. The handle must have
2253 * %GENERIC_WRITE access.
2254 * @buffer: The buffer to read data from.
2255 * @numbytes: The maximum number of bytes to write.
2256 * @byteswritten: The actual number of bytes written is stored here.
2257 * If the handle is positioned at the file end, the length of the file
2258 * is extended. This parameter may be %NULL.
2259 * @overlapped: points to a required %WapiOverlapped structure if
2260 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2263 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2264 * function writes up to @numbytes bytes from @buffer to the file at
2265 * the current file position. If @handle is positioned at the end of
2266 * the file, the file is extended. The actual number of bytes written
2267 * is stored in @byteswritten.
2269 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2270 * file position is ignored and the write position is taken from data
2271 * in the @overlapped structure.
2273 * Return value: %TRUE if the write succeeds, %FALSE on error.
2275 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2276 guint32 *byteswritten, WapiOverlapped *overlapped)
2278 WapiHandleType type;
2280 type = _wapi_handle_type (handle);
2282 if(io_ops[type].writefile==NULL) {
2283 SetLastError (ERROR_INVALID_HANDLE);
2287 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2293 * @handle: Handle to open file. The handle must have
2294 * %GENERIC_WRITE access.
2296 * Flushes buffers of the file and causes all unwritten data to
2299 * Return value: %TRUE on success, %FALSE otherwise.
2301 gboolean FlushFileBuffers(gpointer handle)
2303 WapiHandleType type;
2305 type = _wapi_handle_type (handle);
2307 if(io_ops[type].flushfile==NULL) {
2308 SetLastError (ERROR_INVALID_HANDLE);
2312 return(io_ops[type].flushfile (handle));
2317 * @handle: The file handle to set. The handle must have
2318 * %GENERIC_WRITE access.
2320 * Moves the end-of-file position to the current position of the file
2321 * pointer. This function is used to truncate or extend a file.
2323 * Return value: %TRUE on success, %FALSE otherwise.
2325 gboolean SetEndOfFile(gpointer handle)
2327 WapiHandleType type;
2329 type = _wapi_handle_type (handle);
2331 if (io_ops[type].setendoffile == NULL) {
2332 SetLastError (ERROR_INVALID_HANDLE);
2336 return(io_ops[type].setendoffile (handle));
2341 * @handle: The file handle to set. The handle must have
2342 * %GENERIC_READ or %GENERIC_WRITE access.
2343 * @movedistance: Low 32 bits of a signed value that specifies the
2344 * number of bytes to move the file pointer.
2345 * @highmovedistance: Pointer to the high 32 bits of a signed value
2346 * that specifies the number of bytes to move the file pointer, or
2348 * @method: The starting point for the file pointer move.
2350 * Sets the file pointer of an open file.
2352 * The distance to move the file pointer is calculated from
2353 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2354 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2355 * is the low 32 bits and @highmovedistance a pointer to the high 32
2356 * bits of a 64 bit signed value. A positive distance moves the file
2357 * pointer forward from the position specified by @method; a negative
2358 * distance moves the file pointer backward.
2360 * If the library is compiled without large file support,
2361 * @highmovedistance is ignored and its value is set to zero on a
2362 * successful return.
2364 * Return value: On success, the low 32 bits of the new file pointer.
2365 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2366 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2368 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2369 gint32 *highmovedistance, WapiSeekMethod method)
2371 WapiHandleType type;
2373 type = _wapi_handle_type (handle);
2375 if (io_ops[type].seek == NULL) {
2376 SetLastError (ERROR_INVALID_HANDLE);
2377 return(INVALID_SET_FILE_POINTER);
2380 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2386 * @handle: The file handle to test.
2388 * Finds the type of file @handle.
2390 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2391 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2392 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2393 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2395 WapiFileType GetFileType(gpointer handle)
2397 WapiHandleType type;
2399 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2400 SetLastError (ERROR_INVALID_HANDLE);
2401 return(FILE_TYPE_UNKNOWN);
2404 type = _wapi_handle_type (handle);
2406 if (io_ops[type].getfiletype == NULL) {
2407 SetLastError (ERROR_INVALID_HANDLE);
2408 return(FILE_TYPE_UNKNOWN);
2411 return(io_ops[type].getfiletype ());
2416 * @handle: The file handle to query. The handle must have
2417 * %GENERIC_READ or %GENERIC_WRITE access.
2418 * @highsize: If non-%NULL, the high 32 bits of the file size are
2421 * Retrieves the size of the file @handle.
2423 * If the library is compiled without large file support, @highsize
2424 * has its value set to zero on a successful return.
2426 * Return value: On success, the low 32 bits of the file size. If
2427 * @highsize is non-%NULL then the high 32 bits of the file size are
2428 * stored here. On failure %INVALID_FILE_SIZE is returned.
2430 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2432 WapiHandleType type;
2434 type = _wapi_handle_type (handle);
2436 if (io_ops[type].getfilesize == NULL) {
2437 SetLastError (ERROR_INVALID_HANDLE);
2438 return(INVALID_FILE_SIZE);
2441 return(io_ops[type].getfilesize (handle, highsize));
2446 * @handle: The file handle to query. The handle must have
2447 * %GENERIC_READ access.
2448 * @create_time: Points to a %WapiFileTime structure to receive the
2449 * number of ticks since the epoch that file was created. May be
2451 * @last_access: Points to a %WapiFileTime structure to receive the
2452 * number of ticks since the epoch when file was last accessed. May be
2454 * @last_write: Points to a %WapiFileTime structure to receive the
2455 * number of ticks since the epoch when file was last written to. May
2458 * Finds the number of ticks since the epoch that the file referenced
2459 * by @handle was created, last accessed and last modified. A tick is
2460 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2463 * Create time isn't recorded on POSIX file systems or reported by
2464 * stat(2), so that time is guessed by returning the oldest of the
2467 * Return value: %TRUE on success, %FALSE otherwise.
2469 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2470 WapiFileTime *last_access, WapiFileTime *last_write)
2472 WapiHandleType type;
2474 type = _wapi_handle_type (handle);
2476 if (io_ops[type].getfiletime == NULL) {
2477 SetLastError (ERROR_INVALID_HANDLE);
2481 return(io_ops[type].getfiletime (handle, create_time, last_access,
2487 * @handle: The file handle to set. The handle must have
2488 * %GENERIC_WRITE access.
2489 * @create_time: Points to a %WapiFileTime structure that contains the
2490 * number of ticks since the epoch that the file was created. May be
2492 * @last_access: Points to a %WapiFileTime structure that contains the
2493 * number of ticks since the epoch when the file was last accessed.
2495 * @last_write: Points to a %WapiFileTime structure that contains the
2496 * number of ticks since the epoch when the file was last written to.
2499 * Sets the number of ticks since the epoch that the file referenced
2500 * by @handle was created, last accessed or last modified. A tick is
2501 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2504 * Create time isn't recorded on POSIX file systems, and is ignored.
2506 * Return value: %TRUE on success, %FALSE otherwise.
2508 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2509 const WapiFileTime *last_access,
2510 const WapiFileTime *last_write)
2512 WapiHandleType type;
2514 type = _wapi_handle_type (handle);
2516 if (io_ops[type].setfiletime == NULL) {
2517 SetLastError (ERROR_INVALID_HANDLE);
2521 return(io_ops[type].setfiletime (handle, create_time, last_access,
2525 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2526 * January 1 1601 GMT
2529 #define TICKS_PER_MILLISECOND 10000L
2530 #define TICKS_PER_SECOND 10000000L
2531 #define TICKS_PER_MINUTE 600000000L
2532 #define TICKS_PER_HOUR 36000000000LL
2533 #define TICKS_PER_DAY 864000000000LL
2535 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2537 static const guint16 mon_yday[2][13]={
2538 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2539 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2543 * FileTimeToSystemTime:
2544 * @file_time: Points to a %WapiFileTime structure that contains the
2545 * number of ticks to convert.
2546 * @system_time: Points to a %WapiSystemTime structure to receive the
2549 * Converts a tick count into broken-out time values.
2551 * Return value: %TRUE on success, %FALSE otherwise.
2553 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2554 WapiSystemTime *system_time)
2556 gint64 file_ticks, totaldays, rem, y;
2559 if(system_time==NULL) {
2560 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: system_time NULL", __func__);
2562 SetLastError (ERROR_INVALID_PARAMETER);
2566 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2567 file_time->dwLowDateTime;
2569 /* Really compares if file_ticks>=0x8000000000000000
2570 * (LLONG_MAX+1) but we're working with a signed value for the
2571 * year and day calculation to work later
2574 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file_time too big", __func__);
2576 SetLastError (ERROR_INVALID_PARAMETER);
2580 totaldays=(file_ticks / TICKS_PER_DAY);
2581 rem = file_ticks % TICKS_PER_DAY;
2582 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2584 system_time->wHour=rem/TICKS_PER_HOUR;
2585 rem %= TICKS_PER_HOUR;
2586 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2588 system_time->wMinute = rem / TICKS_PER_MINUTE;
2589 rem %= TICKS_PER_MINUTE;
2590 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2593 system_time->wSecond = rem / TICKS_PER_SECOND;
2594 rem %= TICKS_PER_SECOND;
2595 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2598 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2599 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Milliseconds: %d", __func__,
2600 system_time->wMilliseconds);
2602 /* January 1, 1601 was a Monday, according to Emacs calendar */
2603 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2604 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2606 /* This algorithm to find year and month given days from epoch
2611 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2612 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2614 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2615 /* Guess a corrected year, assuming 365 days per year */
2616 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2617 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld yg: %lld y: %lld", __func__,
2620 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2621 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2623 /* Adjust days and y to match the guessed year. */
2624 totaldays -= ((yg - y) * 365
2625 + LEAPS_THRU_END_OF (yg - 1)
2626 - LEAPS_THRU_END_OF (y - 1));
2627 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2629 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: y: %lld", __func__, y);
2632 system_time->wYear = y;
2633 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Year: %d", __func__, system_time->wYear);
2635 ip = mon_yday[isleap(y)];
2637 for(y=11; totaldays < ip[y]; --y) {
2641 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2643 system_time->wMonth = y + 1;
2644 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Month: %d", __func__, system_time->wMonth);
2646 system_time->wDay = totaldays + 1;
2647 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day: %d", __func__, system_time->wDay);
2652 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2654 struct _WapiHandle_find find_handle = {0};
2656 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2659 if (pattern == NULL) {
2660 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: pattern is NULL", __func__);
2662 SetLastError (ERROR_PATH_NOT_FOUND);
2663 return(INVALID_HANDLE_VALUE);
2666 utf8_pattern = mono_unicode_to_external (pattern);
2667 if (utf8_pattern == NULL) {
2668 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2670 SetLastError (ERROR_INVALID_NAME);
2671 return(INVALID_HANDLE_VALUE);
2674 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for [%s]", __func__, utf8_pattern);
2676 /* Figure out which bit of the pattern is the directory */
2677 dir_part = _wapi_dirname (utf8_pattern);
2678 entry_part = _wapi_basename (utf8_pattern);
2681 /* Don't do this check for now, it breaks if directories
2682 * really do have metachars in their names (see bug 58116).
2683 * FIXME: Figure out a better solution to keep some checks...
2685 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2686 SetLastError (ERROR_INVALID_NAME);
2688 g_free (entry_part);
2689 g_free (utf8_pattern);
2690 return(INVALID_HANDLE_VALUE);
2694 /* The pattern can specify a directory or a set of files.
2696 * The pattern can have wildcard characters ? and *, but only
2697 * in the section after the last directory delimiter. (Return
2698 * ERROR_INVALID_NAME if there are wildcards in earlier path
2699 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2700 * means "match one character", "??" seems to mean "match one
2701 * or two characters", "???" seems to mean "match one, two or
2702 * three characters", etc. Windows will also try and match
2703 * the mangled "short name" of files, so 8 character patterns
2704 * with wildcards will show some surprising results.
2706 * All the written documentation I can find says that '?'
2707 * should only match one character, and doesn't mention '??',
2708 * '???' etc. I'm going to assume that the strict behaviour
2709 * (ie '???' means three and only three characters) is the
2710 * correct one, because that lets me use fnmatch(3) rather
2711 * than mess around with regexes.
2714 find_handle.namelist = NULL;
2715 result = _wapi_io_scandir (dir_part, entry_part,
2716 &find_handle.namelist);
2719 /* No files, which windows seems to call
2722 SetLastError (ERROR_FILE_NOT_FOUND);
2723 g_free (utf8_pattern);
2724 g_free (entry_part);
2726 return (INVALID_HANDLE_VALUE);
2730 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2731 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: scandir error: %s", __func__, g_strerror (errno));
2732 g_free (utf8_pattern);
2733 g_free (entry_part);
2735 return (INVALID_HANDLE_VALUE);
2738 g_free (utf8_pattern);
2739 g_free (entry_part);
2741 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Got %d matches", __func__, result);
2743 find_handle.dir_part = dir_part;
2744 find_handle.num = result;
2745 find_handle.count = 0;
2747 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2748 if (handle == _WAPI_HANDLE_INVALID) {
2749 g_warning ("%s: error creating find handle", __func__);
2751 g_free (entry_part);
2752 g_free (utf8_pattern);
2753 SetLastError (ERROR_GEN_FAILURE);
2755 return(INVALID_HANDLE_VALUE);
2758 if (handle != INVALID_HANDLE_VALUE &&
2759 !FindNextFile (handle, find_data)) {
2761 SetLastError (ERROR_NO_MORE_FILES);
2762 handle = INVALID_HANDLE_VALUE;
2768 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2770 struct _WapiHandle_find *find_handle;
2772 struct stat buf, linkbuf;
2775 gchar *utf8_filename, *utf8_basename;
2776 gunichar2 *utf16_basename;
2780 gboolean ret = FALSE;
2782 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2783 (gpointer *)&find_handle);
2785 g_warning ("%s: error looking up find handle %p", __func__,
2787 SetLastError (ERROR_INVALID_HANDLE);
2791 thr_ret = _wapi_handle_lock_handle (handle);
2792 g_assert (thr_ret == 0);
2795 if (find_handle->count >= find_handle->num) {
2796 SetLastError (ERROR_NO_MORE_FILES);
2800 /* stat next match */
2802 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2804 result = _wapi_stat (filename, &buf);
2805 if (result == -1 && errno == ENOENT) {
2806 /* Might be a dangling symlink */
2807 result = _wapi_lstat (filename, &buf);
2811 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: stat failed: %s", __func__, filename);
2817 #ifndef __native_client__
2818 result = _wapi_lstat (filename, &linkbuf);
2820 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lstat failed: %s", __func__, filename);
2827 utf8_filename = mono_utf8_from_external (filename);
2828 if (utf8_filename == NULL) {
2829 /* We couldn't turn this filename into utf8 (eg the
2830 * encoding of the name wasn't convertible), so just
2833 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2840 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Found [%s]", __func__, utf8_filename);
2842 /* fill data block */
2844 if (buf.st_mtime < buf.st_ctime)
2845 create_time = buf.st_mtime;
2847 create_time = buf.st_ctime;
2849 #ifdef __native_client__
2850 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, NULL);
2852 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2855 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2856 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2857 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2859 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2860 find_data->nFileSizeHigh = 0;
2861 find_data->nFileSizeLow = 0;
2863 find_data->nFileSizeHigh = buf.st_size >> 32;
2864 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2867 find_data->dwReserved0 = 0;
2868 find_data->dwReserved1 = 0;
2870 utf8_basename = _wapi_basename (utf8_filename);
2871 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2873 if(utf16_basename==NULL) {
2874 g_free (utf8_basename);
2875 g_free (utf8_filename);
2880 /* utf16 is 2 * utf8 */
2883 memset (find_data->cFileName, '\0', (MAX_PATH*2));
2885 /* Truncating a utf16 string like this might leave the last
2888 memcpy (find_data->cFileName, utf16_basename,
2889 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
2891 find_data->cAlternateFileName [0] = 0; /* not used */
2893 g_free (utf8_basename);
2894 g_free (utf8_filename);
2895 g_free (utf16_basename);
2898 thr_ret = _wapi_handle_unlock_handle (handle);
2899 g_assert (thr_ret == 0);
2906 * @wapi_handle: the find handle to close.
2908 * Closes find handle @wapi_handle
2910 * Return value: %TRUE on success, %FALSE otherwise.
2912 gboolean FindClose (gpointer handle)
2914 struct _WapiHandle_find *find_handle;
2918 if (handle == NULL) {
2919 SetLastError (ERROR_INVALID_HANDLE);
2923 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2924 (gpointer *)&find_handle);
2926 g_warning ("%s: error looking up find handle %p", __func__,
2928 SetLastError (ERROR_INVALID_HANDLE);
2932 thr_ret = _wapi_handle_lock_handle (handle);
2933 g_assert (thr_ret == 0);
2935 g_strfreev (find_handle->namelist);
2936 g_free (find_handle->dir_part);
2938 thr_ret = _wapi_handle_unlock_handle (handle);
2939 g_assert (thr_ret == 0);
2941 _wapi_handle_unref (handle);
2948 * @name: a pointer to a NULL-terminated unicode string, that names
2949 * the directory to be created.
2950 * @security: ignored for now
2952 * Creates directory @name
2954 * Return value: %TRUE on success, %FALSE otherwise.
2956 gboolean CreateDirectory (const gunichar2 *name,
2957 WapiSecurityAttributes *security)
2963 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2965 SetLastError (ERROR_INVALID_NAME);
2969 utf8_name = mono_unicode_to_external (name);
2970 if (utf8_name == NULL) {
2971 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2973 SetLastError (ERROR_INVALID_NAME);
2977 result = _wapi_mkdir (utf8_name, 0777);
2984 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2991 * @name: a pointer to a NULL-terminated unicode string, that names
2992 * the directory to be removed.
2994 * Removes directory @name
2996 * Return value: %TRUE on success, %FALSE otherwise.
2998 gboolean RemoveDirectory (const gunichar2 *name)
3004 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3006 SetLastError (ERROR_INVALID_NAME);
3010 utf8_name = mono_unicode_to_external (name);
3011 if (utf8_name == NULL) {
3012 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3014 SetLastError (ERROR_INVALID_NAME);
3018 result = _wapi_rmdir (utf8_name);
3020 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3031 * GetFileAttributes:
3032 * @name: a pointer to a NULL-terminated unicode filename.
3034 * Gets the attributes for @name;
3036 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3038 guint32 GetFileAttributes (const gunichar2 *name)
3041 struct stat buf, linkbuf;
3046 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3048 SetLastError (ERROR_INVALID_NAME);
3052 utf8_name = mono_unicode_to_external (name);
3053 if (utf8_name == NULL) {
3054 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3056 SetLastError (ERROR_INVALID_PARAMETER);
3057 return (INVALID_FILE_ATTRIBUTES);
3060 result = _wapi_stat (utf8_name, &buf);
3061 if (result == -1 && errno == ENOENT) {
3062 /* Might be a dangling symlink... */
3063 result = _wapi_lstat (utf8_name, &buf);
3067 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3069 return (INVALID_FILE_ATTRIBUTES);
3072 #ifndef __native_client__
3073 result = _wapi_lstat (utf8_name, &linkbuf);
3075 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3077 return (INVALID_FILE_ATTRIBUTES);
3081 #ifdef __native_client__
3082 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, NULL);
3084 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3093 * GetFileAttributesEx:
3094 * @name: a pointer to a NULL-terminated unicode filename.
3095 * @level: must be GetFileExInfoStandard
3096 * @info: pointer to a WapiFileAttributesData structure
3098 * Gets attributes, size and filetimes for @name;
3100 * Return value: %TRUE on success, %FALSE on failure
3102 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3105 WapiFileAttributesData *data;
3107 struct stat buf, linkbuf;
3111 if (level != GetFileExInfoStandard) {
3112 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: info level %d not supported.", __func__,
3115 SetLastError (ERROR_INVALID_PARAMETER);
3120 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3122 SetLastError (ERROR_INVALID_NAME);
3126 utf8_name = mono_unicode_to_external (name);
3127 if (utf8_name == NULL) {
3128 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3130 SetLastError (ERROR_INVALID_PARAMETER);
3134 result = _wapi_stat (utf8_name, &buf);
3135 if (result == -1 && errno == ENOENT) {
3136 /* Might be a dangling symlink... */
3137 result = _wapi_lstat (utf8_name, &buf);
3141 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3146 result = _wapi_lstat (utf8_name, &linkbuf);
3148 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3153 /* fill data block */
3155 data = (WapiFileAttributesData *)info;
3157 if (buf.st_mtime < buf.st_ctime)
3158 create_time = buf.st_mtime;
3160 create_time = buf.st_ctime;
3162 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3168 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3169 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3170 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3172 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3173 data->nFileSizeHigh = 0;
3174 data->nFileSizeLow = 0;
3177 data->nFileSizeHigh = buf.st_size >> 32;
3178 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3186 * @name: name of file
3187 * @attrs: attributes to set
3189 * Changes the attributes on a named file.
3191 * Return value: %TRUE on success, %FALSE on failure.
3193 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3195 /* FIXME: think of something clever to do on unix */
3201 * Currently we only handle one *internal* case, with a value that is
3202 * not standard: 0x80000000, which means `set executable bit'
3206 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3208 SetLastError (ERROR_INVALID_NAME);
3212 utf8_name = mono_unicode_to_external (name);
3213 if (utf8_name == NULL) {
3214 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3216 SetLastError (ERROR_INVALID_NAME);
3220 result = _wapi_stat (utf8_name, &buf);
3221 if (result == -1 && errno == ENOENT) {
3222 /* Might be a dangling symlink... */
3223 result = _wapi_lstat (utf8_name, &buf);
3227 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3232 /* Contrary to the documentation, ms allows NORMAL to be
3233 * specified along with other attributes, so dont bother to
3234 * catch that case here.
3236 if (attrs & FILE_ATTRIBUTE_READONLY) {
3237 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWUSR | S_IWOTH | S_IWGRP));
3239 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWUSR);
3242 /* Ignore the other attributes for now */
3244 if (attrs & 0x80000000){
3245 mode_t exec_mask = 0;
3247 if ((buf.st_mode & S_IRUSR) != 0)
3248 exec_mask |= S_IXUSR;
3250 if ((buf.st_mode & S_IRGRP) != 0)
3251 exec_mask |= S_IXGRP;
3253 if ((buf.st_mode & S_IROTH) != 0)
3254 exec_mask |= S_IXOTH;
3256 result = chmod (utf8_name, buf.st_mode | exec_mask);
3258 /* Don't bother to reset executable (might need to change this
3268 * GetCurrentDirectory
3269 * @length: size of the buffer
3270 * @buffer: pointer to buffer that recieves path
3272 * Retrieves the current directory for the current process.
3274 * Return value: number of characters in buffer on success, zero on failure
3276 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3278 gunichar2 *utf16_path;
3282 #ifdef __native_client__
3283 gchar *path = g_get_current_dir ();
3284 if (length < strlen(path) + 1 || path == NULL)
3286 memcpy (buffer, path, strlen(path) + 1);
3288 if (getcwd ((char*)buffer, length) == NULL) {
3289 if (errno == ERANGE) { /*buffer length is not big enough */
3290 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*/
3293 utf16_path = mono_unicode_from_external (path, &bytes);
3294 g_free (utf16_path);
3298 _wapi_set_last_error_from_errno ();
3303 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3304 count = (bytes/2)+1;
3305 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3307 /* Add the terminator */
3308 memset (buffer, '\0', bytes+2);
3309 memcpy (buffer, utf16_path, bytes);
3311 g_free (utf16_path);
3317 * SetCurrentDirectory
3318 * @path: path to new directory
3320 * Changes the directory path for the current process.
3322 * Return value: %TRUE on success, %FALSE on failure.
3324 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3330 SetLastError (ERROR_INVALID_PARAMETER);
3334 utf8_path = mono_unicode_to_external (path);
3335 if (_wapi_chdir (utf8_path) != 0) {
3336 _wapi_set_last_error_from_errno ();
3346 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3347 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3349 struct _WapiHandle_file pipe_read_handle = {0};
3350 struct _WapiHandle_file pipe_write_handle = {0};
3351 gpointer read_handle;
3352 gpointer write_handle;
3356 mono_once (&io_ops_once, io_ops_init);
3358 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Creating pipe", __func__);
3362 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error creating pipe: %s", __func__,
3365 _wapi_set_last_error_from_errno ();
3369 if (filedes[0] >= _wapi_fd_reserve ||
3370 filedes[1] >= _wapi_fd_reserve) {
3371 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
3373 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3381 /* filedes[0] is open for reading, filedes[1] for writing */
3383 pipe_read_handle.fd = filedes [0];
3384 pipe_read_handle.fileaccess = GENERIC_READ;
3385 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3387 if (read_handle == _WAPI_HANDLE_INVALID) {
3388 g_warning ("%s: error creating pipe read handle", __func__);
3391 SetLastError (ERROR_GEN_FAILURE);
3396 pipe_write_handle.fd = filedes [1];
3397 pipe_write_handle.fileaccess = GENERIC_WRITE;
3398 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3399 &pipe_write_handle);
3400 if (write_handle == _WAPI_HANDLE_INVALID) {
3401 g_warning ("%s: error creating pipe write handle", __func__);
3402 _wapi_handle_unref (read_handle);
3406 SetLastError (ERROR_GEN_FAILURE);
3411 *readpipe = read_handle;
3412 *writepipe = write_handle;
3414 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning pipe: read handle %p, write handle %p",
3415 __func__, read_handle, write_handle);
3420 #ifdef HAVE_GETFSSTAT
3421 /* Darwin has getfsstat */
3422 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3424 struct statfs *stats;
3427 glong length, total = 0;
3429 n = getfsstat (NULL, 0, MNT_NOWAIT);
3432 size = n * sizeof (struct statfs);
3433 stats = (struct statfs *) g_malloc (size);
3436 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3440 for (i = 0; i < n; i++){
3441 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3442 if (total + length < len){
3443 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3444 buf [total+length] = 0;
3447 total += length + 1;
3456 /* In-place octal sequence replacement */
3458 unescape_octal (gchar *str)
3467 while (*rptr != '\0') {
3468 if (*rptr == '\\') {
3471 c = (*(rptr++) - '0') << 6;
3472 c += (*(rptr++) - '0') << 3;
3473 c += *(rptr++) - '0';
3475 } else if (wptr != rptr) {
3483 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3486 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3487 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3488 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3493 guint32 buffer_index;
3494 guint32 mountpoint_index;
3495 guint32 field_number;
3496 guint32 allocated_size;
3497 guint32 fsname_index;
3498 guint32 fstype_index;
3499 gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3500 gchar *mountpoint_allocated;
3501 gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3502 gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3503 gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3506 gboolean check_mount_source;
3507 } LinuxMountInfoParseState;
3509 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3510 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3511 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3512 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3514 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3518 LinuxMountInfoParseState state;
3519 gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3521 memset (buf, 0, len * sizeof (gunichar2));
3522 fd = open ("/proc/self/mountinfo", O_RDONLY);
3524 parser = GetLogicalDriveStrings_MountInfo;
3526 fd = open ("/proc/mounts", O_RDONLY);
3528 parser = GetLogicalDriveStrings_Mounts;
3532 ret = GetLogicalDriveStrings_Mtab (len, buf);
3536 memset (&state, 0, sizeof (LinuxMountInfoParseState));
3537 state.field_number = 1;
3538 state.delimiter = ' ';
3540 while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3541 state.buffer_index = 0;
3543 while ((*parser)(len, buf, &state)) {
3544 if (state.buffer [state.buffer_index] == '\n') {
3545 gboolean quit = add_drive_string (len, buf, &state);
3546 state.field_number = 1;
3547 state.buffer_index++;
3548 if (state.mountpoint_allocated) {
3549 g_free (state.mountpoint_allocated);
3550 state.mountpoint_allocated = NULL;
3567 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3571 if (state->field_number == 1)
3572 state->check_mount_source = TRUE;
3574 while (state->buffer_index < (guint32)state->nbytes) {
3575 if (state->buffer [state->buffer_index] == state->delimiter) {
3576 state->field_number++;
3577 switch (state->field_number) {
3579 state->mountpoint_index = 0;
3583 if (state->mountpoint_allocated)
3584 state->mountpoint_allocated [state->mountpoint_index] = 0;
3586 state->mountpoint [state->mountpoint_index] = 0;
3590 ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3592 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3594 state->buffer_index = state->nbytes;
3597 state->buffer_index++;
3599 } else if (state->buffer [state->buffer_index] == '\n')
3602 switch (state->field_number) {
3604 if (state->check_mount_source) {
3605 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3606 /* We can ignore the rest, it's a device
3608 state->check_mount_source = FALSE;
3609 state->fsname [state->fsname_index++] = '/';
3612 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3613 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3618 append_to_mountpoint (state);
3622 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3623 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3627 state->buffer_index++;
3633 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3635 while (state->buffer_index < (guint32)state->nbytes) {
3636 if (state->buffer [state->buffer_index] == state->delimiter) {
3637 state->field_number++;
3638 switch (state->field_number) {
3640 state->mountpoint_index = 0;
3644 if (state->mountpoint_allocated)
3645 state->mountpoint_allocated [state->mountpoint_index] = 0;
3647 state->mountpoint [state->mountpoint_index] = 0;
3651 state->delimiter = '-';
3655 state->delimiter = ' ';
3659 state->check_mount_source = TRUE;
3662 state->buffer_index++;
3664 } else if (state->buffer [state->buffer_index] == '\n')
3667 switch (state->field_number) {
3669 append_to_mountpoint (state);
3673 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3674 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3678 if (state->check_mount_source) {
3679 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3680 /* We can ignore the rest, it's a device
3682 state->check_mount_source = FALSE;
3683 state->fsname [state->fsname_index++] = '/';
3686 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3687 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3692 state->buffer_index++;
3699 append_to_mountpoint (LinuxMountInfoParseState *state)
3701 gchar ch = state->buffer [state->buffer_index];
3702 if (state->mountpoint_allocated) {
3703 if (state->mountpoint_index >= state->allocated_size) {
3704 guint32 newsize = (state->allocated_size << 1) + 1;
3705 gchar *newbuf = (gchar *)g_malloc0 (newsize * sizeof (gchar));
3707 memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3708 g_free (state->mountpoint_allocated);
3709 state->mountpoint_allocated = newbuf;
3710 state->allocated_size = newsize;
3712 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3714 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3715 state->allocated_size = (state->mountpoint_index << 1) + 1;
3716 state->mountpoint_allocated = (gchar *)g_malloc0 (state->allocated_size * sizeof (gchar));
3717 memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3718 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3720 state->mountpoint [state->mountpoint_index++] = ch;
3725 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3727 gboolean quit = FALSE;
3728 gboolean ignore_entry;
3730 if (state->fsname_index == 1 && state->fsname [0] == '/')
3731 ignore_entry = FALSE;
3732 else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0)
3733 ignore_entry = TRUE;
3734 else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3735 /* Ignore GNOME's gvfs */
3736 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3737 ignore_entry = TRUE;
3739 ignore_entry = FALSE;
3740 } else if (state->fstype_index == 3 && memcmp ("nfs", state->fstype, state->fstype_index) == 0)
3741 ignore_entry = FALSE;
3743 ignore_entry = TRUE;
3745 if (!ignore_entry) {
3748 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3750 unescape_octal (mountpoint);
3751 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3752 if (state->total + length + 1 > len) {
3754 state->total = len * 2;
3757 memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3758 state->total += length;
3762 state->fsname_index = 0;
3763 state->fstype_index = 0;
3769 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3771 return GetLogicalDriveStrings_Mtab (len, buf);
3775 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3778 gunichar2 *ptr, *dir;
3779 glong length, total = 0;
3783 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3788 /* Sigh, mntent and friends don't work well.
3789 * It stops on the first line that doesn't begin with a '/'.
3790 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3791 fp = fopen ("/etc/mtab", "rt");
3793 fp = fopen ("/etc/mnttab", "rt");
3799 while (fgets (buffer, 512, fp) != NULL) {
3803 splitted = g_strsplit (buffer, " ", 0);
3804 if (!*splitted || !*(splitted + 1)) {
3805 g_strfreev (splitted);
3809 unescape_octal (*(splitted + 1));
3810 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3811 g_strfreev (splitted);
3812 if (total + length + 1 > len) {
3815 return len * 2; /* guess */
3818 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3820 total += length + 1;
3825 /* Commented out, does not work with my mtab!!! - Gonz */
3826 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3830 gunichar2 *ptr, *dir;
3831 glong len, total = 0;
3834 fp = setmntent ("/etc/mtab", "rt");
3836 fp = setmntent ("/etc/mnttab", "rt");
3842 while ((mnt = getmntent (fp)) != NULL) {
3843 g_print ("GOT %s\n", mnt->mnt_dir);
3844 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3845 if (total + len + 1 > len) {
3846 return len * 2; /* guess */
3849 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3861 #if defined(HAVE_STATVFS) || defined(HAVE_STATFS)
3862 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3863 WapiULargeInteger *total_number_of_bytes,
3864 WapiULargeInteger *total_number_of_free_bytes)
3867 struct statvfs fsstat;
3868 #elif defined(HAVE_STATFS)
3869 struct statfs fsstat;
3871 gboolean isreadonly;
3872 gchar *utf8_path_name;
3874 unsigned long block_size;
3876 if (path_name == NULL) {
3877 utf8_path_name = g_strdup (g_get_current_dir());
3878 if (utf8_path_name == NULL) {
3879 SetLastError (ERROR_DIRECTORY);
3884 utf8_path_name = mono_unicode_to_external (path_name);
3885 if (utf8_path_name == NULL) {
3886 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3888 SetLastError (ERROR_INVALID_NAME);
3895 ret = statvfs (utf8_path_name, &fsstat);
3896 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
3897 block_size = fsstat.f_frsize;
3898 #elif defined(HAVE_STATFS)
3899 ret = statfs (utf8_path_name, &fsstat);
3900 #if defined (MNT_RDONLY)
3901 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
3902 #elif defined (MS_RDONLY)
3903 isreadonly = ((fsstat.f_flags & MS_RDONLY) == MS_RDONLY);
3905 block_size = fsstat.f_bsize;
3907 } while(ret == -1 && errno == EINTR);
3909 g_free(utf8_path_name);
3912 _wapi_set_last_error_from_errno ();
3913 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: statvfs failed: %s", __func__, strerror (errno));
3917 /* total number of free bytes for non-root */
3918 if (free_bytes_avail != NULL) {
3920 free_bytes_avail->QuadPart = 0;
3923 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
3927 /* total number of bytes available for non-root */
3928 if (total_number_of_bytes != NULL) {
3929 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
3932 /* total number of bytes available for root */
3933 if (total_number_of_free_bytes != NULL) {
3935 total_number_of_free_bytes->QuadPart = 0;
3938 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
3945 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3946 WapiULargeInteger *total_number_of_bytes,
3947 WapiULargeInteger *total_number_of_free_bytes)
3949 if (free_bytes_avail != NULL) {
3950 free_bytes_avail->QuadPart = (guint64) -1;
3953 if (total_number_of_bytes != NULL) {
3954 total_number_of_bytes->QuadPart = (guint64) -1;
3957 if (total_number_of_free_bytes != NULL) {
3958 total_number_of_free_bytes->QuadPart = (guint64) -1;
3966 * General Unix support
3971 const long fstypeid;
3973 const gchar* fstype;
3976 static _wapi_drive_type _wapi_drive_types[] = {
3978 { DRIVE_REMOTE, "afp" },
3979 { DRIVE_REMOTE, "autofs" },
3980 { DRIVE_CDROM, "cddafs" },
3981 { DRIVE_CDROM, "cd9660" },
3982 { DRIVE_RAMDISK, "devfs" },
3983 { DRIVE_FIXED, "exfat" },
3984 { DRIVE_RAMDISK, "fdesc" },
3985 { DRIVE_REMOTE, "ftp" },
3986 { DRIVE_FIXED, "hfs" },
3987 { DRIVE_FIXED, "msdos" },
3988 { DRIVE_REMOTE, "nfs" },
3989 { DRIVE_FIXED, "ntfs" },
3990 { DRIVE_REMOTE, "smbfs" },
3991 { DRIVE_FIXED, "udf" },
3992 { DRIVE_REMOTE, "webdav" },
3993 { DRIVE_UNKNOWN, NULL }
3995 { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
3996 { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
3997 { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
3998 { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
3999 { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
4000 { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
4001 { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
4002 { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
4003 { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
4004 { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
4005 { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
4006 { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
4007 { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
4008 { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
4009 { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
4010 { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
4011 { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
4012 { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4013 { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4014 { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4015 { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4016 { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4017 { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4018 { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4019 { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4020 { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4021 { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4022 { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4023 { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4024 { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4025 { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4026 { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4027 { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4028 { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4029 { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4030 { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4031 { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4032 { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4033 { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4034 { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4035 { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4036 { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4037 { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4038 { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4039 { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4040 { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4041 { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4042 { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4043 { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4044 { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4045 { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4046 { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4047 { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4048 { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4049 { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4050 { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4051 { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4052 { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4053 { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4054 { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4055 { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4056 { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4057 { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4058 { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4059 { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4060 { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4061 { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4062 { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4063 { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4064 { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4065 { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4066 { DRIVE_UNKNOWN, 0, NULL}
4068 { DRIVE_RAMDISK, "ramfs" },
4069 { DRIVE_RAMDISK, "tmpfs" },
4070 { DRIVE_RAMDISK, "proc" },
4071 { DRIVE_RAMDISK, "sysfs" },
4072 { DRIVE_RAMDISK, "debugfs" },
4073 { DRIVE_RAMDISK, "devpts" },
4074 { DRIVE_RAMDISK, "securityfs" },
4075 { DRIVE_CDROM, "iso9660" },
4076 { DRIVE_FIXED, "ext2" },
4077 { DRIVE_FIXED, "ext3" },
4078 { DRIVE_FIXED, "ext4" },
4079 { DRIVE_FIXED, "sysv" },
4080 { DRIVE_FIXED, "reiserfs" },
4081 { DRIVE_FIXED, "ufs" },
4082 { DRIVE_FIXED, "vfat" },
4083 { DRIVE_FIXED, "msdos" },
4084 { DRIVE_FIXED, "udf" },
4085 { DRIVE_FIXED, "hfs" },
4086 { DRIVE_FIXED, "hpfs" },
4087 { DRIVE_FIXED, "qnx4" },
4088 { DRIVE_FIXED, "ntfs" },
4089 { DRIVE_FIXED, "ntfs-3g" },
4090 { DRIVE_REMOTE, "smbfs" },
4091 { DRIVE_REMOTE, "fuse" },
4092 { DRIVE_REMOTE, "nfs" },
4093 { DRIVE_REMOTE, "nfs4" },
4094 { DRIVE_REMOTE, "cifs" },
4095 { DRIVE_REMOTE, "ncpfs" },
4096 { DRIVE_REMOTE, "coda" },
4097 { DRIVE_REMOTE, "afs" },
4098 { DRIVE_UNKNOWN, NULL }
4103 static guint32 _wapi_get_drive_type(long f_type)
4105 _wapi_drive_type *current;
4107 current = &_wapi_drive_types[0];
4108 while (current->drive_type != DRIVE_UNKNOWN) {
4109 if (current->fstypeid == f_type)
4110 return current->drive_type;
4114 return DRIVE_UNKNOWN;
4117 static guint32 _wapi_get_drive_type(const gchar* fstype)
4119 _wapi_drive_type *current;
4121 current = &_wapi_drive_types[0];
4122 while (current->drive_type != DRIVE_UNKNOWN) {
4123 if (strcmp (current->fstype, fstype) == 0)
4129 return current->drive_type;
4133 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4135 GetDriveTypeFromPath (const char *utf8_root_path_name)
4139 if (statfs (utf8_root_path_name, &buf) == -1)
4140 return DRIVE_UNKNOWN;
4142 return _wapi_get_drive_type (buf.f_fstypename);
4144 return _wapi_get_drive_type (buf.f_type);
4149 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4156 fp = fopen ("/etc/mtab", "rt");
4158 fp = fopen ("/etc/mnttab", "rt");
4160 return(DRIVE_UNKNOWN);
4163 drive_type = DRIVE_NO_ROOT_DIR;
4164 while (fgets (buffer, 512, fp) != NULL) {
4165 splitted = g_strsplit (buffer, " ", 0);
4166 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4167 g_strfreev (splitted);
4171 /* compare given root_path_name with the one from mtab,
4172 if length of utf8_root_path_name is zero it must be the root dir */
4173 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4174 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4175 drive_type = _wapi_get_drive_type (*(splitted + 2));
4176 /* it is possible this path might be mounted again with
4177 a known type...keep looking */
4178 if (drive_type != DRIVE_UNKNOWN) {
4179 g_strfreev (splitted);
4184 g_strfreev (splitted);
4192 guint32 GetDriveType(const gunichar2 *root_path_name)
4194 gchar *utf8_root_path_name;
4197 if (root_path_name == NULL) {
4198 utf8_root_path_name = g_strdup (g_get_current_dir());
4199 if (utf8_root_path_name == NULL) {
4200 return(DRIVE_NO_ROOT_DIR);
4204 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4205 if (utf8_root_path_name == NULL) {
4206 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4207 return(DRIVE_NO_ROOT_DIR);
4210 /* strip trailing slash for compare below */
4211 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4212 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4215 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4216 g_free (utf8_root_path_name);
4218 return (drive_type);
4221 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__) || defined(__FreeBSD_kernel__)
4223 get_fstypename (gchar *utfpath)
4225 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4228 _wapi_drive_type *current;
4230 if (statfs (utfpath, &stat) == -1)
4233 return g_strdup (stat.f_fstypename);
4235 current = &_wapi_drive_types[0];
4236 while (current->drive_type != DRIVE_UNKNOWN) {
4237 if (stat.f_type == current->fstypeid)
4238 return g_strdup (current->fstype);
4248 /* Linux has struct statfs which has a different layout */
4250 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4254 gboolean status = FALSE;
4257 // We only support getting the file system type
4258 if (fsbuffer == NULL)
4261 utfpath = mono_unicode_to_external (path);
4262 if ((fstypename = get_fstypename (utfpath)) != NULL){
4263 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4264 if (ret != NULL && len < fsbuffersize){
4265 memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4271 g_free (fstypename);
4280 _wapi_io_init (void)
4282 mono_os_mutex_init (&stdhandle_mutex);