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).
10 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
20 #ifdef HAVE_SYS_STATVFS_H
21 #include <sys/statvfs.h>
23 #if defined(HAVE_SYS_STATFS_H)
24 #include <sys/statfs.h>
26 #if defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H)
27 #include <sys/param.h>
28 #include <sys/mount.h>
30 #include <sys/types.h>
34 #include <sys/ioctl.h>
36 #include <mono/utils/linux_magic.h>
39 #include <mono/io-layer/wapi.h>
40 #include <mono/io-layer/wapi-private.h>
41 #include <mono/io-layer/handles-private.h>
42 #include <mono/io-layer/io-private.h>
43 #include <mono/io-layer/timefuncs-private.h>
44 #include <mono/io-layer/thread-private.h>
45 #include <mono/io-layer/io-portability.h>
46 #include <mono/io-layer/io-trace.h>
47 #include <mono/utils/strenc.h>
48 #include <mono/utils/mono-once.h>
49 #include <mono/utils/mono-logger-internals.h>
51 static void file_close (gpointer handle, gpointer data);
52 static WapiFileType file_getfiletype(void);
53 static gboolean file_read(gpointer handle, gpointer buffer,
54 guint32 numbytes, guint32 *bytesread,
55 WapiOverlapped *overlapped);
56 static gboolean file_write(gpointer handle, gconstpointer buffer,
57 guint32 numbytes, guint32 *byteswritten,
58 WapiOverlapped *overlapped);
59 static gboolean file_flush(gpointer handle);
60 static guint32 file_seek(gpointer handle, gint32 movedistance,
61 gint32 *highmovedistance, WapiSeekMethod method);
62 static gboolean file_setendoffile(gpointer handle);
63 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
64 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
65 WapiFileTime *last_access,
66 WapiFileTime *last_write);
67 static gboolean file_setfiletime(gpointer handle,
68 const WapiFileTime *create_time,
69 const WapiFileTime *last_access,
70 const WapiFileTime *last_write);
71 static guint32 GetDriveTypeFromPath (const gchar *utf8_root_path_name);
73 /* File handle is only signalled for overlapped IO */
74 struct _WapiHandleOps _wapi_file_ops = {
75 file_close, /* close */
79 NULL, /* special_wait */
83 void _wapi_file_details (gpointer handle_info)
85 struct _WapiHandle_file *file = (struct _WapiHandle_file *)handle_info;
87 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
89 file->fileaccess&GENERIC_READ?'R':'.',
90 file->fileaccess&GENERIC_WRITE?'W':'.',
91 file->fileaccess&GENERIC_EXECUTE?'X':'.',
92 file->sharemode&FILE_SHARE_READ?'R':'.',
93 file->sharemode&FILE_SHARE_WRITE?'W':'.',
94 file->sharemode&FILE_SHARE_DELETE?'D':'.',
98 static void console_close (gpointer handle, gpointer data);
99 static WapiFileType console_getfiletype(void);
100 static gboolean console_read(gpointer handle, gpointer buffer,
101 guint32 numbytes, guint32 *bytesread,
102 WapiOverlapped *overlapped);
103 static gboolean console_write(gpointer handle, gconstpointer buffer,
104 guint32 numbytes, guint32 *byteswritten,
105 WapiOverlapped *overlapped);
107 /* Console is mostly the same as file, except it can block waiting for
110 struct _WapiHandleOps _wapi_console_ops = {
111 console_close, /* close */
115 NULL, /* special_wait */
119 void _wapi_console_details (gpointer handle_info)
121 _wapi_file_details (handle_info);
124 /* Find handle has no ops.
126 struct _WapiHandleOps _wapi_find_ops = {
131 NULL, /* special_wait */
135 static void pipe_close (gpointer handle, gpointer data);
136 static WapiFileType pipe_getfiletype (void);
137 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
138 guint32 *bytesread, WapiOverlapped *overlapped);
139 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
140 guint32 numbytes, guint32 *byteswritten,
141 WapiOverlapped *overlapped);
145 struct _WapiHandleOps _wapi_pipe_ops = {
146 pipe_close, /* close */
150 NULL, /* special_wait */
154 void _wapi_pipe_details (gpointer handle_info)
156 _wapi_file_details (handle_info);
159 static const struct {
160 /* File, console and pipe handles */
161 WapiFileType (*getfiletype)(void);
163 /* File, console and pipe handles */
164 gboolean (*readfile)(gpointer handle, gpointer buffer,
165 guint32 numbytes, guint32 *bytesread,
166 WapiOverlapped *overlapped);
167 gboolean (*writefile)(gpointer handle, gconstpointer buffer,
168 guint32 numbytes, guint32 *byteswritten,
169 WapiOverlapped *overlapped);
170 gboolean (*flushfile)(gpointer handle);
173 guint32 (*seek)(gpointer handle, gint32 movedistance,
174 gint32 *highmovedistance, WapiSeekMethod method);
175 gboolean (*setendoffile)(gpointer handle);
176 guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
177 gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
178 WapiFileTime *last_access,
179 WapiFileTime *last_write);
180 gboolean (*setfiletime)(gpointer handle,
181 const WapiFileTime *create_time,
182 const WapiFileTime *last_access,
183 const WapiFileTime *last_write);
184 } io_ops[WAPI_HANDLE_COUNT]={
185 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
188 file_read, file_write,
189 file_flush, file_seek,
195 {console_getfiletype,
198 NULL, NULL, NULL, NULL, NULL, NULL},
200 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
202 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
204 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
206 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
207 /* socket (will need at least read and write) */
208 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
210 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
212 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
217 NULL, NULL, NULL, NULL, NULL, NULL},
220 static mono_once_t io_ops_once=MONO_ONCE_INIT;
221 static gboolean lock_while_writing = FALSE;
223 static void io_ops_init (void)
225 /* _wapi_handle_register_capabilities (WAPI_HANDLE_FILE, */
226 /* WAPI_HANDLE_CAP_WAIT); */
227 /* _wapi_handle_register_capabilities (WAPI_HANDLE_CONSOLE, */
228 /* WAPI_HANDLE_CAP_WAIT); */
230 if (g_getenv ("MONO_STRICT_IO_EMULATION") != NULL) {
231 lock_while_writing = TRUE;
235 /* Some utility functions.
239 * Check if a file is writable by the current user.
241 * This is is a best effort kind of thing. It assumes a reasonable sane set
242 * of permissions by the underlying OS.
244 * We generally assume that basic unix permission bits are authoritative. Which might not
245 * be the case under systems with extended permissions systems (posix ACLs, SELinux, OSX/iOS sandboxing, etc)
247 * The choice of access as the fallback is due to the expected lower overhead compared to trying to open the file.
249 * The only expected problem with using access are for root, setuid or setgid programs as access is not consistent
250 * under those situations. It's to be expected that this should not happen in practice as those bits are very dangerous
251 * and should not be used with a dynamic runtime.
254 is_file_writable (struct stat *st, const char *path)
257 // OS X Finder "locked" or `ls -lO` "uchg".
258 // This only covers one of several cases where an OS X file could be unwritable through special flags.
259 if (st->st_flags & (UF_IMMUTABLE|SF_IMMUTABLE))
263 /* Is it globally writable? */
264 if (st->st_mode & S_IWOTH)
267 /* Am I the owner? */
268 if ((st->st_uid == geteuid ()) && (st->st_mode & S_IWUSR))
271 /* Am I in the same group? */
272 if ((st->st_gid == getegid ()) && (st->st_mode & S_IWGRP))
275 /* Fallback to using access(2). It's not ideal as it might not take into consideration euid/egid
276 * but it's the only sane option we have on unix.
278 return access (path, W_OK) == 0;
282 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
289 /* FIXME: this could definitely be better, but there seems to
290 * be no pattern to the attributes that are set
293 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
294 if (S_ISSOCK (buf->st_mode))
295 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
297 filename = _wapi_basename (pathname);
299 if (S_ISDIR (buf->st_mode)) {
300 attrs = FILE_ATTRIBUTE_DIRECTORY;
301 if (!is_file_writable (buf, pathname)) {
302 attrs |= FILE_ATTRIBUTE_READONLY;
304 if (filename[0] == '.') {
305 attrs |= FILE_ATTRIBUTE_HIDDEN;
308 if (!is_file_writable (buf, pathname)) {
309 attrs = FILE_ATTRIBUTE_READONLY;
311 if (filename[0] == '.') {
312 attrs |= FILE_ATTRIBUTE_HIDDEN;
314 } else if (filename[0] == '.') {
315 attrs = FILE_ATTRIBUTE_HIDDEN;
317 attrs = FILE_ATTRIBUTE_NORMAL;
322 if (S_ISLNK (lbuf->st_mode)) {
323 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
333 _wapi_set_last_error_from_errno (void)
335 SetLastError (_wapi_get_win32_file_error (errno));
338 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
341 if (errno == ENOENT) {
342 /* Check the path - if it's a missing directory then
343 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
349 dirname = _wapi_dirname (path);
351 dirname = g_strdup (dir);
354 if (_wapi_access (dirname, F_OK) == 0) {
355 SetLastError (ERROR_FILE_NOT_FOUND);
357 SetLastError (ERROR_PATH_NOT_FOUND);
362 _wapi_set_last_error_from_errno ();
368 static void file_close (gpointer handle, gpointer data)
370 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
371 int fd = file_handle->fd;
373 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing file handle %p [%s]", __func__, handle,
374 file_handle->filename);
376 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
377 _wapi_unlink (file_handle->filename);
379 g_free (file_handle->filename);
381 if (file_handle->share_info)
382 _wapi_handle_share_release (file_handle->share_info);
387 static WapiFileType file_getfiletype(void)
389 return(FILE_TYPE_DISK);
392 static gboolean file_read(gpointer handle, gpointer buffer,
393 guint32 numbytes, guint32 *bytesread,
394 WapiOverlapped *overlapped)
396 struct _WapiHandle_file *file_handle;
400 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
401 (gpointer *)&file_handle);
403 g_warning ("%s: error looking up file handle %p", __func__,
405 SetLastError (ERROR_INVALID_HANDLE);
409 fd = file_handle->fd;
410 if(bytesread!=NULL) {
414 if(!(file_handle->fileaccess & GENERIC_READ) &&
415 !(file_handle->fileaccess & GENERIC_ALL)) {
416 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
417 __func__, handle, file_handle->fileaccess);
419 SetLastError (ERROR_ACCESS_DENIED);
424 ret = read (fd, buffer, numbytes);
425 } while (ret == -1 && errno == EINTR &&
426 !_wapi_thread_cur_apc_pending());
431 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
432 handle, strerror(err));
433 SetLastError (_wapi_get_win32_file_error (err));
437 if (bytesread != NULL) {
444 static gboolean file_write(gpointer handle, gconstpointer buffer,
445 guint32 numbytes, guint32 *byteswritten,
446 WapiOverlapped *overlapped G_GNUC_UNUSED)
448 struct _WapiHandle_file *file_handle;
451 off_t current_pos = 0;
453 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
454 (gpointer *)&file_handle);
456 g_warning ("%s: error looking up file handle %p", __func__,
458 SetLastError (ERROR_INVALID_HANDLE);
462 fd = file_handle->fd;
464 if(byteswritten!=NULL) {
468 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
469 !(file_handle->fileaccess & GENERIC_ALL)) {
470 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);
472 SetLastError (ERROR_ACCESS_DENIED);
476 if (lock_while_writing) {
477 /* Need to lock the region we're about to write to,
478 * because we only do advisory locking on POSIX
481 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
482 if (current_pos == -1) {
483 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
484 handle, strerror (errno));
485 _wapi_set_last_error_from_errno ();
489 if (_wapi_lock_file_region (fd, current_pos,
490 numbytes) == FALSE) {
491 /* The error has already been set */
497 ret = write (fd, buffer, numbytes);
498 } while (ret == -1 && errno == EINTR &&
499 !_wapi_thread_cur_apc_pending());
501 if (lock_while_writing) {
502 _wapi_unlock_file_region (fd, current_pos, numbytes);
506 if (errno == EINTR) {
509 _wapi_set_last_error_from_errno ();
511 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
512 __func__, handle, strerror(errno));
517 if (byteswritten != NULL) {
523 static gboolean file_flush(gpointer handle)
525 struct _WapiHandle_file *file_handle;
529 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
530 (gpointer *)&file_handle);
532 g_warning ("%s: error looking up file handle %p", __func__,
534 SetLastError (ERROR_INVALID_HANDLE);
538 fd = file_handle->fd;
540 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
541 !(file_handle->fileaccess & GENERIC_ALL)) {
542 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);
544 SetLastError (ERROR_ACCESS_DENIED);
550 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fsync of handle %p error: %s", __func__, handle,
553 _wapi_set_last_error_from_errno ();
560 static guint32 file_seek(gpointer handle, gint32 movedistance,
561 gint32 *highmovedistance, WapiSeekMethod method)
563 struct _WapiHandle_file *file_handle;
565 gint64 offset, newpos;
569 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
570 (gpointer *)&file_handle);
572 g_warning ("%s: error looking up file handle %p", __func__,
574 SetLastError (ERROR_INVALID_HANDLE);
575 return(INVALID_SET_FILE_POINTER);
578 fd = file_handle->fd;
580 if(!(file_handle->fileaccess & GENERIC_READ) &&
581 !(file_handle->fileaccess & GENERIC_WRITE) &&
582 !(file_handle->fileaccess & GENERIC_ALL)) {
583 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);
585 SetLastError (ERROR_ACCESS_DENIED);
586 return(INVALID_SET_FILE_POINTER);
600 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: invalid seek type %d", __func__, method);
602 SetLastError (ERROR_INVALID_PARAMETER);
603 return(INVALID_SET_FILE_POINTER);
606 #ifdef HAVE_LARGE_FILE_SUPPORT
607 if(highmovedistance==NULL) {
609 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting offset to %lld (low %d)", __func__,
610 offset, movedistance);
612 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
614 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);
620 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: moving handle %p by %lld bytes from %d", __func__,
621 handle, (long long)offset, whence);
623 #ifdef PLATFORM_ANDROID
624 /* bionic doesn't support -D_FILE_OFFSET_BITS=64 */
625 newpos=lseek64(fd, offset, whence);
627 newpos=lseek(fd, offset, whence);
630 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek on handle %p returned error %s",
631 __func__, handle, strerror(errno));
633 _wapi_set_last_error_from_errno ();
634 return(INVALID_SET_FILE_POINTER);
637 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek returns %lld", __func__, newpos);
639 #ifdef HAVE_LARGE_FILE_SUPPORT
640 ret=newpos & 0xFFFFFFFF;
641 if(highmovedistance!=NULL) {
642 *highmovedistance=newpos>>32;
646 if(highmovedistance!=NULL) {
647 /* Accurate, but potentially dodgy :-) */
652 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: move of handle %p returning %d/%d", __func__,
653 handle, ret, highmovedistance==NULL?0:*highmovedistance);
658 static gboolean file_setendoffile(gpointer handle)
660 struct _WapiHandle_file *file_handle;
666 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
667 (gpointer *)&file_handle);
669 g_warning ("%s: error looking up file handle %p", __func__,
671 SetLastError (ERROR_INVALID_HANDLE);
674 fd = file_handle->fd;
676 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
677 !(file_handle->fileaccess & GENERIC_ALL)) {
678 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);
680 SetLastError (ERROR_ACCESS_DENIED);
684 /* Find the current file position, and the file length. If
685 * the file position is greater than the length, write to
686 * extend the file with a hole. If the file position is less
687 * than the length, truncate the file.
690 ret=fstat(fd, &statbuf);
692 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
693 handle, strerror(errno));
695 _wapi_set_last_error_from_errno ();
699 pos=lseek(fd, (off_t)0, SEEK_CUR);
701 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
702 handle, strerror(errno));
704 _wapi_set_last_error_from_errno ();
708 #ifdef FTRUNCATE_DOESNT_EXTEND
709 off_t size = statbuf.st_size;
710 /* I haven't bothered to write the configure.ac stuff for this
711 * because I don't know if any platform needs it. I'm leaving
712 * this code just in case though
715 /* Extend the file. Use write() here, because some
716 * manuals say that ftruncate() behaviour is undefined
717 * when the file needs extending. The POSIX spec says
718 * that on XSI-conformant systems it extends, so if
719 * every system we care about conforms, then we can
723 ret = write (fd, "", 1);
724 } while (ret == -1 && errno == EINTR &&
725 !_wapi_thread_cur_apc_pending());
728 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
730 _wapi_set_last_error_from_errno ();
734 /* And put the file position back after the write */
735 ret = lseek (fd, pos, SEEK_SET);
737 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p second lseek failed: %s",
738 __func__, handle, strerror(errno));
740 _wapi_set_last_error_from_errno ();
746 /* Native Client has no ftruncate function, even in standalone sel_ldr. */
747 #ifndef __native_client__
748 /* always truncate, because the extend write() adds an extra
749 * byte to the end of the file
752 ret=ftruncate(fd, pos);
754 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
756 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ftruncate failed: %s", __func__,
757 handle, strerror(errno));
759 _wapi_set_last_error_from_errno ();
767 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
769 struct _WapiHandle_file *file_handle;
776 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
777 (gpointer *)&file_handle);
779 g_warning ("%s: error looking up file handle %p", __func__,
781 SetLastError (ERROR_INVALID_HANDLE);
782 return(INVALID_FILE_SIZE);
784 fd = file_handle->fd;
786 if(!(file_handle->fileaccess & GENERIC_READ) &&
787 !(file_handle->fileaccess & GENERIC_WRITE) &&
788 !(file_handle->fileaccess & GENERIC_ALL)) {
789 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);
791 SetLastError (ERROR_ACCESS_DENIED);
792 return(INVALID_FILE_SIZE);
795 /* If the file has a size with the low bits 0xFFFFFFFF the
796 * caller can't tell if this is an error, so clear the error
799 SetLastError (ERROR_SUCCESS);
801 ret = fstat(fd, &statbuf);
803 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
804 handle, strerror(errno));
806 _wapi_set_last_error_from_errno ();
807 return(INVALID_FILE_SIZE);
810 /* fstat indicates block devices as zero-length, so go a different path */
812 if (S_ISBLK(statbuf.st_mode)) {
814 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
815 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ioctl BLKGETSIZE64 failed: %s",
816 __func__, handle, strerror(errno));
818 _wapi_set_last_error_from_errno ();
819 return(INVALID_FILE_SIZE);
822 size = bigsize & 0xFFFFFFFF;
823 if (highsize != NULL) {
824 *highsize = bigsize>>32;
827 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning block device size %d/%d",
828 __func__, size, *highsize);
834 #ifdef HAVE_LARGE_FILE_SUPPORT
835 size = statbuf.st_size & 0xFFFFFFFF;
836 if (highsize != NULL) {
837 *highsize = statbuf.st_size>>32;
840 if (highsize != NULL) {
841 /* Accurate, but potentially dodgy :-) */
844 size = statbuf.st_size;
847 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning size %d/%d", __func__, size, *highsize);
852 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
853 WapiFileTime *last_access,
854 WapiFileTime *last_write)
856 struct _WapiHandle_file *file_handle;
859 guint64 create_ticks, access_ticks, write_ticks;
862 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
863 (gpointer *)&file_handle);
865 g_warning ("%s: error looking up file handle %p", __func__,
867 SetLastError (ERROR_INVALID_HANDLE);
870 fd = file_handle->fd;
872 if(!(file_handle->fileaccess & GENERIC_READ) &&
873 !(file_handle->fileaccess & GENERIC_ALL)) {
874 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
875 __func__, handle, file_handle->fileaccess);
877 SetLastError (ERROR_ACCESS_DENIED);
881 ret=fstat(fd, &statbuf);
883 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
886 _wapi_set_last_error_from_errno ();
890 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: atime: %ld ctime: %ld mtime: %ld", __func__,
891 statbuf.st_atime, statbuf.st_ctime,
894 /* Try and guess a meaningful create time by using the older
897 /* The magic constant comes from msdn documentation
898 * "Converting a time_t Value to a File Time"
900 if(statbuf.st_atime < statbuf.st_ctime) {
901 create_ticks=((guint64)statbuf.st_atime*10000000)
902 + 116444736000000000ULL;
904 create_ticks=((guint64)statbuf.st_ctime*10000000)
905 + 116444736000000000ULL;
908 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
909 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
911 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
912 access_ticks, create_ticks, write_ticks);
914 if(create_time!=NULL) {
915 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
916 create_time->dwHighDateTime = create_ticks >> 32;
919 if(last_access!=NULL) {
920 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
921 last_access->dwHighDateTime = access_ticks >> 32;
924 if(last_write!=NULL) {
925 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
926 last_write->dwHighDateTime = write_ticks >> 32;
932 static gboolean file_setfiletime(gpointer handle,
933 const WapiFileTime *create_time G_GNUC_UNUSED,
934 const WapiFileTime *last_access,
935 const WapiFileTime *last_write)
937 struct _WapiHandle_file *file_handle;
939 struct utimbuf utbuf;
941 guint64 access_ticks, write_ticks;
944 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
945 (gpointer *)&file_handle);
947 g_warning ("%s: error looking up file handle %p", __func__,
949 SetLastError (ERROR_INVALID_HANDLE);
952 fd = file_handle->fd;
954 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
955 !(file_handle->fileaccess & GENERIC_ALL)) {
956 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);
958 SetLastError (ERROR_ACCESS_DENIED);
962 if(file_handle->filename == NULL) {
963 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p unknown filename", __func__, handle);
965 SetLastError (ERROR_INVALID_HANDLE);
969 /* Get the current times, so we can put the same times back in
970 * the event that one of the FileTime structs is NULL
972 ret=fstat (fd, &statbuf);
974 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
977 SetLastError (ERROR_INVALID_PARAMETER);
981 if(last_access!=NULL) {
982 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
983 last_access->dwLowDateTime;
984 /* This is (time_t)0. We can actually go to INT_MIN,
985 * but this will do for now.
987 if (access_ticks < 116444736000000000ULL) {
988 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set access time too early",
990 SetLastError (ERROR_INVALID_PARAMETER);
994 if (sizeof (utbuf.actime) == 4 && ((access_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
995 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set write time that is too big for a 32bits time_t",
997 SetLastError (ERROR_INVALID_PARAMETER);
1001 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
1003 utbuf.actime=statbuf.st_atime;
1006 if(last_write!=NULL) {
1007 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
1008 last_write->dwLowDateTime;
1009 /* This is (time_t)0. We can actually go to INT_MIN,
1010 * but this will do for now.
1012 if (write_ticks < 116444736000000000ULL) {
1013 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set write time too early",
1015 SetLastError (ERROR_INVALID_PARAMETER);
1018 if (sizeof (utbuf.modtime) == 4 && ((write_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
1019 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set write time that is too big for a 32bits time_t",
1021 SetLastError (ERROR_INVALID_PARAMETER);
1025 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1027 utbuf.modtime=statbuf.st_mtime;
1030 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting handle %p access %ld write %ld", __func__,
1031 handle, utbuf.actime, utbuf.modtime);
1033 ret = _wapi_utime (file_handle->filename, &utbuf);
1035 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p [%s] utime failed: %s", __func__,
1036 handle, file_handle->filename, strerror(errno));
1038 SetLastError (ERROR_INVALID_PARAMETER);
1045 static void console_close (gpointer handle, gpointer data)
1047 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1048 int fd = console_handle->fd;
1050 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing console handle %p", __func__, handle);
1052 g_free (console_handle->filename);
1055 if (console_handle->share_info)
1056 _wapi_handle_share_release (console_handle->share_info);
1061 static WapiFileType console_getfiletype(void)
1063 return(FILE_TYPE_CHAR);
1066 static gboolean console_read(gpointer handle, gpointer buffer,
1067 guint32 numbytes, guint32 *bytesread,
1068 WapiOverlapped *overlapped G_GNUC_UNUSED)
1070 struct _WapiHandle_file *console_handle;
1074 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1075 (gpointer *)&console_handle);
1077 g_warning ("%s: error looking up console handle %p", __func__,
1079 SetLastError (ERROR_INVALID_HANDLE);
1082 fd = console_handle->fd;
1084 if(bytesread!=NULL) {
1088 if(!(console_handle->fileaccess & GENERIC_READ) &&
1089 !(console_handle->fileaccess & GENERIC_ALL)) {
1090 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1091 __func__, handle, console_handle->fileaccess);
1093 SetLastError (ERROR_ACCESS_DENIED);
1098 ret=read(fd, buffer, numbytes);
1099 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1102 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__, handle,
1105 _wapi_set_last_error_from_errno ();
1109 if(bytesread!=NULL) {
1116 static gboolean console_write(gpointer handle, gconstpointer buffer,
1117 guint32 numbytes, guint32 *byteswritten,
1118 WapiOverlapped *overlapped G_GNUC_UNUSED)
1120 struct _WapiHandle_file *console_handle;
1124 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1125 (gpointer *)&console_handle);
1127 g_warning ("%s: error looking up console handle %p", __func__,
1129 SetLastError (ERROR_INVALID_HANDLE);
1132 fd = console_handle->fd;
1134 if(byteswritten!=NULL) {
1138 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1139 !(console_handle->fileaccess & GENERIC_ALL)) {
1140 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);
1142 SetLastError (ERROR_ACCESS_DENIED);
1147 ret = write(fd, buffer, numbytes);
1148 } while (ret == -1 && errno == EINTR &&
1149 !_wapi_thread_cur_apc_pending());
1152 if (errno == EINTR) {
1155 _wapi_set_last_error_from_errno ();
1157 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
1158 __func__, handle, strerror(errno));
1163 if(byteswritten!=NULL) {
1170 static void pipe_close (gpointer handle, gpointer data)
1172 struct _WapiHandle_file *pipe_handle = (struct _WapiHandle_file*)data;
1173 int fd = pipe_handle->fd;
1175 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing pipe handle %p fd %d", __func__, handle, fd);
1177 /* No filename with pipe handles */
1179 if (pipe_handle->share_info)
1180 _wapi_handle_share_release (pipe_handle->share_info);
1185 static WapiFileType pipe_getfiletype(void)
1187 return(FILE_TYPE_PIPE);
1190 static gboolean pipe_read (gpointer handle, gpointer buffer,
1191 guint32 numbytes, guint32 *bytesread,
1192 WapiOverlapped *overlapped G_GNUC_UNUSED)
1194 struct _WapiHandle_file *pipe_handle;
1198 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1199 (gpointer *)&pipe_handle);
1201 g_warning ("%s: error looking up pipe handle %p", __func__,
1203 SetLastError (ERROR_INVALID_HANDLE);
1206 fd = pipe_handle->fd;
1208 if(bytesread!=NULL) {
1212 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1213 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1214 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1215 __func__, handle, pipe_handle->fileaccess);
1217 SetLastError (ERROR_ACCESS_DENIED);
1221 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: reading up to %d bytes from pipe %p", __func__,
1225 ret=read(fd, buffer, numbytes);
1226 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1229 if (errno == EINTR) {
1232 _wapi_set_last_error_from_errno ();
1234 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
1235 handle, strerror(errno));
1241 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read %d bytes from pipe %p", __func__, ret, handle);
1243 if(bytesread!=NULL) {
1250 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1251 guint32 numbytes, guint32 *byteswritten,
1252 WapiOverlapped *overlapped G_GNUC_UNUSED)
1254 struct _WapiHandle_file *pipe_handle;
1258 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1259 (gpointer *)&pipe_handle);
1261 g_warning ("%s: error looking up pipe handle %p", __func__,
1263 SetLastError (ERROR_INVALID_HANDLE);
1266 fd = pipe_handle->fd;
1268 if(byteswritten!=NULL) {
1272 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1273 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1274 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);
1276 SetLastError (ERROR_ACCESS_DENIED);
1280 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1284 ret = write (fd, buffer, numbytes);
1285 } while (ret == -1 && errno == EINTR &&
1286 !_wapi_thread_cur_apc_pending());
1289 if (errno == EINTR) {
1292 _wapi_set_last_error_from_errno ();
1294 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s", __func__,
1295 handle, strerror(errno));
1300 if(byteswritten!=NULL) {
1307 static int convert_flags(guint32 fileaccess, guint32 createmode)
1311 switch(fileaccess) {
1318 case GENERIC_READ|GENERIC_WRITE:
1322 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown access type 0x%x", __func__,
1327 switch(createmode) {
1329 flags|=O_CREAT|O_EXCL;
1332 flags|=O_CREAT|O_TRUNC;
1339 case TRUNCATE_EXISTING:
1343 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown create mode 0x%x", __func__,
1352 static mode_t convert_perms(guint32 sharemode)
1356 if(sharemode&FILE_SHARE_READ) {
1359 if(sharemode&FILE_SHARE_WRITE) {
1367 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1369 struct _WapiFileShare **share_info)
1371 gboolean file_already_shared;
1372 guint32 file_existing_share, file_existing_access;
1374 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);
1376 if (file_already_shared) {
1377 /* The reference to this share info was incremented
1378 * when we looked it up, so be careful to put it back
1379 * if we conclude we can't use this file.
1381 if (file_existing_share == 0) {
1382 /* Quick and easy, no possibility to share */
1383 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);
1385 _wapi_handle_share_release (*share_info);
1390 if (((file_existing_share == FILE_SHARE_READ) &&
1391 (fileaccess != GENERIC_READ)) ||
1392 ((file_existing_share == FILE_SHARE_WRITE) &&
1393 (fileaccess != GENERIC_WRITE))) {
1394 /* New access mode doesn't match up */
1395 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);
1397 _wapi_handle_share_release (*share_info);
1402 if (((file_existing_access & GENERIC_READ) &&
1403 !(sharemode & FILE_SHARE_READ)) ||
1404 ((file_existing_access & GENERIC_WRITE) &&
1405 !(sharemode & FILE_SHARE_WRITE))) {
1406 /* New share mode doesn't match up */
1407 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);
1409 _wapi_handle_share_release (*share_info);
1414 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
1422 share_allows_delete (struct stat *statbuf, struct _WapiFileShare **share_info)
1424 gboolean file_already_shared;
1425 guint32 file_existing_share, file_existing_access;
1427 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);
1429 if (file_already_shared) {
1430 /* The reference to this share info was incremented
1431 * when we looked it up, so be careful to put it back
1432 * if we conclude we can't use this file.
1434 if (file_existing_share == 0) {
1435 /* Quick and easy, no possibility to share */
1436 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);
1438 _wapi_handle_share_release (*share_info);
1443 if (!(file_existing_share & FILE_SHARE_DELETE)) {
1444 /* New access mode doesn't match up */
1445 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);
1447 _wapi_handle_share_release (*share_info);
1452 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
1460 * @name: a pointer to a NULL-terminated unicode string, that names
1461 * the file or other object to create.
1462 * @fileaccess: specifies the file access mode
1463 * @sharemode: whether the file should be shared. This parameter is
1464 * currently ignored.
1465 * @security: Ignored for now.
1466 * @createmode: specifies whether to create a new file, whether to
1467 * overwrite an existing file, whether to truncate the file, etc.
1468 * @attrs: specifies file attributes and flags. On win32 attributes
1469 * are characteristics of the file, not the handle, and are ignored
1470 * when an existing file is opened. Flags give the library hints on
1471 * how to process a file to optimise performance.
1472 * @template: the handle of an open %GENERIC_READ file that specifies
1473 * attributes to apply to a newly created file, ignoring @attrs.
1474 * Normally this parameter is NULL. This parameter is ignored when an
1475 * existing file is opened.
1477 * Creates a new file handle. This only applies to normal files:
1478 * pipes are handled by CreatePipe(), and console handles are created
1479 * with GetStdHandle().
1481 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1483 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1484 guint32 sharemode, WapiSecurityAttributes *security,
1485 guint32 createmode, guint32 attrs,
1486 gpointer template_ G_GNUC_UNUSED)
1488 struct _WapiHandle_file file_handle = {0};
1490 int flags=convert_flags(fileaccess, createmode);
1491 /*mode_t perms=convert_perms(sharemode);*/
1492 /* we don't use sharemode, because that relates to sharing of
1493 * the file when the file is open and is already handled by
1494 * other code, perms instead are the on-disk permissions and
1495 * this is a sane default.
1500 WapiHandleType handle_type;
1501 struct stat statbuf;
1503 mono_once (&io_ops_once, io_ops_init);
1505 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1508 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1509 SetLastError (ERROR_ENCRYPTION_FAILED);
1510 return INVALID_HANDLE_VALUE;
1514 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1516 SetLastError (ERROR_INVALID_NAME);
1517 return(INVALID_HANDLE_VALUE);
1520 filename = mono_unicode_to_external (name);
1521 if (filename == NULL) {
1522 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1524 SetLastError (ERROR_INVALID_NAME);
1525 return(INVALID_HANDLE_VALUE);
1528 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Opening %s with share 0x%x and access 0x%x", __func__,
1529 filename, sharemode, fileaccess);
1531 fd = _wapi_open (filename, flags, perms);
1533 /* If we were trying to open a directory with write permissions
1534 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1535 * EISDIR. However, this is a bit bogus because calls to
1536 * manipulate the directory (e.g. SetFileTime) will still work on
1537 * the directory because they use other API calls
1538 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1539 * to open the directory again without write permission.
1541 if (fd == -1 && errno == EISDIR)
1543 /* Try again but don't try to make it writable */
1544 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1548 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s: %s", __func__, filename,
1550 _wapi_set_last_path_error_from_errno (NULL, filename);
1553 return(INVALID_HANDLE_VALUE);
1556 if (fd >= _wapi_fd_reserve) {
1557 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
1559 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1564 return(INVALID_HANDLE_VALUE);
1567 ret = fstat (fd, &statbuf);
1569 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fstat error of file %s: %s", __func__,
1570 filename, strerror (errno));
1571 _wapi_set_last_error_from_errno ();
1575 return(INVALID_HANDLE_VALUE);
1577 #ifdef __native_client__
1578 /* Workaround: Native Client currently returns the same fake inode
1579 * for all files, so do a simple hash on the filename so we don't
1580 * use the same share info for each file.
1582 statbuf.st_ino = g_str_hash(filename);
1585 if (share_allows_open (&statbuf, sharemode, fileaccess,
1586 &file_handle.share_info) == FALSE) {
1587 SetLastError (ERROR_SHARING_VIOLATION);
1591 return (INVALID_HANDLE_VALUE);
1593 if (file_handle.share_info == NULL) {
1594 /* No space, so no more files can be opened */
1595 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No space in the share table", __func__);
1597 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1601 return(INVALID_HANDLE_VALUE);
1604 file_handle.filename = filename;
1606 if(security!=NULL) {
1607 //file_handle->security_attributes=_wapi_handle_scratch_store (
1608 //security, sizeof(WapiSecurityAttributes));
1611 file_handle.fd = fd;
1612 file_handle.fileaccess=fileaccess;
1613 file_handle.sharemode=sharemode;
1614 file_handle.attrs=attrs;
1616 #ifdef HAVE_POSIX_FADVISE
1617 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1618 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1619 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1620 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1624 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1626 if (S_ISFIFO (statbuf.st_mode)) {
1627 handle_type = WAPI_HANDLE_PIPE;
1628 /* maintain invariant that pipes have no filename */
1629 file_handle.filename = NULL;
1632 } else if (S_ISCHR (statbuf.st_mode)) {
1633 handle_type = WAPI_HANDLE_CONSOLE;
1635 handle_type = WAPI_HANDLE_FILE;
1638 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1639 if (handle == _WAPI_HANDLE_INVALID) {
1640 g_warning ("%s: error creating file handle", __func__);
1644 SetLastError (ERROR_GEN_FAILURE);
1645 return(INVALID_HANDLE_VALUE);
1648 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p", __func__, handle);
1655 * @name: a pointer to a NULL-terminated unicode string, that names
1656 * the file to be deleted.
1658 * Deletes file @name.
1660 * Return value: %TRUE on success, %FALSE otherwise.
1662 gboolean DeleteFile(const gunichar2 *name)
1666 gboolean ret = FALSE;
1669 struct stat statbuf;
1670 struct _WapiFileShare *shareinfo;
1674 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1676 SetLastError (ERROR_INVALID_NAME);
1680 filename=mono_unicode_to_external(name);
1681 if(filename==NULL) {
1682 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1684 SetLastError (ERROR_INVALID_NAME);
1688 attrs = GetFileAttributes (name);
1689 if (attrs == INVALID_FILE_ATTRIBUTES) {
1690 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file attributes error", __func__);
1691 /* Error set by GetFileAttributes() */
1697 /* Check to make sure sharing allows us to open the file for
1698 * writing. See bug 323389.
1700 * Do the checks that don't need an open file descriptor, for
1701 * simplicity's sake. If we really have to do the full checks
1702 * then we can implement that later.
1704 if (_wapi_stat (filename, &statbuf) < 0) {
1705 _wapi_set_last_path_error_from_errno (NULL, filename);
1710 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1711 &shareinfo) == FALSE) {
1712 SetLastError (ERROR_SHARING_VIOLATION);
1717 _wapi_handle_share_release (shareinfo);
1720 retval = _wapi_unlink (filename);
1723 _wapi_set_last_path_error_from_errno (NULL, filename);
1735 * @name: a pointer to a NULL-terminated unicode string, that names
1736 * the file to be moved.
1737 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1738 * new name for the file.
1740 * Renames file @name to @dest_name.
1741 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1742 * when it is the same file as the source. In that case it silently succeeds.
1744 * Return value: %TRUE on success, %FALSE otherwise.
1746 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1748 gchar *utf8_name, *utf8_dest_name;
1749 int result, errno_copy;
1750 struct stat stat_src, stat_dest;
1751 gboolean ret = FALSE;
1752 struct _WapiFileShare *shareinfo;
1755 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1757 SetLastError (ERROR_INVALID_NAME);
1761 utf8_name = mono_unicode_to_external (name);
1762 if (utf8_name == NULL) {
1763 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1765 SetLastError (ERROR_INVALID_NAME);
1769 if(dest_name==NULL) {
1770 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1773 SetLastError (ERROR_INVALID_NAME);
1777 utf8_dest_name = mono_unicode_to_external (dest_name);
1778 if (utf8_dest_name == NULL) {
1779 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1782 SetLastError (ERROR_INVALID_NAME);
1787 * In C# land we check for the existence of src, but not for dest.
1788 * We check it here and return the failure if dest exists and is not
1789 * the same file as src.
1791 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1792 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1793 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1795 g_free (utf8_dest_name);
1800 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1801 if (stat_dest.st_dev != stat_src.st_dev ||
1802 stat_dest.st_ino != stat_src.st_ino) {
1804 g_free (utf8_dest_name);
1805 SetLastError (ERROR_ALREADY_EXISTS);
1810 /* Check to make that we have delete sharing permission.
1811 * See https://bugzilla.xamarin.com/show_bug.cgi?id=17009
1813 * Do the checks that don't need an open file descriptor, for
1814 * simplicity's sake. If we really have to do the full checks
1815 * then we can implement that later.
1817 if (share_allows_delete (&stat_src, &shareinfo) == FALSE) {
1818 SetLastError (ERROR_SHARING_VIOLATION);
1822 _wapi_handle_share_release (shareinfo);
1824 result = _wapi_rename (utf8_name, utf8_dest_name);
1828 switch(errno_copy) {
1830 SetLastError (ERROR_ALREADY_EXISTS);
1834 /* Ignore here, it is dealt with below */
1838 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1843 g_free (utf8_dest_name);
1845 if (result != 0 && errno_copy == EXDEV) {
1846 if (S_ISDIR (stat_src.st_mode)) {
1847 SetLastError (ERROR_NOT_SAME_DEVICE);
1850 /* Try a copy to the new location, and delete the source */
1851 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1852 /* CopyFile will set the error */
1856 return(DeleteFile (name));
1867 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1871 int buf_size = st_src->st_blksize;
1873 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1874 buf = (char *) malloc (buf_size);
1877 remain = read (src_fd, buf, buf_size);
1879 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1883 _wapi_set_last_error_from_errno ();
1893 while (remain > 0) {
1894 if ((n = write (dest_fd, wbuf, remain)) < 0) {
1895 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1899 _wapi_set_last_error_from_errno ();
1900 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write failed.", __func__);
1916 * @name: a pointer to a NULL-terminated unicode string, that names
1917 * the file to be copied.
1918 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1919 * new name for the file.
1920 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1922 * Copies file @name to @dest_name
1924 * Return value: %TRUE on success, %FALSE otherwise.
1926 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1927 gboolean fail_if_exists)
1929 gchar *utf8_src, *utf8_dest;
1930 int src_fd, dest_fd;
1931 struct stat st, dest_st;
1932 struct utimbuf dest_time;
1933 gboolean ret = TRUE;
1937 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1939 SetLastError (ERROR_INVALID_NAME);
1943 utf8_src = mono_unicode_to_external (name);
1944 if (utf8_src == NULL) {
1945 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of source returned NULL",
1948 SetLastError (ERROR_INVALID_PARAMETER);
1952 if(dest_name==NULL) {
1953 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: dest is NULL", __func__);
1956 SetLastError (ERROR_INVALID_NAME);
1960 utf8_dest = mono_unicode_to_external (dest_name);
1961 if (utf8_dest == NULL) {
1962 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of dest returned NULL",
1965 SetLastError (ERROR_INVALID_PARAMETER);
1972 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
1974 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
1982 if (fstat (src_fd, &st) < 0) {
1983 _wapi_set_last_error_from_errno ();
1992 /* Before trying to open/create the dest, we need to report a 'file busy'
1993 * error if src and dest are actually the same file. We do the check here to take
1994 * advantage of the IOMAP capability */
1995 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
1996 st.st_ino == dest_st.st_ino) {
2002 SetLastError (ERROR_SHARING_VIOLATION);
2006 if (fail_if_exists) {
2007 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2009 /* FIXME: it kinda sucks that this code path potentially scans
2010 * the directory twice due to the weird SetLastError()
2012 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2014 /* The file does not exist, try creating it */
2015 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2017 /* Apparently this error is set if we
2018 * overwrite the dest file
2020 SetLastError (ERROR_ALREADY_EXISTS);
2024 _wapi_set_last_error_from_errno ();
2033 if (!write_file (src_fd, dest_fd, &st, TRUE))
2039 dest_time.modtime = st.st_mtime;
2040 dest_time.actime = st.st_atime;
2041 ret_utime = utime (utf8_dest, &dest_time);
2042 if (ret_utime == -1)
2043 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file [%s] utime failed: %s", __func__, utf8_dest, strerror(errno));
2052 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2057 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: %s is NULL", __func__, arg_name);
2058 SetLastError (ERROR_INVALID_NAME);
2062 utf8_ret = mono_unicode_to_external (arg);
2063 if (utf8_ret == NULL) {
2064 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of %s returned NULL",
2065 __func__, arg_name);
2066 SetLastError (ERROR_INVALID_PARAMETER);
2074 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2075 const gunichar2 *backupFileName, guint32 replaceFlags,
2076 gpointer exclude, gpointer reserved)
2078 int result, backup_fd = -1,replaced_fd = -1;
2079 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2080 struct stat stBackup;
2081 gboolean ret = FALSE;
2083 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2085 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2086 goto replace_cleanup;
2087 if (backupFileName != NULL) {
2088 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2089 goto replace_cleanup;
2092 if (utf8_backupFileName) {
2093 // Open the backup file for read so we can restore the file if an error occurs.
2094 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2095 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2097 goto replace_cleanup;
2100 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2102 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2103 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2104 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2105 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2108 if (replaced_fd == -1)
2109 goto replace_cleanup;
2111 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2114 goto replace_cleanup;
2120 g_free (utf8_replacedFileName);
2121 g_free (utf8_replacementFileName);
2122 g_free (utf8_backupFileName);
2123 if (backup_fd != -1)
2125 if (replaced_fd != -1)
2126 close (replaced_fd);
2132 * @stdhandle: specifies the file descriptor
2134 * Returns a handle for stdin, stdout, or stderr. Always returns the
2135 * same handle for the same @stdhandle.
2137 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2140 static mono_mutex_t stdhandle_mutex;
2142 gpointer GetStdHandle(WapiStdHandle stdhandle)
2144 struct _WapiHandle_file *file_handle;
2151 case STD_INPUT_HANDLE:
2156 case STD_OUTPUT_HANDLE:
2161 case STD_ERROR_HANDLE:
2167 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unknown standard handle type", __func__);
2169 SetLastError (ERROR_INVALID_PARAMETER);
2170 return(INVALID_HANDLE_VALUE);
2173 handle = GINT_TO_POINTER (fd);
2175 thr_ret = mono_os_mutex_lock (&stdhandle_mutex);
2176 g_assert (thr_ret == 0);
2178 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2179 (gpointer *)&file_handle);
2181 /* Need to create this console handle */
2182 handle = _wapi_stdhandle_create (fd, name);
2184 if (handle == INVALID_HANDLE_VALUE) {
2185 SetLastError (ERROR_NO_MORE_FILES);
2189 /* Add a reference to this handle */
2190 _wapi_handle_ref (handle);
2194 thr_ret = mono_os_mutex_unlock (&stdhandle_mutex);
2195 g_assert (thr_ret == 0);
2202 * @handle: The file handle to read from. The handle must have
2203 * %GENERIC_READ access.
2204 * @buffer: The buffer to store read data in
2205 * @numbytes: The maximum number of bytes to read
2206 * @bytesread: The actual number of bytes read is stored here. This
2207 * value can be zero if the handle is positioned at the end of the
2209 * @overlapped: points to a required %WapiOverlapped structure if
2210 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2213 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2214 * function reads up to @numbytes bytes from the file from the current
2215 * file position, and stores them in @buffer. If there are not enough
2216 * bytes left in the file, just the amount available will be read.
2217 * The actual number of bytes read is stored in @bytesread.
2219 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2220 * file position is ignored and the read position is taken from data
2221 * in the @overlapped structure.
2223 * Return value: %TRUE if the read succeeds (even if no bytes were
2224 * read due to an attempt to read past the end of the file), %FALSE on
2227 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2228 guint32 *bytesread, WapiOverlapped *overlapped)
2230 WapiHandleType type;
2232 type = _wapi_handle_type (handle);
2234 if(io_ops[type].readfile==NULL) {
2235 SetLastError (ERROR_INVALID_HANDLE);
2239 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2245 * @handle: The file handle to write to. The handle must have
2246 * %GENERIC_WRITE access.
2247 * @buffer: The buffer to read data from.
2248 * @numbytes: The maximum number of bytes to write.
2249 * @byteswritten: The actual number of bytes written is stored here.
2250 * If the handle is positioned at the file end, the length of the file
2251 * is extended. This parameter may be %NULL.
2252 * @overlapped: points to a required %WapiOverlapped structure if
2253 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2256 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2257 * function writes up to @numbytes bytes from @buffer to the file at
2258 * the current file position. If @handle is positioned at the end of
2259 * the file, the file is extended. The actual number of bytes written
2260 * is stored in @byteswritten.
2262 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2263 * file position is ignored and the write position is taken from data
2264 * in the @overlapped structure.
2266 * Return value: %TRUE if the write succeeds, %FALSE on error.
2268 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2269 guint32 *byteswritten, WapiOverlapped *overlapped)
2271 WapiHandleType type;
2273 type = _wapi_handle_type (handle);
2275 if(io_ops[type].writefile==NULL) {
2276 SetLastError (ERROR_INVALID_HANDLE);
2280 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2286 * @handle: Handle to open file. The handle must have
2287 * %GENERIC_WRITE access.
2289 * Flushes buffers of the file and causes all unwritten data to
2292 * Return value: %TRUE on success, %FALSE otherwise.
2294 gboolean FlushFileBuffers(gpointer handle)
2296 WapiHandleType type;
2298 type = _wapi_handle_type (handle);
2300 if(io_ops[type].flushfile==NULL) {
2301 SetLastError (ERROR_INVALID_HANDLE);
2305 return(io_ops[type].flushfile (handle));
2310 * @handle: The file handle to set. The handle must have
2311 * %GENERIC_WRITE access.
2313 * Moves the end-of-file position to the current position of the file
2314 * pointer. This function is used to truncate or extend a file.
2316 * Return value: %TRUE on success, %FALSE otherwise.
2318 gboolean SetEndOfFile(gpointer handle)
2320 WapiHandleType type;
2322 type = _wapi_handle_type (handle);
2324 if (io_ops[type].setendoffile == NULL) {
2325 SetLastError (ERROR_INVALID_HANDLE);
2329 return(io_ops[type].setendoffile (handle));
2334 * @handle: The file handle to set. The handle must have
2335 * %GENERIC_READ or %GENERIC_WRITE access.
2336 * @movedistance: Low 32 bits of a signed value that specifies the
2337 * number of bytes to move the file pointer.
2338 * @highmovedistance: Pointer to the high 32 bits of a signed value
2339 * that specifies the number of bytes to move the file pointer, or
2341 * @method: The starting point for the file pointer move.
2343 * Sets the file pointer of an open file.
2345 * The distance to move the file pointer is calculated from
2346 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2347 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2348 * is the low 32 bits and @highmovedistance a pointer to the high 32
2349 * bits of a 64 bit signed value. A positive distance moves the file
2350 * pointer forward from the position specified by @method; a negative
2351 * distance moves the file pointer backward.
2353 * If the library is compiled without large file support,
2354 * @highmovedistance is ignored and its value is set to zero on a
2355 * successful return.
2357 * Return value: On success, the low 32 bits of the new file pointer.
2358 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2359 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2361 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2362 gint32 *highmovedistance, WapiSeekMethod method)
2364 WapiHandleType type;
2366 type = _wapi_handle_type (handle);
2368 if (io_ops[type].seek == NULL) {
2369 SetLastError (ERROR_INVALID_HANDLE);
2370 return(INVALID_SET_FILE_POINTER);
2373 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2379 * @handle: The file handle to test.
2381 * Finds the type of file @handle.
2383 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2384 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2385 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2386 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2388 WapiFileType GetFileType(gpointer handle)
2390 WapiHandleType type;
2392 if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2393 SetLastError (ERROR_INVALID_HANDLE);
2394 return(FILE_TYPE_UNKNOWN);
2397 type = _wapi_handle_type (handle);
2399 if (io_ops[type].getfiletype == NULL) {
2400 SetLastError (ERROR_INVALID_HANDLE);
2401 return(FILE_TYPE_UNKNOWN);
2404 return(io_ops[type].getfiletype ());
2409 * @handle: The file handle to query. The handle must have
2410 * %GENERIC_READ or %GENERIC_WRITE access.
2411 * @highsize: If non-%NULL, the high 32 bits of the file size are
2414 * Retrieves the size of the file @handle.
2416 * If the library is compiled without large file support, @highsize
2417 * has its value set to zero on a successful return.
2419 * Return value: On success, the low 32 bits of the file size. If
2420 * @highsize is non-%NULL then the high 32 bits of the file size are
2421 * stored here. On failure %INVALID_FILE_SIZE is returned.
2423 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2425 WapiHandleType type;
2427 type = _wapi_handle_type (handle);
2429 if (io_ops[type].getfilesize == NULL) {
2430 SetLastError (ERROR_INVALID_HANDLE);
2431 return(INVALID_FILE_SIZE);
2434 return(io_ops[type].getfilesize (handle, highsize));
2439 * @handle: The file handle to query. The handle must have
2440 * %GENERIC_READ access.
2441 * @create_time: Points to a %WapiFileTime structure to receive the
2442 * number of ticks since the epoch that file was created. May be
2444 * @last_access: Points to a %WapiFileTime structure to receive the
2445 * number of ticks since the epoch when file was last accessed. May be
2447 * @last_write: Points to a %WapiFileTime structure to receive the
2448 * number of ticks since the epoch when file was last written to. May
2451 * Finds the number of ticks since the epoch that the file referenced
2452 * by @handle was created, last accessed and last modified. A tick is
2453 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2456 * Create time isn't recorded on POSIX file systems or reported by
2457 * stat(2), so that time is guessed by returning the oldest of the
2460 * Return value: %TRUE on success, %FALSE otherwise.
2462 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2463 WapiFileTime *last_access, WapiFileTime *last_write)
2465 WapiHandleType type;
2467 type = _wapi_handle_type (handle);
2469 if (io_ops[type].getfiletime == NULL) {
2470 SetLastError (ERROR_INVALID_HANDLE);
2474 return(io_ops[type].getfiletime (handle, create_time, last_access,
2480 * @handle: The file handle to set. The handle must have
2481 * %GENERIC_WRITE access.
2482 * @create_time: Points to a %WapiFileTime structure that contains the
2483 * number of ticks since the epoch that the file was created. May be
2485 * @last_access: Points to a %WapiFileTime structure that contains the
2486 * number of ticks since the epoch when the file was last accessed.
2488 * @last_write: Points to a %WapiFileTime structure that contains the
2489 * number of ticks since the epoch when the file was last written to.
2492 * Sets the number of ticks since the epoch that the file referenced
2493 * by @handle was created, last accessed or last modified. A tick is
2494 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2497 * Create time isn't recorded on POSIX file systems, and is ignored.
2499 * Return value: %TRUE on success, %FALSE otherwise.
2501 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2502 const WapiFileTime *last_access,
2503 const WapiFileTime *last_write)
2505 WapiHandleType type;
2507 type = _wapi_handle_type (handle);
2509 if (io_ops[type].setfiletime == NULL) {
2510 SetLastError (ERROR_INVALID_HANDLE);
2514 return(io_ops[type].setfiletime (handle, create_time, last_access,
2518 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2519 * January 1 1601 GMT
2522 #define TICKS_PER_MILLISECOND 10000L
2523 #define TICKS_PER_SECOND 10000000L
2524 #define TICKS_PER_MINUTE 600000000L
2525 #define TICKS_PER_HOUR 36000000000LL
2526 #define TICKS_PER_DAY 864000000000LL
2528 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2530 static const guint16 mon_yday[2][13]={
2531 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2532 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2536 * FileTimeToSystemTime:
2537 * @file_time: Points to a %WapiFileTime structure that contains the
2538 * number of ticks to convert.
2539 * @system_time: Points to a %WapiSystemTime structure to receive the
2542 * Converts a tick count into broken-out time values.
2544 * Return value: %TRUE on success, %FALSE otherwise.
2546 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2547 WapiSystemTime *system_time)
2549 gint64 file_ticks, totaldays, rem, y;
2552 if(system_time==NULL) {
2553 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: system_time NULL", __func__);
2555 SetLastError (ERROR_INVALID_PARAMETER);
2559 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2560 file_time->dwLowDateTime;
2562 /* Really compares if file_ticks>=0x8000000000000000
2563 * (LLONG_MAX+1) but we're working with a signed value for the
2564 * year and day calculation to work later
2567 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file_time too big", __func__);
2569 SetLastError (ERROR_INVALID_PARAMETER);
2573 totaldays=(file_ticks / TICKS_PER_DAY);
2574 rem = file_ticks % TICKS_PER_DAY;
2575 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2577 system_time->wHour=rem/TICKS_PER_HOUR;
2578 rem %= TICKS_PER_HOUR;
2579 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2581 system_time->wMinute = rem / TICKS_PER_MINUTE;
2582 rem %= TICKS_PER_MINUTE;
2583 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2586 system_time->wSecond = rem / TICKS_PER_SECOND;
2587 rem %= TICKS_PER_SECOND;
2588 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2591 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2592 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Milliseconds: %d", __func__,
2593 system_time->wMilliseconds);
2595 /* January 1, 1601 was a Monday, according to Emacs calendar */
2596 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2597 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2599 /* This algorithm to find year and month given days from epoch
2604 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2605 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2607 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2608 /* Guess a corrected year, assuming 365 days per year */
2609 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2610 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld yg: %lld y: %lld", __func__,
2613 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2614 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2616 /* Adjust days and y to match the guessed year. */
2617 totaldays -= ((yg - y) * 365
2618 + LEAPS_THRU_END_OF (yg - 1)
2619 - LEAPS_THRU_END_OF (y - 1));
2620 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2622 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: y: %lld", __func__, y);
2625 system_time->wYear = y;
2626 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Year: %d", __func__, system_time->wYear);
2628 ip = mon_yday[isleap(y)];
2630 for(y=11; totaldays < ip[y]; --y) {
2634 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2636 system_time->wMonth = y + 1;
2637 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Month: %d", __func__, system_time->wMonth);
2639 system_time->wDay = totaldays + 1;
2640 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day: %d", __func__, system_time->wDay);
2645 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2647 struct _WapiHandle_find find_handle = {0};
2649 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2652 if (pattern == NULL) {
2653 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: pattern is NULL", __func__);
2655 SetLastError (ERROR_PATH_NOT_FOUND);
2656 return(INVALID_HANDLE_VALUE);
2659 utf8_pattern = mono_unicode_to_external (pattern);
2660 if (utf8_pattern == NULL) {
2661 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2663 SetLastError (ERROR_INVALID_NAME);
2664 return(INVALID_HANDLE_VALUE);
2667 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for [%s]", __func__, utf8_pattern);
2669 /* Figure out which bit of the pattern is the directory */
2670 dir_part = _wapi_dirname (utf8_pattern);
2671 entry_part = _wapi_basename (utf8_pattern);
2674 /* Don't do this check for now, it breaks if directories
2675 * really do have metachars in their names (see bug 58116).
2676 * FIXME: Figure out a better solution to keep some checks...
2678 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2679 SetLastError (ERROR_INVALID_NAME);
2681 g_free (entry_part);
2682 g_free (utf8_pattern);
2683 return(INVALID_HANDLE_VALUE);
2687 /* The pattern can specify a directory or a set of files.
2689 * The pattern can have wildcard characters ? and *, but only
2690 * in the section after the last directory delimiter. (Return
2691 * ERROR_INVALID_NAME if there are wildcards in earlier path
2692 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2693 * means "match one character", "??" seems to mean "match one
2694 * or two characters", "???" seems to mean "match one, two or
2695 * three characters", etc. Windows will also try and match
2696 * the mangled "short name" of files, so 8 character patterns
2697 * with wildcards will show some surprising results.
2699 * All the written documentation I can find says that '?'
2700 * should only match one character, and doesn't mention '??',
2701 * '???' etc. I'm going to assume that the strict behaviour
2702 * (ie '???' means three and only three characters) is the
2703 * correct one, because that lets me use fnmatch(3) rather
2704 * than mess around with regexes.
2707 find_handle.namelist = NULL;
2708 result = _wapi_io_scandir (dir_part, entry_part,
2709 &find_handle.namelist);
2712 /* No files, which windows seems to call
2715 SetLastError (ERROR_FILE_NOT_FOUND);
2716 g_free (utf8_pattern);
2717 g_free (entry_part);
2719 return (INVALID_HANDLE_VALUE);
2723 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2724 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: scandir error: %s", __func__, g_strerror (errno));
2725 g_free (utf8_pattern);
2726 g_free (entry_part);
2728 return (INVALID_HANDLE_VALUE);
2731 g_free (utf8_pattern);
2732 g_free (entry_part);
2734 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Got %d matches", __func__, result);
2736 find_handle.dir_part = dir_part;
2737 find_handle.num = result;
2738 find_handle.count = 0;
2740 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2741 if (handle == _WAPI_HANDLE_INVALID) {
2742 g_warning ("%s: error creating find handle", __func__);
2744 g_free (entry_part);
2745 g_free (utf8_pattern);
2746 SetLastError (ERROR_GEN_FAILURE);
2748 return(INVALID_HANDLE_VALUE);
2751 if (handle != INVALID_HANDLE_VALUE &&
2752 !FindNextFile (handle, find_data)) {
2754 SetLastError (ERROR_NO_MORE_FILES);
2755 handle = INVALID_HANDLE_VALUE;
2761 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2763 struct _WapiHandle_find *find_handle;
2765 struct stat buf, linkbuf;
2768 gchar *utf8_filename, *utf8_basename;
2769 gunichar2 *utf16_basename;
2773 gboolean ret = FALSE;
2775 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2776 (gpointer *)&find_handle);
2778 g_warning ("%s: error looking up find handle %p", __func__,
2780 SetLastError (ERROR_INVALID_HANDLE);
2784 thr_ret = _wapi_handle_lock_handle (handle);
2785 g_assert (thr_ret == 0);
2788 if (find_handle->count >= find_handle->num) {
2789 SetLastError (ERROR_NO_MORE_FILES);
2793 /* stat next match */
2795 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2797 result = _wapi_stat (filename, &buf);
2798 if (result == -1 && errno == ENOENT) {
2799 /* Might be a dangling symlink */
2800 result = _wapi_lstat (filename, &buf);
2804 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: stat failed: %s", __func__, filename);
2810 #ifndef __native_client__
2811 result = _wapi_lstat (filename, &linkbuf);
2813 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lstat failed: %s", __func__, filename);
2820 utf8_filename = mono_utf8_from_external (filename);
2821 if (utf8_filename == NULL) {
2822 /* We couldn't turn this filename into utf8 (eg the
2823 * encoding of the name wasn't convertible), so just
2826 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2833 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Found [%s]", __func__, utf8_filename);
2835 /* fill data block */
2837 if (buf.st_mtime < buf.st_ctime)
2838 create_time = buf.st_mtime;
2840 create_time = buf.st_ctime;
2842 #ifdef __native_client__
2843 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, NULL);
2845 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2848 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2849 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2850 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2852 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2853 find_data->nFileSizeHigh = 0;
2854 find_data->nFileSizeLow = 0;
2856 find_data->nFileSizeHigh = buf.st_size >> 32;
2857 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2860 find_data->dwReserved0 = 0;
2861 find_data->dwReserved1 = 0;
2863 utf8_basename = _wapi_basename (utf8_filename);
2864 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2866 if(utf16_basename==NULL) {
2867 g_free (utf8_basename);
2868 g_free (utf8_filename);
2873 /* utf16 is 2 * utf8 */
2876 memset (find_data->cFileName, '\0', (MAX_PATH*2));
2878 /* Truncating a utf16 string like this might leave the last
2881 memcpy (find_data->cFileName, utf16_basename,
2882 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
2884 find_data->cAlternateFileName [0] = 0; /* not used */
2886 g_free (utf8_basename);
2887 g_free (utf8_filename);
2888 g_free (utf16_basename);
2891 thr_ret = _wapi_handle_unlock_handle (handle);
2892 g_assert (thr_ret == 0);
2899 * @wapi_handle: the find handle to close.
2901 * Closes find handle @wapi_handle
2903 * Return value: %TRUE on success, %FALSE otherwise.
2905 gboolean FindClose (gpointer handle)
2907 struct _WapiHandle_find *find_handle;
2911 if (handle == NULL) {
2912 SetLastError (ERROR_INVALID_HANDLE);
2916 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2917 (gpointer *)&find_handle);
2919 g_warning ("%s: error looking up find handle %p", __func__,
2921 SetLastError (ERROR_INVALID_HANDLE);
2925 thr_ret = _wapi_handle_lock_handle (handle);
2926 g_assert (thr_ret == 0);
2928 g_strfreev (find_handle->namelist);
2929 g_free (find_handle->dir_part);
2931 thr_ret = _wapi_handle_unlock_handle (handle);
2932 g_assert (thr_ret == 0);
2934 _wapi_handle_unref (handle);
2941 * @name: a pointer to a NULL-terminated unicode string, that names
2942 * the directory to be created.
2943 * @security: ignored for now
2945 * Creates directory @name
2947 * Return value: %TRUE on success, %FALSE otherwise.
2949 gboolean CreateDirectory (const gunichar2 *name,
2950 WapiSecurityAttributes *security)
2956 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2958 SetLastError (ERROR_INVALID_NAME);
2962 utf8_name = mono_unicode_to_external (name);
2963 if (utf8_name == NULL) {
2964 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2966 SetLastError (ERROR_INVALID_NAME);
2970 result = _wapi_mkdir (utf8_name, 0777);
2977 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2984 * @name: a pointer to a NULL-terminated unicode string, that names
2985 * the directory to be removed.
2987 * Removes directory @name
2989 * Return value: %TRUE on success, %FALSE otherwise.
2991 gboolean RemoveDirectory (const gunichar2 *name)
2997 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2999 SetLastError (ERROR_INVALID_NAME);
3003 utf8_name = mono_unicode_to_external (name);
3004 if (utf8_name == NULL) {
3005 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3007 SetLastError (ERROR_INVALID_NAME);
3011 result = _wapi_rmdir (utf8_name);
3013 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3024 * GetFileAttributes:
3025 * @name: a pointer to a NULL-terminated unicode filename.
3027 * Gets the attributes for @name;
3029 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3031 guint32 GetFileAttributes (const gunichar2 *name)
3034 struct stat buf, linkbuf;
3039 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3041 SetLastError (ERROR_INVALID_NAME);
3045 utf8_name = mono_unicode_to_external (name);
3046 if (utf8_name == NULL) {
3047 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3049 SetLastError (ERROR_INVALID_PARAMETER);
3050 return (INVALID_FILE_ATTRIBUTES);
3053 result = _wapi_stat (utf8_name, &buf);
3054 if (result == -1 && errno == ENOENT) {
3055 /* Might be a dangling symlink... */
3056 result = _wapi_lstat (utf8_name, &buf);
3060 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3062 return (INVALID_FILE_ATTRIBUTES);
3065 #ifndef __native_client__
3066 result = _wapi_lstat (utf8_name, &linkbuf);
3068 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3070 return (INVALID_FILE_ATTRIBUTES);
3074 #ifdef __native_client__
3075 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, NULL);
3077 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3086 * GetFileAttributesEx:
3087 * @name: a pointer to a NULL-terminated unicode filename.
3088 * @level: must be GetFileExInfoStandard
3089 * @info: pointer to a WapiFileAttributesData structure
3091 * Gets attributes, size and filetimes for @name;
3093 * Return value: %TRUE on success, %FALSE on failure
3095 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3098 WapiFileAttributesData *data;
3100 struct stat buf, linkbuf;
3104 if (level != GetFileExInfoStandard) {
3105 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: info level %d not supported.", __func__,
3108 SetLastError (ERROR_INVALID_PARAMETER);
3113 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3115 SetLastError (ERROR_INVALID_NAME);
3119 utf8_name = mono_unicode_to_external (name);
3120 if (utf8_name == NULL) {
3121 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3123 SetLastError (ERROR_INVALID_PARAMETER);
3127 result = _wapi_stat (utf8_name, &buf);
3128 if (result == -1 && errno == ENOENT) {
3129 /* Might be a dangling symlink... */
3130 result = _wapi_lstat (utf8_name, &buf);
3134 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3139 result = _wapi_lstat (utf8_name, &linkbuf);
3141 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3146 /* fill data block */
3148 data = (WapiFileAttributesData *)info;
3150 if (buf.st_mtime < buf.st_ctime)
3151 create_time = buf.st_mtime;
3153 create_time = buf.st_ctime;
3155 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3161 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3162 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3163 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3165 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3166 data->nFileSizeHigh = 0;
3167 data->nFileSizeLow = 0;
3170 data->nFileSizeHigh = buf.st_size >> 32;
3171 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3179 * @name: name of file
3180 * @attrs: attributes to set
3182 * Changes the attributes on a named file.
3184 * Return value: %TRUE on success, %FALSE on failure.
3186 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3188 /* FIXME: think of something clever to do on unix */
3194 * Currently we only handle one *internal* case, with a value that is
3195 * not standard: 0x80000000, which means `set executable bit'
3199 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3201 SetLastError (ERROR_INVALID_NAME);
3205 utf8_name = mono_unicode_to_external (name);
3206 if (utf8_name == NULL) {
3207 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3209 SetLastError (ERROR_INVALID_NAME);
3213 result = _wapi_stat (utf8_name, &buf);
3214 if (result == -1 && errno == ENOENT) {
3215 /* Might be a dangling symlink... */
3216 result = _wapi_lstat (utf8_name, &buf);
3220 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3225 /* Contrary to the documentation, ms allows NORMAL to be
3226 * specified along with other attributes, so dont bother to
3227 * catch that case here.
3229 if (attrs & FILE_ATTRIBUTE_READONLY) {
3230 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWUSR | S_IWOTH | S_IWGRP));
3232 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWUSR);
3235 /* Ignore the other attributes for now */
3237 if (attrs & 0x80000000){
3238 mode_t exec_mask = 0;
3240 if ((buf.st_mode & S_IRUSR) != 0)
3241 exec_mask |= S_IXUSR;
3243 if ((buf.st_mode & S_IRGRP) != 0)
3244 exec_mask |= S_IXGRP;
3246 if ((buf.st_mode & S_IROTH) != 0)
3247 exec_mask |= S_IXOTH;
3249 result = chmod (utf8_name, buf.st_mode | exec_mask);
3251 /* Don't bother to reset executable (might need to change this
3261 * GetCurrentDirectory
3262 * @length: size of the buffer
3263 * @buffer: pointer to buffer that recieves path
3265 * Retrieves the current directory for the current process.
3267 * Return value: number of characters in buffer on success, zero on failure
3269 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3271 gunichar2 *utf16_path;
3275 #ifdef __native_client__
3276 gchar *path = g_get_current_dir ();
3277 if (length < strlen(path) + 1 || path == NULL)
3279 memcpy (buffer, path, strlen(path) + 1);
3281 if (getcwd ((char*)buffer, length) == NULL) {
3282 if (errno == ERANGE) { /*buffer length is not big enough */
3283 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*/
3286 utf16_path = mono_unicode_from_external (path, &bytes);
3287 g_free (utf16_path);
3291 _wapi_set_last_error_from_errno ();
3296 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3297 count = (bytes/2)+1;
3298 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3300 /* Add the terminator */
3301 memset (buffer, '\0', bytes+2);
3302 memcpy (buffer, utf16_path, bytes);
3304 g_free (utf16_path);
3310 * SetCurrentDirectory
3311 * @path: path to new directory
3313 * Changes the directory path for the current process.
3315 * Return value: %TRUE on success, %FALSE on failure.
3317 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3323 SetLastError (ERROR_INVALID_PARAMETER);
3327 utf8_path = mono_unicode_to_external (path);
3328 if (_wapi_chdir (utf8_path) != 0) {
3329 _wapi_set_last_error_from_errno ();
3339 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3340 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3342 struct _WapiHandle_file pipe_read_handle = {0};
3343 struct _WapiHandle_file pipe_write_handle = {0};
3344 gpointer read_handle;
3345 gpointer write_handle;
3349 mono_once (&io_ops_once, io_ops_init);
3351 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Creating pipe", __func__);
3355 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error creating pipe: %s", __func__,
3358 _wapi_set_last_error_from_errno ();
3362 if (filedes[0] >= _wapi_fd_reserve ||
3363 filedes[1] >= _wapi_fd_reserve) {
3364 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
3366 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3374 /* filedes[0] is open for reading, filedes[1] for writing */
3376 pipe_read_handle.fd = filedes [0];
3377 pipe_read_handle.fileaccess = GENERIC_READ;
3378 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3380 if (read_handle == _WAPI_HANDLE_INVALID) {
3381 g_warning ("%s: error creating pipe read handle", __func__);
3384 SetLastError (ERROR_GEN_FAILURE);
3389 pipe_write_handle.fd = filedes [1];
3390 pipe_write_handle.fileaccess = GENERIC_WRITE;
3391 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3392 &pipe_write_handle);
3393 if (write_handle == _WAPI_HANDLE_INVALID) {
3394 g_warning ("%s: error creating pipe write handle", __func__);
3395 _wapi_handle_unref (read_handle);
3399 SetLastError (ERROR_GEN_FAILURE);
3404 *readpipe = read_handle;
3405 *writepipe = write_handle;
3407 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning pipe: read handle %p, write handle %p",
3408 __func__, read_handle, write_handle);
3413 #ifdef HAVE_GETFSSTAT
3414 /* Darwin has getfsstat */
3415 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3417 struct statfs *stats;
3420 glong length, total = 0;
3422 n = getfsstat (NULL, 0, MNT_NOWAIT);
3425 size = n * sizeof (struct statfs);
3426 stats = (struct statfs *) g_malloc (size);
3429 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3433 for (i = 0; i < n; i++){
3434 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3435 if (total + length < len){
3436 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3437 buf [total+length] = 0;
3440 total += length + 1;
3449 /* In-place octal sequence replacement */
3451 unescape_octal (gchar *str)
3460 while (*rptr != '\0') {
3461 if (*rptr == '\\') {
3464 c = (*(rptr++) - '0') << 6;
3465 c += (*(rptr++) - '0') << 3;
3466 c += *(rptr++) - '0';
3468 } else if (wptr != rptr) {
3476 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3479 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3480 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3481 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3486 guint32 buffer_index;
3487 guint32 mountpoint_index;
3488 guint32 field_number;
3489 guint32 allocated_size;
3490 guint32 fsname_index;
3491 guint32 fstype_index;
3492 gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3493 gchar *mountpoint_allocated;
3494 gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3495 gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3496 gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3499 gboolean check_mount_source;
3500 } LinuxMountInfoParseState;
3502 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3503 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3504 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3505 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3507 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3511 LinuxMountInfoParseState state;
3512 gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3514 memset (buf, 0, len * sizeof (gunichar2));
3515 fd = open ("/proc/self/mountinfo", O_RDONLY);
3517 parser = GetLogicalDriveStrings_MountInfo;
3519 fd = open ("/proc/mounts", O_RDONLY);
3521 parser = GetLogicalDriveStrings_Mounts;
3525 ret = GetLogicalDriveStrings_Mtab (len, buf);
3529 memset (&state, 0, sizeof (LinuxMountInfoParseState));
3530 state.field_number = 1;
3531 state.delimiter = ' ';
3533 while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3534 state.buffer_index = 0;
3536 while ((*parser)(len, buf, &state)) {
3537 if (state.buffer [state.buffer_index] == '\n') {
3538 gboolean quit = add_drive_string (len, buf, &state);
3539 state.field_number = 1;
3540 state.buffer_index++;
3541 if (state.mountpoint_allocated) {
3542 g_free (state.mountpoint_allocated);
3543 state.mountpoint_allocated = NULL;
3560 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3564 if (state->field_number == 1)
3565 state->check_mount_source = TRUE;
3567 while (state->buffer_index < (guint32)state->nbytes) {
3568 if (state->buffer [state->buffer_index] == state->delimiter) {
3569 state->field_number++;
3570 switch (state->field_number) {
3572 state->mountpoint_index = 0;
3576 if (state->mountpoint_allocated)
3577 state->mountpoint_allocated [state->mountpoint_index] = 0;
3579 state->mountpoint [state->mountpoint_index] = 0;
3583 ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3585 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3587 state->buffer_index = state->nbytes;
3590 state->buffer_index++;
3592 } else if (state->buffer [state->buffer_index] == '\n')
3595 switch (state->field_number) {
3597 if (state->check_mount_source) {
3598 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3599 /* We can ignore the rest, it's a device
3601 state->check_mount_source = FALSE;
3602 state->fsname [state->fsname_index++] = '/';
3605 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3606 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3611 append_to_mountpoint (state);
3615 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3616 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3620 state->buffer_index++;
3626 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3628 while (state->buffer_index < (guint32)state->nbytes) {
3629 if (state->buffer [state->buffer_index] == state->delimiter) {
3630 state->field_number++;
3631 switch (state->field_number) {
3633 state->mountpoint_index = 0;
3637 if (state->mountpoint_allocated)
3638 state->mountpoint_allocated [state->mountpoint_index] = 0;
3640 state->mountpoint [state->mountpoint_index] = 0;
3644 state->delimiter = '-';
3648 state->delimiter = ' ';
3652 state->check_mount_source = TRUE;
3655 state->buffer_index++;
3657 } else if (state->buffer [state->buffer_index] == '\n')
3660 switch (state->field_number) {
3662 append_to_mountpoint (state);
3666 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3667 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3671 if (state->check_mount_source) {
3672 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3673 /* We can ignore the rest, it's a device
3675 state->check_mount_source = FALSE;
3676 state->fsname [state->fsname_index++] = '/';
3679 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3680 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3685 state->buffer_index++;
3692 append_to_mountpoint (LinuxMountInfoParseState *state)
3694 gchar ch = state->buffer [state->buffer_index];
3695 if (state->mountpoint_allocated) {
3696 if (state->mountpoint_index >= state->allocated_size) {
3697 guint32 newsize = (state->allocated_size << 1) + 1;
3698 gchar *newbuf = (gchar *)g_malloc0 (newsize * sizeof (gchar));
3700 memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3701 g_free (state->mountpoint_allocated);
3702 state->mountpoint_allocated = newbuf;
3703 state->allocated_size = newsize;
3705 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3707 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3708 state->allocated_size = (state->mountpoint_index << 1) + 1;
3709 state->mountpoint_allocated = (gchar *)g_malloc0 (state->allocated_size * sizeof (gchar));
3710 memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3711 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3713 state->mountpoint [state->mountpoint_index++] = ch;
3718 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3720 gboolean quit = FALSE;
3721 gboolean ignore_entry;
3723 if (state->fsname_index == 1 && state->fsname [0] == '/')
3724 ignore_entry = FALSE;
3725 else if (memcmp ("overlay", state->fsname, state->fsname_index) == 0 ||
3726 memcmp ("aufs", state->fstype, state->fstype_index) == 0) {
3727 /* Don't ignore overlayfs and aufs - these might be used on Docker
3728 * (https://bugzilla.xamarin.com/show_bug.cgi?id=31021) */
3729 ignore_entry = FALSE;
3730 } else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0) {
3731 ignore_entry = TRUE;
3732 } else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3733 /* Ignore GNOME's gvfs */
3734 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3735 ignore_entry = TRUE;
3737 ignore_entry = FALSE;
3738 } else if (state->fstype_index == 3 && memcmp ("nfs", state->fstype, state->fstype_index) == 0)
3739 ignore_entry = FALSE;
3741 ignore_entry = TRUE;
3743 if (!ignore_entry) {
3746 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3748 unescape_octal (mountpoint);
3749 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3750 if (state->total + length + 1 > len) {
3752 state->total = len * 2;
3755 memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3756 state->total += length;
3760 state->fsname_index = 0;
3761 state->fstype_index = 0;
3767 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3769 return GetLogicalDriveStrings_Mtab (len, buf);
3773 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3776 gunichar2 *ptr, *dir;
3777 glong length, total = 0;
3781 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3786 /* Sigh, mntent and friends don't work well.
3787 * It stops on the first line that doesn't begin with a '/'.
3788 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3789 fp = fopen ("/etc/mtab", "rt");
3791 fp = fopen ("/etc/mnttab", "rt");
3797 while (fgets (buffer, 512, fp) != NULL) {
3801 splitted = g_strsplit (buffer, " ", 0);
3802 if (!*splitted || !*(splitted + 1)) {
3803 g_strfreev (splitted);
3807 unescape_octal (*(splitted + 1));
3808 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3809 g_strfreev (splitted);
3810 if (total + length + 1 > len) {
3813 return len * 2; /* guess */
3816 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3818 total += length + 1;
3823 /* Commented out, does not work with my mtab!!! - Gonz */
3824 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3828 gunichar2 *ptr, *dir;
3829 glong len, total = 0;
3832 fp = setmntent ("/etc/mtab", "rt");
3834 fp = setmntent ("/etc/mnttab", "rt");
3840 while ((mnt = getmntent (fp)) != NULL) {
3841 g_print ("GOT %s\n", mnt->mnt_dir);
3842 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3843 if (total + len + 1 > len) {
3844 return len * 2; /* guess */
3847 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3859 #if defined(HAVE_STATVFS) || defined(HAVE_STATFS)
3860 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3861 WapiULargeInteger *total_number_of_bytes,
3862 WapiULargeInteger *total_number_of_free_bytes)
3865 struct statvfs fsstat;
3866 #elif defined(HAVE_STATFS)
3867 struct statfs fsstat;
3869 gboolean isreadonly;
3870 gchar *utf8_path_name;
3872 unsigned long block_size;
3874 if (path_name == NULL) {
3875 utf8_path_name = g_strdup (g_get_current_dir());
3876 if (utf8_path_name == NULL) {
3877 SetLastError (ERROR_DIRECTORY);
3882 utf8_path_name = mono_unicode_to_external (path_name);
3883 if (utf8_path_name == NULL) {
3884 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3886 SetLastError (ERROR_INVALID_NAME);
3893 ret = statvfs (utf8_path_name, &fsstat);
3894 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
3895 block_size = fsstat.f_frsize;
3896 #elif defined(HAVE_STATFS)
3897 ret = statfs (utf8_path_name, &fsstat);
3898 #if defined (MNT_RDONLY)
3899 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
3900 #elif defined (MS_RDONLY)
3901 isreadonly = ((fsstat.f_flags & MS_RDONLY) == MS_RDONLY);
3903 block_size = fsstat.f_bsize;
3905 } while(ret == -1 && errno == EINTR);
3907 g_free(utf8_path_name);
3910 _wapi_set_last_error_from_errno ();
3911 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: statvfs failed: %s", __func__, strerror (errno));
3915 /* total number of free bytes for non-root */
3916 if (free_bytes_avail != NULL) {
3918 free_bytes_avail->QuadPart = 0;
3921 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
3925 /* total number of bytes available for non-root */
3926 if (total_number_of_bytes != NULL) {
3927 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
3930 /* total number of bytes available for root */
3931 if (total_number_of_free_bytes != NULL) {
3933 total_number_of_free_bytes->QuadPart = 0;
3936 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
3943 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3944 WapiULargeInteger *total_number_of_bytes,
3945 WapiULargeInteger *total_number_of_free_bytes)
3947 if (free_bytes_avail != NULL) {
3948 free_bytes_avail->QuadPart = (guint64) -1;
3951 if (total_number_of_bytes != NULL) {
3952 total_number_of_bytes->QuadPart = (guint64) -1;
3955 if (total_number_of_free_bytes != NULL) {
3956 total_number_of_free_bytes->QuadPart = (guint64) -1;
3964 * General Unix support
3969 const long fstypeid;
3971 const gchar* fstype;
3974 static _wapi_drive_type _wapi_drive_types[] = {
3976 { DRIVE_REMOTE, "afp" },
3977 { DRIVE_REMOTE, "autofs" },
3978 { DRIVE_CDROM, "cddafs" },
3979 { DRIVE_CDROM, "cd9660" },
3980 { DRIVE_RAMDISK, "devfs" },
3981 { DRIVE_FIXED, "exfat" },
3982 { DRIVE_RAMDISK, "fdesc" },
3983 { DRIVE_REMOTE, "ftp" },
3984 { DRIVE_FIXED, "hfs" },
3985 { DRIVE_FIXED, "msdos" },
3986 { DRIVE_REMOTE, "nfs" },
3987 { DRIVE_FIXED, "ntfs" },
3988 { DRIVE_REMOTE, "smbfs" },
3989 { DRIVE_FIXED, "udf" },
3990 { DRIVE_REMOTE, "webdav" },
3991 { DRIVE_UNKNOWN, NULL }
3993 { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
3994 { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
3995 { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
3996 { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
3997 { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
3998 { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
3999 { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
4000 { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
4001 { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
4002 { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
4003 { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
4004 { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
4005 { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
4006 { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
4007 { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
4008 { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
4009 { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
4010 { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4011 { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4012 { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4013 { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4014 { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4015 { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4016 { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4017 { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4018 { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4019 { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4020 { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4021 { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4022 { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4023 { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4024 { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4025 { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4026 { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4027 { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4028 { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4029 { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4030 { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4031 { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4032 { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4033 { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4034 { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4035 { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4036 { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4037 { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4038 { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4039 { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4040 { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4041 { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4042 { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4043 { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4044 { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4045 { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4046 { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4047 { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4048 { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4049 { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4050 { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4051 { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4052 { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4053 { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4054 { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4055 { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4056 { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4057 { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4058 { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4059 { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4060 { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4061 { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4062 { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4063 { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4064 { DRIVE_UNKNOWN, 0, NULL}
4066 { DRIVE_RAMDISK, "ramfs" },
4067 { DRIVE_RAMDISK, "tmpfs" },
4068 { DRIVE_RAMDISK, "proc" },
4069 { DRIVE_RAMDISK, "sysfs" },
4070 { DRIVE_RAMDISK, "debugfs" },
4071 { DRIVE_RAMDISK, "devpts" },
4072 { DRIVE_RAMDISK, "securityfs" },
4073 { DRIVE_CDROM, "iso9660" },
4074 { DRIVE_FIXED, "ext2" },
4075 { DRIVE_FIXED, "ext3" },
4076 { DRIVE_FIXED, "ext4" },
4077 { DRIVE_FIXED, "sysv" },
4078 { DRIVE_FIXED, "reiserfs" },
4079 { DRIVE_FIXED, "ufs" },
4080 { DRIVE_FIXED, "vfat" },
4081 { DRIVE_FIXED, "msdos" },
4082 { DRIVE_FIXED, "udf" },
4083 { DRIVE_FIXED, "hfs" },
4084 { DRIVE_FIXED, "hpfs" },
4085 { DRIVE_FIXED, "qnx4" },
4086 { DRIVE_FIXED, "ntfs" },
4087 { DRIVE_FIXED, "ntfs-3g" },
4088 { DRIVE_REMOTE, "smbfs" },
4089 { DRIVE_REMOTE, "fuse" },
4090 { DRIVE_REMOTE, "nfs" },
4091 { DRIVE_REMOTE, "nfs4" },
4092 { DRIVE_REMOTE, "cifs" },
4093 { DRIVE_REMOTE, "ncpfs" },
4094 { DRIVE_REMOTE, "coda" },
4095 { DRIVE_REMOTE, "afs" },
4096 { DRIVE_UNKNOWN, NULL }
4101 static guint32 _wapi_get_drive_type(long f_type)
4103 _wapi_drive_type *current;
4105 current = &_wapi_drive_types[0];
4106 while (current->drive_type != DRIVE_UNKNOWN) {
4107 if (current->fstypeid == f_type)
4108 return current->drive_type;
4112 return DRIVE_UNKNOWN;
4115 static guint32 _wapi_get_drive_type(const gchar* fstype)
4117 _wapi_drive_type *current;
4119 current = &_wapi_drive_types[0];
4120 while (current->drive_type != DRIVE_UNKNOWN) {
4121 if (strcmp (current->fstype, fstype) == 0)
4127 return current->drive_type;
4131 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4133 GetDriveTypeFromPath (const char *utf8_root_path_name)
4137 if (statfs (utf8_root_path_name, &buf) == -1)
4138 return DRIVE_UNKNOWN;
4140 return _wapi_get_drive_type (buf.f_fstypename);
4142 return _wapi_get_drive_type (buf.f_type);
4147 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4154 fp = fopen ("/etc/mtab", "rt");
4156 fp = fopen ("/etc/mnttab", "rt");
4158 return(DRIVE_UNKNOWN);
4161 drive_type = DRIVE_NO_ROOT_DIR;
4162 while (fgets (buffer, 512, fp) != NULL) {
4163 splitted = g_strsplit (buffer, " ", 0);
4164 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4165 g_strfreev (splitted);
4169 /* compare given root_path_name with the one from mtab,
4170 if length of utf8_root_path_name is zero it must be the root dir */
4171 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4172 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4173 drive_type = _wapi_get_drive_type (*(splitted + 2));
4174 /* it is possible this path might be mounted again with
4175 a known type...keep looking */
4176 if (drive_type != DRIVE_UNKNOWN) {
4177 g_strfreev (splitted);
4182 g_strfreev (splitted);
4190 guint32 GetDriveType(const gunichar2 *root_path_name)
4192 gchar *utf8_root_path_name;
4195 if (root_path_name == NULL) {
4196 utf8_root_path_name = g_strdup (g_get_current_dir());
4197 if (utf8_root_path_name == NULL) {
4198 return(DRIVE_NO_ROOT_DIR);
4202 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4203 if (utf8_root_path_name == NULL) {
4204 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4205 return(DRIVE_NO_ROOT_DIR);
4208 /* strip trailing slash for compare below */
4209 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4210 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4213 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4214 g_free (utf8_root_path_name);
4216 return (drive_type);
4219 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__) || defined(__FreeBSD_kernel__)
4221 get_fstypename (gchar *utfpath)
4223 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4226 _wapi_drive_type *current;
4228 if (statfs (utfpath, &stat) == -1)
4231 return g_strdup (stat.f_fstypename);
4233 current = &_wapi_drive_types[0];
4234 while (current->drive_type != DRIVE_UNKNOWN) {
4235 if (stat.f_type == current->fstypeid)
4236 return g_strdup (current->fstype);
4246 /* Linux has struct statfs which has a different layout */
4248 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4252 gboolean status = FALSE;
4255 // We only support getting the file system type
4256 if (fsbuffer == NULL)
4259 utfpath = mono_unicode_to_external (path);
4260 if ((fstypename = get_fstypename (utfpath)) != NULL){
4261 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4262 if (ret != NULL && len < fsbuffersize){
4263 memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4269 g_free (fstypename);
4278 _wapi_io_init (void)
4280 mono_os_mutex_init (&stdhandle_mutex);