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/io-private.h>
42 #include <mono/io-layer/timefuncs-private.h>
43 #include <mono/io-layer/io-portability.h>
44 #include <mono/io-layer/io-trace.h>
45 #include <mono/utils/strenc.h>
46 #include <mono/utils/mono-once.h>
47 #include <mono/utils/mono-logger-internals.h>
48 #include <mono/utils/w32handle.h>
51 * If SHM is disabled, this will point to a hash of _WapiFileShare structures, otherwise
52 * it will be NULL. We use this instead of _wapi_fileshare_layout to avoid allocating a
55 static GHashTable *file_share_hash;
56 static mono_mutex_t file_share_hash_mutex;
58 #define file_share_hash_lock() mono_os_mutex_lock (&file_share_hash_mutex)
59 #define file_share_hash_unlock() mono_os_mutex_unlock (&file_share_hash_mutex)
62 _wapi_handle_share_release (_WapiFileShare *share_info)
66 g_assert (share_info->handle_refs > 0);
68 /* Prevent new entries racing with us */
69 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_FILESHARE);
70 g_assert(thr_ret == 0);
72 if (InterlockedDecrement ((gint32 *)&share_info->handle_refs) == 0) {
73 file_share_hash_lock ();
74 g_hash_table_remove (file_share_hash, share_info);
75 file_share_hash_unlock ();
78 thr_ret = _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_FILESHARE);
79 g_assert (thr_ret == 0);
83 wapi_share_info_equal (gconstpointer ka, gconstpointer kb)
85 const _WapiFileShare *s1 = (const _WapiFileShare *)ka;
86 const _WapiFileShare *s2 = (const _WapiFileShare *)kb;
88 return (s1->device == s2->device && s1->inode == s2->inode) ? 1 : 0;
92 wapi_share_info_hash (gconstpointer data)
94 const _WapiFileShare *s = (const _WapiFileShare *)data;
100 _wapi_handle_get_or_set_share (guint64 device, guint64 inode, guint32 new_sharemode, guint32 new_access,
101 guint32 *old_sharemode, guint32 *old_access, struct _WapiFileShare **share_info)
103 struct _WapiFileShare *file_share;
105 gboolean exists = FALSE;
107 /* Prevent new entries racing with us */
108 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_FILESHARE);
109 g_assert (thr_ret == 0);
114 * Instead of allocating a 4MB array, we use a hash table to keep track of this
115 * info. This is needed even if SHM is disabled, to track sharing inside
116 * the current process.
118 if (!file_share_hash) {
119 file_share_hash = g_hash_table_new_full (wapi_share_info_hash, wapi_share_info_equal, NULL, g_free);
120 mono_os_mutex_init_recursive (&file_share_hash_mutex);
126 file_share_hash_lock ();
128 file_share = (_WapiFileShare *)g_hash_table_lookup (file_share_hash, &tmp);
130 *old_sharemode = file_share->sharemode;
131 *old_access = file_share->access;
132 *share_info = file_share;
134 InterlockedIncrement ((gint32 *)&file_share->handle_refs);
137 file_share = g_new0 (_WapiFileShare, 1);
139 file_share->device = device;
140 file_share->inode = inode;
141 file_share->opened_by_pid = wapi_getpid ();
142 file_share->sharemode = new_sharemode;
143 file_share->access = new_access;
144 file_share->handle_refs = 1;
145 *share_info = file_share;
147 g_hash_table_insert (file_share_hash, file_share, file_share);
150 file_share_hash_unlock ();
152 thr_ret = _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_FILESHARE);
153 g_assert (thr_ret == 0);
158 static void file_close (gpointer handle, gpointer data);
159 static void file_details (gpointer data);
160 static const gchar* file_typename (void);
161 static gsize file_typesize (void);
162 static WapiFileType file_getfiletype(void);
163 static gboolean file_read(gpointer handle, gpointer buffer,
164 guint32 numbytes, guint32 *bytesread,
165 WapiOverlapped *overlapped);
166 static gboolean file_write(gpointer handle, gconstpointer buffer,
167 guint32 numbytes, guint32 *byteswritten,
168 WapiOverlapped *overlapped);
169 static gboolean file_flush(gpointer handle);
170 static guint32 file_seek(gpointer handle, gint32 movedistance,
171 gint32 *highmovedistance, WapiSeekMethod method);
172 static gboolean file_setendoffile(gpointer handle);
173 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
174 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
175 WapiFileTime *last_access,
176 WapiFileTime *last_write);
177 static gboolean file_setfiletime(gpointer handle,
178 const WapiFileTime *create_time,
179 const WapiFileTime *last_access,
180 const WapiFileTime *last_write);
181 static guint32 GetDriveTypeFromPath (const gchar *utf8_root_path_name);
183 /* File handle is only signalled for overlapped IO */
184 static MonoW32HandleOps _wapi_file_ops = {
185 file_close, /* close */
189 NULL, /* special_wait */
191 file_details, /* details */
192 file_typename, /* typename */
193 file_typesize, /* typesize */
196 static void console_close (gpointer handle, gpointer data);
197 static void console_details (gpointer data);
198 static const gchar* console_typename (void);
199 static gsize console_typesize (void);
200 static WapiFileType console_getfiletype(void);
201 static gboolean console_read(gpointer handle, gpointer buffer,
202 guint32 numbytes, guint32 *bytesread,
203 WapiOverlapped *overlapped);
204 static gboolean console_write(gpointer handle, gconstpointer buffer,
205 guint32 numbytes, guint32 *byteswritten,
206 WapiOverlapped *overlapped);
208 /* Console is mostly the same as file, except it can block waiting for
211 static MonoW32HandleOps _wapi_console_ops = {
212 console_close, /* close */
216 NULL, /* special_wait */
218 console_details, /* details */
219 console_typename, /* typename */
220 console_typesize, /* typesize */
223 static const gchar* find_typename (void);
224 static gsize find_typesize (void);
226 static MonoW32HandleOps _wapi_find_ops = {
231 NULL, /* special_wait */
234 find_typename, /* typename */
235 find_typesize, /* typesize */
238 static void pipe_close (gpointer handle, gpointer data);
239 static void pipe_details (gpointer data);
240 static const gchar* pipe_typename (void);
241 static gsize pipe_typesize (void);
242 static WapiFileType pipe_getfiletype (void);
243 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
244 guint32 *bytesread, WapiOverlapped *overlapped);
245 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
246 guint32 numbytes, guint32 *byteswritten,
247 WapiOverlapped *overlapped);
251 static MonoW32HandleOps _wapi_pipe_ops = {
252 pipe_close, /* close */
256 NULL, /* special_wait */
258 pipe_details, /* details */
259 pipe_typename, /* typename */
260 pipe_typesize, /* typesize */
263 static const struct {
264 /* File, console and pipe handles */
265 WapiFileType (*getfiletype)(void);
267 /* File, console and pipe handles */
268 gboolean (*readfile)(gpointer handle, gpointer buffer,
269 guint32 numbytes, guint32 *bytesread,
270 WapiOverlapped *overlapped);
271 gboolean (*writefile)(gpointer handle, gconstpointer buffer,
272 guint32 numbytes, guint32 *byteswritten,
273 WapiOverlapped *overlapped);
274 gboolean (*flushfile)(gpointer handle);
277 guint32 (*seek)(gpointer handle, gint32 movedistance,
278 gint32 *highmovedistance, WapiSeekMethod method);
279 gboolean (*setendoffile)(gpointer handle);
280 guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
281 gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
282 WapiFileTime *last_access,
283 WapiFileTime *last_write);
284 gboolean (*setfiletime)(gpointer handle,
285 const WapiFileTime *create_time,
286 const WapiFileTime *last_access,
287 const WapiFileTime *last_write);
288 } io_ops[MONO_W32HANDLE_COUNT]={
289 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
292 file_read, file_write,
293 file_flush, file_seek,
299 {console_getfiletype,
302 NULL, NULL, NULL, NULL, NULL, NULL},
304 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
306 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
308 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
310 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
311 /* socket (will need at least read and write) */
312 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
314 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
316 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
321 NULL, NULL, NULL, NULL, NULL, NULL},
324 static gboolean lock_while_writing = FALSE;
326 /* Some utility functions.
330 * Check if a file is writable by the current user.
332 * This is is a best effort kind of thing. It assumes a reasonable sane set
333 * of permissions by the underlying OS.
335 * We generally assume that basic unix permission bits are authoritative. Which might not
336 * be the case under systems with extended permissions systems (posix ACLs, SELinux, OSX/iOS sandboxing, etc)
338 * The choice of access as the fallback is due to the expected lower overhead compared to trying to open the file.
340 * The only expected problem with using access are for root, setuid or setgid programs as access is not consistent
341 * under those situations. It's to be expected that this should not happen in practice as those bits are very dangerous
342 * and should not be used with a dynamic runtime.
345 is_file_writable (struct stat *st, const char *path)
348 // OS X Finder "locked" or `ls -lO` "uchg".
349 // This only covers one of several cases where an OS X file could be unwritable through special flags.
350 if (st->st_flags & (UF_IMMUTABLE|SF_IMMUTABLE))
354 /* Is it globally writable? */
355 if (st->st_mode & S_IWOTH)
358 /* Am I the owner? */
359 if ((st->st_uid == geteuid ()) && (st->st_mode & S_IWUSR))
362 /* Am I in the same group? */
363 if ((st->st_gid == getegid ()) && (st->st_mode & S_IWGRP))
366 /* Fallback to using access(2). It's not ideal as it might not take into consideration euid/egid
367 * but it's the only sane option we have on unix.
369 return access (path, W_OK) == 0;
373 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
380 /* FIXME: this could definitely be better, but there seems to
381 * be no pattern to the attributes that are set
384 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
385 if (S_ISSOCK (buf->st_mode))
386 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
388 filename = _wapi_basename (pathname);
390 if (S_ISDIR (buf->st_mode)) {
391 attrs = FILE_ATTRIBUTE_DIRECTORY;
392 if (!is_file_writable (buf, pathname)) {
393 attrs |= FILE_ATTRIBUTE_READONLY;
395 if (filename[0] == '.') {
396 attrs |= FILE_ATTRIBUTE_HIDDEN;
399 if (!is_file_writable (buf, pathname)) {
400 attrs = FILE_ATTRIBUTE_READONLY;
402 if (filename[0] == '.') {
403 attrs |= FILE_ATTRIBUTE_HIDDEN;
405 } else if (filename[0] == '.') {
406 attrs = FILE_ATTRIBUTE_HIDDEN;
408 attrs = FILE_ATTRIBUTE_NORMAL;
413 if (S_ISLNK (lbuf->st_mode)) {
414 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
424 _wapi_set_last_error_from_errno (void)
426 SetLastError (_wapi_get_win32_file_error (errno));
429 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
432 if (errno == ENOENT) {
433 /* Check the path - if it's a missing directory then
434 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
440 dirname = _wapi_dirname (path);
442 dirname = g_strdup (dir);
445 if (_wapi_access (dirname, F_OK) == 0) {
446 SetLastError (ERROR_FILE_NOT_FOUND);
448 SetLastError (ERROR_PATH_NOT_FOUND);
453 _wapi_set_last_error_from_errno ();
459 static void file_close (gpointer handle, gpointer data)
461 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
462 int fd = file_handle->fd;
464 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing file handle %p [%s]", __func__, handle,
465 file_handle->filename);
467 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
468 _wapi_unlink (file_handle->filename);
470 g_free (file_handle->filename);
472 if (file_handle->share_info)
473 _wapi_handle_share_release (file_handle->share_info);
478 static void file_details (gpointer data)
480 struct _WapiHandle_file *file = (struct _WapiHandle_file *)data;
482 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
484 file->fileaccess&GENERIC_READ?'R':'.',
485 file->fileaccess&GENERIC_WRITE?'W':'.',
486 file->fileaccess&GENERIC_EXECUTE?'X':'.',
487 file->sharemode&FILE_SHARE_READ?'R':'.',
488 file->sharemode&FILE_SHARE_WRITE?'W':'.',
489 file->sharemode&FILE_SHARE_DELETE?'D':'.',
493 static const gchar* file_typename (void)
498 static gsize file_typesize (void)
500 return sizeof (struct _WapiHandle_file);
503 static WapiFileType file_getfiletype(void)
505 return(FILE_TYPE_DISK);
508 static gboolean file_read(gpointer handle, gpointer buffer,
509 guint32 numbytes, guint32 *bytesread,
510 WapiOverlapped *overlapped)
512 struct _WapiHandle_file *file_handle;
515 MonoThreadInfo *info = mono_thread_info_current ();
517 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
518 (gpointer *)&file_handle);
520 g_warning ("%s: error looking up file handle %p", __func__,
522 SetLastError (ERROR_INVALID_HANDLE);
526 fd = file_handle->fd;
527 if(bytesread!=NULL) {
531 if(!(file_handle->fileaccess & GENERIC_READ) &&
532 !(file_handle->fileaccess & GENERIC_ALL)) {
533 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
534 __func__, handle, file_handle->fileaccess);
536 SetLastError (ERROR_ACCESS_DENIED);
541 ret = read (fd, buffer, numbytes);
542 } while (ret == -1 && errno == EINTR &&
543 !mono_thread_info_is_interrupt_state (info));
548 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
549 handle, strerror(err));
550 SetLastError (_wapi_get_win32_file_error (err));
554 if (bytesread != NULL) {
561 static gboolean file_write(gpointer handle, gconstpointer buffer,
562 guint32 numbytes, guint32 *byteswritten,
563 WapiOverlapped *overlapped G_GNUC_UNUSED)
565 struct _WapiHandle_file *file_handle;
568 off_t current_pos = 0;
569 MonoThreadInfo *info = mono_thread_info_current ();
571 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
572 (gpointer *)&file_handle);
574 g_warning ("%s: error looking up file handle %p", __func__,
576 SetLastError (ERROR_INVALID_HANDLE);
580 fd = file_handle->fd;
582 if(byteswritten!=NULL) {
586 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
587 !(file_handle->fileaccess & GENERIC_ALL)) {
588 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);
590 SetLastError (ERROR_ACCESS_DENIED);
594 if (lock_while_writing) {
595 /* Need to lock the region we're about to write to,
596 * because we only do advisory locking on POSIX
599 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
600 if (current_pos == -1) {
601 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
602 handle, strerror (errno));
603 _wapi_set_last_error_from_errno ();
607 if (_wapi_lock_file_region (fd, current_pos,
608 numbytes) == FALSE) {
609 /* The error has already been set */
615 ret = write (fd, buffer, numbytes);
616 } while (ret == -1 && errno == EINTR &&
617 !mono_thread_info_is_interrupt_state (info));
619 if (lock_while_writing) {
620 _wapi_unlock_file_region (fd, current_pos, numbytes);
624 if (errno == EINTR) {
627 _wapi_set_last_error_from_errno ();
629 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
630 __func__, handle, strerror(errno));
635 if (byteswritten != NULL) {
641 static gboolean file_flush(gpointer handle)
643 struct _WapiHandle_file *file_handle;
647 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
648 (gpointer *)&file_handle);
650 g_warning ("%s: error looking up file handle %p", __func__,
652 SetLastError (ERROR_INVALID_HANDLE);
656 fd = file_handle->fd;
658 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
659 !(file_handle->fileaccess & GENERIC_ALL)) {
660 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);
662 SetLastError (ERROR_ACCESS_DENIED);
668 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fsync of handle %p error: %s", __func__, handle,
671 _wapi_set_last_error_from_errno ();
678 static guint32 file_seek(gpointer handle, gint32 movedistance,
679 gint32 *highmovedistance, WapiSeekMethod method)
681 struct _WapiHandle_file *file_handle;
683 gint64 offset, newpos;
687 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
688 (gpointer *)&file_handle);
690 g_warning ("%s: error looking up file handle %p", __func__,
692 SetLastError (ERROR_INVALID_HANDLE);
693 return(INVALID_SET_FILE_POINTER);
696 fd = file_handle->fd;
698 if(!(file_handle->fileaccess & GENERIC_READ) &&
699 !(file_handle->fileaccess & GENERIC_WRITE) &&
700 !(file_handle->fileaccess & GENERIC_ALL)) {
701 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);
703 SetLastError (ERROR_ACCESS_DENIED);
704 return(INVALID_SET_FILE_POINTER);
718 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: invalid seek type %d", __func__, method);
720 SetLastError (ERROR_INVALID_PARAMETER);
721 return(INVALID_SET_FILE_POINTER);
724 #ifdef HAVE_LARGE_FILE_SUPPORT
725 if(highmovedistance==NULL) {
727 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting offset to %lld (low %d)", __func__,
728 offset, movedistance);
730 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
732 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);
738 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: moving handle %p by %lld bytes from %d", __func__,
739 handle, (long long)offset, whence);
741 #ifdef PLATFORM_ANDROID
742 /* bionic doesn't support -D_FILE_OFFSET_BITS=64 */
743 newpos=lseek64(fd, offset, whence);
745 newpos=lseek(fd, offset, whence);
748 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek on handle %p returned error %s",
749 __func__, handle, strerror(errno));
751 _wapi_set_last_error_from_errno ();
752 return(INVALID_SET_FILE_POINTER);
755 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek returns %lld", __func__, newpos);
757 #ifdef HAVE_LARGE_FILE_SUPPORT
758 ret=newpos & 0xFFFFFFFF;
759 if(highmovedistance!=NULL) {
760 *highmovedistance=newpos>>32;
764 if(highmovedistance!=NULL) {
765 /* Accurate, but potentially dodgy :-) */
770 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: move of handle %p returning %d/%d", __func__,
771 handle, ret, highmovedistance==NULL?0:*highmovedistance);
776 static gboolean file_setendoffile(gpointer handle)
778 struct _WapiHandle_file *file_handle;
783 MonoThreadInfo *info = mono_thread_info_current ();
785 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
786 (gpointer *)&file_handle);
788 g_warning ("%s: error looking up file handle %p", __func__,
790 SetLastError (ERROR_INVALID_HANDLE);
793 fd = file_handle->fd;
795 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
796 !(file_handle->fileaccess & GENERIC_ALL)) {
797 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);
799 SetLastError (ERROR_ACCESS_DENIED);
803 /* Find the current file position, and the file length. If
804 * the file position is greater than the length, write to
805 * extend the file with a hole. If the file position is less
806 * than the length, truncate the file.
809 ret=fstat(fd, &statbuf);
811 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
812 handle, strerror(errno));
814 _wapi_set_last_error_from_errno ();
818 pos=lseek(fd, (off_t)0, SEEK_CUR);
820 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
821 handle, strerror(errno));
823 _wapi_set_last_error_from_errno ();
827 #ifdef FTRUNCATE_DOESNT_EXTEND
828 off_t size = statbuf.st_size;
829 /* I haven't bothered to write the configure.ac stuff for this
830 * because I don't know if any platform needs it. I'm leaving
831 * this code just in case though
834 /* Extend the file. Use write() here, because some
835 * manuals say that ftruncate() behaviour is undefined
836 * when the file needs extending. The POSIX spec says
837 * that on XSI-conformant systems it extends, so if
838 * every system we care about conforms, then we can
842 ret = write (fd, "", 1);
843 } while (ret == -1 && errno == EINTR &&
844 !mono_thread_info_is_interrupt_state (info));
847 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
849 _wapi_set_last_error_from_errno ();
853 /* And put the file position back after the write */
854 ret = lseek (fd, pos, SEEK_SET);
856 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p second lseek failed: %s",
857 __func__, handle, strerror(errno));
859 _wapi_set_last_error_from_errno ();
865 /* Native Client has no ftruncate function, even in standalone sel_ldr. */
866 #ifndef __native_client__
867 /* always truncate, because the extend write() adds an extra
868 * byte to the end of the file
871 ret=ftruncate(fd, pos);
873 while (ret==-1 && errno==EINTR && !mono_thread_info_is_interrupt_state (info));
875 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ftruncate failed: %s", __func__,
876 handle, strerror(errno));
878 _wapi_set_last_error_from_errno ();
886 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
888 struct _WapiHandle_file *file_handle;
895 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
896 (gpointer *)&file_handle);
898 g_warning ("%s: error looking up file handle %p", __func__,
900 SetLastError (ERROR_INVALID_HANDLE);
901 return(INVALID_FILE_SIZE);
903 fd = file_handle->fd;
905 if(!(file_handle->fileaccess & GENERIC_READ) &&
906 !(file_handle->fileaccess & GENERIC_WRITE) &&
907 !(file_handle->fileaccess & GENERIC_ALL)) {
908 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);
910 SetLastError (ERROR_ACCESS_DENIED);
911 return(INVALID_FILE_SIZE);
914 /* If the file has a size with the low bits 0xFFFFFFFF the
915 * caller can't tell if this is an error, so clear the error
918 SetLastError (ERROR_SUCCESS);
920 ret = fstat(fd, &statbuf);
922 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
923 handle, strerror(errno));
925 _wapi_set_last_error_from_errno ();
926 return(INVALID_FILE_SIZE);
929 /* fstat indicates block devices as zero-length, so go a different path */
931 if (S_ISBLK(statbuf.st_mode)) {
933 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
934 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ioctl BLKGETSIZE64 failed: %s",
935 __func__, handle, strerror(errno));
937 _wapi_set_last_error_from_errno ();
938 return(INVALID_FILE_SIZE);
941 size = bigsize & 0xFFFFFFFF;
942 if (highsize != NULL) {
943 *highsize = bigsize>>32;
946 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning block device size %d/%d",
947 __func__, size, *highsize);
953 #ifdef HAVE_LARGE_FILE_SUPPORT
954 size = statbuf.st_size & 0xFFFFFFFF;
955 if (highsize != NULL) {
956 *highsize = statbuf.st_size>>32;
959 if (highsize != NULL) {
960 /* Accurate, but potentially dodgy :-) */
963 size = statbuf.st_size;
966 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning size %d/%d", __func__, size, *highsize);
971 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
972 WapiFileTime *last_access,
973 WapiFileTime *last_write)
975 struct _WapiHandle_file *file_handle;
978 guint64 create_ticks, access_ticks, write_ticks;
981 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
982 (gpointer *)&file_handle);
984 g_warning ("%s: error looking up file handle %p", __func__,
986 SetLastError (ERROR_INVALID_HANDLE);
989 fd = file_handle->fd;
991 if(!(file_handle->fileaccess & GENERIC_READ) &&
992 !(file_handle->fileaccess & GENERIC_ALL)) {
993 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
994 __func__, handle, file_handle->fileaccess);
996 SetLastError (ERROR_ACCESS_DENIED);
1000 ret=fstat(fd, &statbuf);
1002 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
1005 _wapi_set_last_error_from_errno ();
1009 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: atime: %ld ctime: %ld mtime: %ld", __func__,
1010 statbuf.st_atime, statbuf.st_ctime,
1013 /* Try and guess a meaningful create time by using the older
1016 /* The magic constant comes from msdn documentation
1017 * "Converting a time_t Value to a File Time"
1019 if(statbuf.st_atime < statbuf.st_ctime) {
1020 create_ticks=((guint64)statbuf.st_atime*10000000)
1021 + 116444736000000000ULL;
1023 create_ticks=((guint64)statbuf.st_ctime*10000000)
1024 + 116444736000000000ULL;
1027 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
1028 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
1030 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
1031 access_ticks, create_ticks, write_ticks);
1033 if(create_time!=NULL) {
1034 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
1035 create_time->dwHighDateTime = create_ticks >> 32;
1038 if(last_access!=NULL) {
1039 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
1040 last_access->dwHighDateTime = access_ticks >> 32;
1043 if(last_write!=NULL) {
1044 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
1045 last_write->dwHighDateTime = write_ticks >> 32;
1051 static gboolean file_setfiletime(gpointer handle,
1052 const WapiFileTime *create_time G_GNUC_UNUSED,
1053 const WapiFileTime *last_access,
1054 const WapiFileTime *last_write)
1056 struct _WapiHandle_file *file_handle;
1058 struct utimbuf utbuf;
1059 struct stat statbuf;
1060 guint64 access_ticks, write_ticks;
1063 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1064 (gpointer *)&file_handle);
1066 g_warning ("%s: error looking up file handle %p", __func__,
1068 SetLastError (ERROR_INVALID_HANDLE);
1071 fd = file_handle->fd;
1073 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
1074 !(file_handle->fileaccess & GENERIC_ALL)) {
1075 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);
1077 SetLastError (ERROR_ACCESS_DENIED);
1081 if(file_handle->filename == NULL) {
1082 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p unknown filename", __func__, handle);
1084 SetLastError (ERROR_INVALID_HANDLE);
1088 /* Get the current times, so we can put the same times back in
1089 * the event that one of the FileTime structs is NULL
1091 ret=fstat (fd, &statbuf);
1093 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
1096 SetLastError (ERROR_INVALID_PARAMETER);
1100 if(last_access!=NULL) {
1101 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
1102 last_access->dwLowDateTime;
1103 /* This is (time_t)0. We can actually go to INT_MIN,
1104 * but this will do for now.
1106 if (access_ticks < 116444736000000000ULL) {
1107 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set access time too early",
1109 SetLastError (ERROR_INVALID_PARAMETER);
1113 if (sizeof (utbuf.actime) == 4 && ((access_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
1114 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",
1116 SetLastError (ERROR_INVALID_PARAMETER);
1120 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
1122 utbuf.actime=statbuf.st_atime;
1125 if(last_write!=NULL) {
1126 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
1127 last_write->dwLowDateTime;
1128 /* This is (time_t)0. We can actually go to INT_MIN,
1129 * but this will do for now.
1131 if (write_ticks < 116444736000000000ULL) {
1132 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set write time too early",
1134 SetLastError (ERROR_INVALID_PARAMETER);
1137 if (sizeof (utbuf.modtime) == 4 && ((write_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
1138 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",
1140 SetLastError (ERROR_INVALID_PARAMETER);
1144 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1146 utbuf.modtime=statbuf.st_mtime;
1149 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting handle %p access %ld write %ld", __func__,
1150 handle, utbuf.actime, utbuf.modtime);
1152 ret = _wapi_utime (file_handle->filename, &utbuf);
1154 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p [%s] utime failed: %s", __func__,
1155 handle, file_handle->filename, strerror(errno));
1157 SetLastError (ERROR_INVALID_PARAMETER);
1164 static void console_close (gpointer handle, gpointer data)
1166 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1167 int fd = console_handle->fd;
1169 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing console handle %p", __func__, handle);
1171 g_free (console_handle->filename);
1174 if (console_handle->share_info)
1175 _wapi_handle_share_release (console_handle->share_info);
1180 static void console_details (gpointer data)
1182 file_details (data);
1185 static const gchar* console_typename (void)
1190 static gsize console_typesize (void)
1192 return sizeof (struct _WapiHandle_file);
1195 static WapiFileType console_getfiletype(void)
1197 return(FILE_TYPE_CHAR);
1200 static gboolean console_read(gpointer handle, gpointer buffer,
1201 guint32 numbytes, guint32 *bytesread,
1202 WapiOverlapped *overlapped G_GNUC_UNUSED)
1204 struct _WapiHandle_file *console_handle;
1207 MonoThreadInfo *info = mono_thread_info_current ();
1209 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_CONSOLE,
1210 (gpointer *)&console_handle);
1212 g_warning ("%s: error looking up console handle %p", __func__,
1214 SetLastError (ERROR_INVALID_HANDLE);
1217 fd = console_handle->fd;
1219 if(bytesread!=NULL) {
1223 if(!(console_handle->fileaccess & GENERIC_READ) &&
1224 !(console_handle->fileaccess & GENERIC_ALL)) {
1225 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1226 __func__, handle, console_handle->fileaccess);
1228 SetLastError (ERROR_ACCESS_DENIED);
1233 ret=read(fd, buffer, numbytes);
1234 } while (ret==-1 && errno==EINTR && !mono_thread_info_is_interrupt_state (info));
1237 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__, handle,
1240 _wapi_set_last_error_from_errno ();
1244 if(bytesread!=NULL) {
1251 static gboolean console_write(gpointer handle, gconstpointer buffer,
1252 guint32 numbytes, guint32 *byteswritten,
1253 WapiOverlapped *overlapped G_GNUC_UNUSED)
1255 struct _WapiHandle_file *console_handle;
1258 MonoThreadInfo *info = mono_thread_info_current ();
1260 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_CONSOLE,
1261 (gpointer *)&console_handle);
1263 g_warning ("%s: error looking up console handle %p", __func__,
1265 SetLastError (ERROR_INVALID_HANDLE);
1268 fd = console_handle->fd;
1270 if(byteswritten!=NULL) {
1274 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1275 !(console_handle->fileaccess & GENERIC_ALL)) {
1276 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);
1278 SetLastError (ERROR_ACCESS_DENIED);
1283 ret = write(fd, buffer, numbytes);
1284 } while (ret == -1 && errno == EINTR &&
1285 !mono_thread_info_is_interrupt_state (info));
1288 if (errno == EINTR) {
1291 _wapi_set_last_error_from_errno ();
1293 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
1294 __func__, handle, strerror(errno));
1299 if(byteswritten!=NULL) {
1306 static const gchar* find_typename (void)
1311 static gsize find_typesize (void)
1313 return sizeof (struct _WapiHandle_find);
1316 static void pipe_close (gpointer handle, gpointer data)
1318 struct _WapiHandle_file *pipe_handle = (struct _WapiHandle_file*)data;
1319 int fd = pipe_handle->fd;
1321 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing pipe handle %p fd %d", __func__, handle, fd);
1323 /* No filename with pipe handles */
1325 if (pipe_handle->share_info)
1326 _wapi_handle_share_release (pipe_handle->share_info);
1331 static void pipe_details (gpointer data)
1333 file_details (data);
1336 static const gchar* pipe_typename (void)
1341 static gsize pipe_typesize (void)
1343 return sizeof (struct _WapiHandle_file);
1346 static WapiFileType pipe_getfiletype(void)
1348 return(FILE_TYPE_PIPE);
1351 static gboolean pipe_read (gpointer handle, gpointer buffer,
1352 guint32 numbytes, guint32 *bytesread,
1353 WapiOverlapped *overlapped G_GNUC_UNUSED)
1355 struct _WapiHandle_file *pipe_handle;
1358 MonoThreadInfo *info = mono_thread_info_current ();
1360 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_PIPE,
1361 (gpointer *)&pipe_handle);
1363 g_warning ("%s: error looking up pipe handle %p", __func__,
1365 SetLastError (ERROR_INVALID_HANDLE);
1368 fd = pipe_handle->fd;
1370 if(bytesread!=NULL) {
1374 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1375 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1376 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1377 __func__, handle, pipe_handle->fileaccess);
1379 SetLastError (ERROR_ACCESS_DENIED);
1383 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: reading up to %d bytes from pipe %p", __func__,
1387 ret=read(fd, buffer, numbytes);
1388 } while (ret==-1 && errno==EINTR && !mono_thread_info_is_interrupt_state (info));
1391 if (errno == EINTR) {
1394 _wapi_set_last_error_from_errno ();
1396 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
1397 handle, strerror(errno));
1403 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read %d bytes from pipe %p", __func__, ret, handle);
1405 if(bytesread!=NULL) {
1412 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1413 guint32 numbytes, guint32 *byteswritten,
1414 WapiOverlapped *overlapped G_GNUC_UNUSED)
1416 struct _WapiHandle_file *pipe_handle;
1419 MonoThreadInfo *info = mono_thread_info_current ();
1421 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_PIPE,
1422 (gpointer *)&pipe_handle);
1424 g_warning ("%s: error looking up pipe handle %p", __func__,
1426 SetLastError (ERROR_INVALID_HANDLE);
1429 fd = pipe_handle->fd;
1431 if(byteswritten!=NULL) {
1435 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1436 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1437 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);
1439 SetLastError (ERROR_ACCESS_DENIED);
1443 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1447 ret = write (fd, buffer, numbytes);
1448 } while (ret == -1 && errno == EINTR &&
1449 !mono_thread_info_is_interrupt_state (info));
1452 if (errno == EINTR) {
1455 _wapi_set_last_error_from_errno ();
1457 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s", __func__,
1458 handle, strerror(errno));
1463 if(byteswritten!=NULL) {
1470 static int convert_flags(guint32 fileaccess, guint32 createmode)
1474 switch(fileaccess) {
1481 case GENERIC_READ|GENERIC_WRITE:
1485 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown access type 0x%x", __func__,
1490 switch(createmode) {
1492 flags|=O_CREAT|O_EXCL;
1495 flags|=O_CREAT|O_TRUNC;
1502 case TRUNCATE_EXISTING:
1506 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown create mode 0x%x", __func__,
1515 static mode_t convert_perms(guint32 sharemode)
1519 if(sharemode&FILE_SHARE_READ) {
1522 if(sharemode&FILE_SHARE_WRITE) {
1530 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1532 struct _WapiFileShare **share_info)
1534 gboolean file_already_shared;
1535 guint32 file_existing_share, file_existing_access;
1537 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);
1539 if (file_already_shared) {
1540 /* The reference to this share info was incremented
1541 * when we looked it up, so be careful to put it back
1542 * if we conclude we can't use this file.
1544 if (file_existing_share == 0) {
1545 /* Quick and easy, no possibility to share */
1546 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);
1548 _wapi_handle_share_release (*share_info);
1553 if (((file_existing_share == FILE_SHARE_READ) &&
1554 (fileaccess != GENERIC_READ)) ||
1555 ((file_existing_share == FILE_SHARE_WRITE) &&
1556 (fileaccess != GENERIC_WRITE))) {
1557 /* New access mode doesn't match up */
1558 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);
1560 _wapi_handle_share_release (*share_info);
1565 if (((file_existing_access & GENERIC_READ) &&
1566 !(sharemode & FILE_SHARE_READ)) ||
1567 ((file_existing_access & GENERIC_WRITE) &&
1568 !(sharemode & FILE_SHARE_WRITE))) {
1569 /* New share mode doesn't match up */
1570 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);
1572 _wapi_handle_share_release (*share_info);
1577 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
1585 share_allows_delete (struct stat *statbuf, struct _WapiFileShare **share_info)
1587 gboolean file_already_shared;
1588 guint32 file_existing_share, file_existing_access;
1590 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);
1592 if (file_already_shared) {
1593 /* The reference to this share info was incremented
1594 * when we looked it up, so be careful to put it back
1595 * if we conclude we can't use this file.
1597 if (file_existing_share == 0) {
1598 /* Quick and easy, no possibility to share */
1599 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);
1601 _wapi_handle_share_release (*share_info);
1606 if (!(file_existing_share & FILE_SHARE_DELETE)) {
1607 /* New access mode doesn't match up */
1608 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);
1610 _wapi_handle_share_release (*share_info);
1615 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
1623 * @name: a pointer to a NULL-terminated unicode string, that names
1624 * the file or other object to create.
1625 * @fileaccess: specifies the file access mode
1626 * @sharemode: whether the file should be shared. This parameter is
1627 * currently ignored.
1628 * @security: Ignored for now.
1629 * @createmode: specifies whether to create a new file, whether to
1630 * overwrite an existing file, whether to truncate the file, etc.
1631 * @attrs: specifies file attributes and flags. On win32 attributes
1632 * are characteristics of the file, not the handle, and are ignored
1633 * when an existing file is opened. Flags give the library hints on
1634 * how to process a file to optimise performance.
1635 * @template: the handle of an open %GENERIC_READ file that specifies
1636 * attributes to apply to a newly created file, ignoring @attrs.
1637 * Normally this parameter is NULL. This parameter is ignored when an
1638 * existing file is opened.
1640 * Creates a new file handle. This only applies to normal files:
1641 * pipes are handled by CreatePipe(), and console handles are created
1642 * with GetStdHandle().
1644 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1646 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1647 guint32 sharemode, WapiSecurityAttributes *security,
1648 guint32 createmode, guint32 attrs,
1649 gpointer template_ G_GNUC_UNUSED)
1651 struct _WapiHandle_file file_handle = {0};
1653 int flags=convert_flags(fileaccess, createmode);
1654 /*mode_t perms=convert_perms(sharemode);*/
1655 /* we don't use sharemode, because that relates to sharing of
1656 * the file when the file is open and is already handled by
1657 * other code, perms instead are the on-disk permissions and
1658 * this is a sane default.
1663 MonoW32HandleType handle_type;
1664 struct stat statbuf;
1666 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1669 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1670 SetLastError (ERROR_ENCRYPTION_FAILED);
1671 return INVALID_HANDLE_VALUE;
1675 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1677 SetLastError (ERROR_INVALID_NAME);
1678 return(INVALID_HANDLE_VALUE);
1681 filename = mono_unicode_to_external (name);
1682 if (filename == NULL) {
1683 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1685 SetLastError (ERROR_INVALID_NAME);
1686 return(INVALID_HANDLE_VALUE);
1689 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Opening %s with share 0x%x and access 0x%x", __func__,
1690 filename, sharemode, fileaccess);
1692 fd = _wapi_open (filename, flags, perms);
1694 /* If we were trying to open a directory with write permissions
1695 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1696 * EISDIR. However, this is a bit bogus because calls to
1697 * manipulate the directory (e.g. SetFileTime) will still work on
1698 * the directory because they use other API calls
1699 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1700 * to open the directory again without write permission.
1702 if (fd == -1 && errno == EISDIR)
1704 /* Try again but don't try to make it writable */
1705 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1709 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s: %s", __func__, filename,
1711 _wapi_set_last_path_error_from_errno (NULL, filename);
1714 return(INVALID_HANDLE_VALUE);
1717 if (fd >= mono_w32handle_fd_reserve) {
1718 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
1720 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1725 return(INVALID_HANDLE_VALUE);
1728 ret = fstat (fd, &statbuf);
1730 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fstat error of file %s: %s", __func__,
1731 filename, strerror (errno));
1732 _wapi_set_last_error_from_errno ();
1736 return(INVALID_HANDLE_VALUE);
1738 #ifdef __native_client__
1739 /* Workaround: Native Client currently returns the same fake inode
1740 * for all files, so do a simple hash on the filename so we don't
1741 * use the same share info for each file.
1743 statbuf.st_ino = g_str_hash(filename);
1746 if (share_allows_open (&statbuf, sharemode, fileaccess,
1747 &file_handle.share_info) == FALSE) {
1748 SetLastError (ERROR_SHARING_VIOLATION);
1752 return (INVALID_HANDLE_VALUE);
1754 if (file_handle.share_info == NULL) {
1755 /* No space, so no more files can be opened */
1756 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No space in the share table", __func__);
1758 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1762 return(INVALID_HANDLE_VALUE);
1765 file_handle.filename = filename;
1767 if(security!=NULL) {
1768 //file_handle->security_attributes=_wapi_handle_scratch_store (
1769 //security, sizeof(WapiSecurityAttributes));
1772 file_handle.fd = fd;
1773 file_handle.fileaccess=fileaccess;
1774 file_handle.sharemode=sharemode;
1775 file_handle.attrs=attrs;
1777 #ifdef HAVE_POSIX_FADVISE
1778 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1779 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1780 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1781 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1785 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1787 if (S_ISFIFO (statbuf.st_mode)) {
1788 handle_type = MONO_W32HANDLE_PIPE;
1789 /* maintain invariant that pipes have no filename */
1790 file_handle.filename = NULL;
1793 } else if (S_ISCHR (statbuf.st_mode)) {
1794 handle_type = MONO_W32HANDLE_CONSOLE;
1796 handle_type = MONO_W32HANDLE_FILE;
1799 handle = mono_w32handle_new_fd (handle_type, fd, &file_handle);
1800 if (handle == INVALID_HANDLE_VALUE) {
1801 g_warning ("%s: error creating file handle", __func__);
1805 SetLastError (ERROR_GEN_FAILURE);
1806 return(INVALID_HANDLE_VALUE);
1809 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p", __func__, handle);
1816 * @name: a pointer to a NULL-terminated unicode string, that names
1817 * the file to be deleted.
1819 * Deletes file @name.
1821 * Return value: %TRUE on success, %FALSE otherwise.
1823 gboolean DeleteFile(const gunichar2 *name)
1827 gboolean ret = FALSE;
1830 struct stat statbuf;
1831 struct _WapiFileShare *shareinfo;
1835 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1837 SetLastError (ERROR_INVALID_NAME);
1841 filename=mono_unicode_to_external(name);
1842 if(filename==NULL) {
1843 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1845 SetLastError (ERROR_INVALID_NAME);
1849 attrs = GetFileAttributes (name);
1850 if (attrs == INVALID_FILE_ATTRIBUTES) {
1851 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file attributes error", __func__);
1852 /* Error set by GetFileAttributes() */
1858 /* Check to make sure sharing allows us to open the file for
1859 * writing. See bug 323389.
1861 * Do the checks that don't need an open file descriptor, for
1862 * simplicity's sake. If we really have to do the full checks
1863 * then we can implement that later.
1865 if (_wapi_stat (filename, &statbuf) < 0) {
1866 _wapi_set_last_path_error_from_errno (NULL, filename);
1871 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1872 &shareinfo) == FALSE) {
1873 SetLastError (ERROR_SHARING_VIOLATION);
1878 _wapi_handle_share_release (shareinfo);
1881 retval = _wapi_unlink (filename);
1884 _wapi_set_last_path_error_from_errno (NULL, filename);
1896 * @name: a pointer to a NULL-terminated unicode string, that names
1897 * the file to be moved.
1898 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1899 * new name for the file.
1901 * Renames file @name to @dest_name.
1902 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1903 * when it is the same file as the source. In that case it silently succeeds.
1905 * Return value: %TRUE on success, %FALSE otherwise.
1907 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1909 gchar *utf8_name, *utf8_dest_name;
1910 int result, errno_copy;
1911 struct stat stat_src, stat_dest;
1912 gboolean ret = FALSE;
1913 struct _WapiFileShare *shareinfo;
1916 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1918 SetLastError (ERROR_INVALID_NAME);
1922 utf8_name = mono_unicode_to_external (name);
1923 if (utf8_name == NULL) {
1924 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1926 SetLastError (ERROR_INVALID_NAME);
1930 if(dest_name==NULL) {
1931 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1934 SetLastError (ERROR_INVALID_NAME);
1938 utf8_dest_name = mono_unicode_to_external (dest_name);
1939 if (utf8_dest_name == NULL) {
1940 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1943 SetLastError (ERROR_INVALID_NAME);
1948 * In C# land we check for the existence of src, but not for dest.
1949 * We check it here and return the failure if dest exists and is not
1950 * the same file as src.
1952 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1953 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1954 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1956 g_free (utf8_dest_name);
1961 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1962 if (stat_dest.st_dev != stat_src.st_dev ||
1963 stat_dest.st_ino != stat_src.st_ino) {
1965 g_free (utf8_dest_name);
1966 SetLastError (ERROR_ALREADY_EXISTS);
1971 /* Check to make that we have delete sharing permission.
1972 * See https://bugzilla.xamarin.com/show_bug.cgi?id=17009
1974 * Do the checks that don't need an open file descriptor, for
1975 * simplicity's sake. If we really have to do the full checks
1976 * then we can implement that later.
1978 if (share_allows_delete (&stat_src, &shareinfo) == FALSE) {
1979 SetLastError (ERROR_SHARING_VIOLATION);
1983 _wapi_handle_share_release (shareinfo);
1985 result = _wapi_rename (utf8_name, utf8_dest_name);
1989 switch(errno_copy) {
1991 SetLastError (ERROR_ALREADY_EXISTS);
1995 /* Ignore here, it is dealt with below */
1999 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2004 g_free (utf8_dest_name);
2006 if (result != 0 && errno_copy == EXDEV) {
2007 if (S_ISDIR (stat_src.st_mode)) {
2008 SetLastError (ERROR_NOT_SAME_DEVICE);
2011 /* Try a copy to the new location, and delete the source */
2012 if (CopyFile (name, dest_name, TRUE)==FALSE) {
2013 /* CopyFile will set the error */
2017 return(DeleteFile (name));
2028 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
2032 int buf_size = st_src->st_blksize;
2033 MonoThreadInfo *info = mono_thread_info_current ();
2035 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
2036 buf = (char *) malloc (buf_size);
2039 remain = read (src_fd, buf, buf_size);
2041 if (errno == EINTR && !mono_thread_info_is_interrupt_state (info))
2045 _wapi_set_last_error_from_errno ();
2055 while (remain > 0) {
2056 if ((n = write (dest_fd, wbuf, remain)) < 0) {
2057 if (errno == EINTR && !mono_thread_info_is_interrupt_state (info))
2061 _wapi_set_last_error_from_errno ();
2062 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write failed.", __func__);
2078 * @name: a pointer to a NULL-terminated unicode string, that names
2079 * the file to be copied.
2080 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
2081 * new name for the file.
2082 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
2084 * Copies file @name to @dest_name
2086 * Return value: %TRUE on success, %FALSE otherwise.
2088 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
2089 gboolean fail_if_exists)
2091 gchar *utf8_src, *utf8_dest;
2092 int src_fd, dest_fd;
2093 struct stat st, dest_st;
2094 struct utimbuf dest_time;
2095 gboolean ret = TRUE;
2099 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2101 SetLastError (ERROR_INVALID_NAME);
2105 utf8_src = mono_unicode_to_external (name);
2106 if (utf8_src == NULL) {
2107 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of source returned NULL",
2110 SetLastError (ERROR_INVALID_PARAMETER);
2114 if(dest_name==NULL) {
2115 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: dest is NULL", __func__);
2118 SetLastError (ERROR_INVALID_NAME);
2122 utf8_dest = mono_unicode_to_external (dest_name);
2123 if (utf8_dest == NULL) {
2124 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of dest returned NULL",
2127 SetLastError (ERROR_INVALID_PARAMETER);
2134 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2136 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2144 if (fstat (src_fd, &st) < 0) {
2145 _wapi_set_last_error_from_errno ();
2154 /* Before trying to open/create the dest, we need to report a 'file busy'
2155 * error if src and dest are actually the same file. We do the check here to take
2156 * advantage of the IOMAP capability */
2157 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
2158 st.st_ino == dest_st.st_ino) {
2164 SetLastError (ERROR_SHARING_VIOLATION);
2168 if (fail_if_exists) {
2169 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2171 /* FIXME: it kinda sucks that this code path potentially scans
2172 * the directory twice due to the weird SetLastError()
2174 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2176 /* The file does not exist, try creating it */
2177 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2179 /* Apparently this error is set if we
2180 * overwrite the dest file
2182 SetLastError (ERROR_ALREADY_EXISTS);
2186 _wapi_set_last_error_from_errno ();
2195 if (!write_file (src_fd, dest_fd, &st, TRUE))
2201 dest_time.modtime = st.st_mtime;
2202 dest_time.actime = st.st_atime;
2203 ret_utime = utime (utf8_dest, &dest_time);
2204 if (ret_utime == -1)
2205 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file [%s] utime failed: %s", __func__, utf8_dest, strerror(errno));
2214 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2219 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: %s is NULL", __func__, arg_name);
2220 SetLastError (ERROR_INVALID_NAME);
2224 utf8_ret = mono_unicode_to_external (arg);
2225 if (utf8_ret == NULL) {
2226 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of %s returned NULL",
2227 __func__, arg_name);
2228 SetLastError (ERROR_INVALID_PARAMETER);
2236 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2237 const gunichar2 *backupFileName, guint32 replaceFlags,
2238 gpointer exclude, gpointer reserved)
2240 int result, backup_fd = -1,replaced_fd = -1;
2241 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2242 struct stat stBackup;
2243 gboolean ret = FALSE;
2245 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2247 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2248 goto replace_cleanup;
2249 if (backupFileName != NULL) {
2250 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2251 goto replace_cleanup;
2254 if (utf8_backupFileName) {
2255 // Open the backup file for read so we can restore the file if an error occurs.
2256 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2257 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2259 goto replace_cleanup;
2262 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2264 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2265 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2266 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2267 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2270 if (replaced_fd == -1)
2271 goto replace_cleanup;
2273 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2276 goto replace_cleanup;
2282 g_free (utf8_replacedFileName);
2283 g_free (utf8_replacementFileName);
2284 g_free (utf8_backupFileName);
2285 if (backup_fd != -1)
2287 if (replaced_fd != -1)
2288 close (replaced_fd);
2294 * @stdhandle: specifies the file descriptor
2296 * Returns a handle for stdin, stdout, or stderr. Always returns the
2297 * same handle for the same @stdhandle.
2299 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2302 static mono_mutex_t stdhandle_mutex;
2304 gpointer GetStdHandle(WapiStdHandle stdhandle)
2306 struct _WapiHandle_file *file_handle;
2313 case STD_INPUT_HANDLE:
2318 case STD_OUTPUT_HANDLE:
2323 case STD_ERROR_HANDLE:
2329 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unknown standard handle type", __func__);
2331 SetLastError (ERROR_INVALID_PARAMETER);
2332 return(INVALID_HANDLE_VALUE);
2335 handle = GINT_TO_POINTER (fd);
2337 mono_os_mutex_lock (&stdhandle_mutex);
2339 ok = mono_w32handle_lookup (handle, MONO_W32HANDLE_CONSOLE,
2340 (gpointer *)&file_handle);
2342 /* Need to create this console handle */
2343 handle = _wapi_stdhandle_create (fd, name);
2345 if (handle == INVALID_HANDLE_VALUE) {
2346 SetLastError (ERROR_NO_MORE_FILES);
2350 /* Add a reference to this handle */
2351 mono_w32handle_ref (handle);
2355 mono_os_mutex_unlock (&stdhandle_mutex);
2362 * @handle: The file handle to read from. The handle must have
2363 * %GENERIC_READ access.
2364 * @buffer: The buffer to store read data in
2365 * @numbytes: The maximum number of bytes to read
2366 * @bytesread: The actual number of bytes read is stored here. This
2367 * value can be zero if the handle is positioned at the end of the
2369 * @overlapped: points to a required %WapiOverlapped structure if
2370 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2373 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2374 * function reads up to @numbytes bytes from the file from the current
2375 * file position, and stores them in @buffer. If there are not enough
2376 * bytes left in the file, just the amount available will be read.
2377 * The actual number of bytes read is stored in @bytesread.
2379 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2380 * file position is ignored and the read position is taken from data
2381 * in the @overlapped structure.
2383 * Return value: %TRUE if the read succeeds (even if no bytes were
2384 * read due to an attempt to read past the end of the file), %FALSE on
2387 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2388 guint32 *bytesread, WapiOverlapped *overlapped)
2390 MonoW32HandleType type;
2392 type = mono_w32handle_get_type (handle);
2394 if(io_ops[type].readfile==NULL) {
2395 SetLastError (ERROR_INVALID_HANDLE);
2399 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2405 * @handle: The file handle to write to. The handle must have
2406 * %GENERIC_WRITE access.
2407 * @buffer: The buffer to read data from.
2408 * @numbytes: The maximum number of bytes to write.
2409 * @byteswritten: The actual number of bytes written is stored here.
2410 * If the handle is positioned at the file end, the length of the file
2411 * is extended. This parameter may be %NULL.
2412 * @overlapped: points to a required %WapiOverlapped structure if
2413 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2416 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2417 * function writes up to @numbytes bytes from @buffer to the file at
2418 * the current file position. If @handle is positioned at the end of
2419 * the file, the file is extended. The actual number of bytes written
2420 * is stored in @byteswritten.
2422 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2423 * file position is ignored and the write position is taken from data
2424 * in the @overlapped structure.
2426 * Return value: %TRUE if the write succeeds, %FALSE on error.
2428 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2429 guint32 *byteswritten, WapiOverlapped *overlapped)
2431 MonoW32HandleType type;
2433 type = mono_w32handle_get_type (handle);
2435 if(io_ops[type].writefile==NULL) {
2436 SetLastError (ERROR_INVALID_HANDLE);
2440 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2446 * @handle: Handle to open file. The handle must have
2447 * %GENERIC_WRITE access.
2449 * Flushes buffers of the file and causes all unwritten data to
2452 * Return value: %TRUE on success, %FALSE otherwise.
2454 gboolean FlushFileBuffers(gpointer handle)
2456 MonoW32HandleType type;
2458 type = mono_w32handle_get_type (handle);
2460 if(io_ops[type].flushfile==NULL) {
2461 SetLastError (ERROR_INVALID_HANDLE);
2465 return(io_ops[type].flushfile (handle));
2470 * @handle: The file handle to set. The handle must have
2471 * %GENERIC_WRITE access.
2473 * Moves the end-of-file position to the current position of the file
2474 * pointer. This function is used to truncate or extend a file.
2476 * Return value: %TRUE on success, %FALSE otherwise.
2478 gboolean SetEndOfFile(gpointer handle)
2480 MonoW32HandleType type;
2482 type = mono_w32handle_get_type (handle);
2484 if (io_ops[type].setendoffile == NULL) {
2485 SetLastError (ERROR_INVALID_HANDLE);
2489 return(io_ops[type].setendoffile (handle));
2494 * @handle: The file handle to set. The handle must have
2495 * %GENERIC_READ or %GENERIC_WRITE access.
2496 * @movedistance: Low 32 bits of a signed value that specifies the
2497 * number of bytes to move the file pointer.
2498 * @highmovedistance: Pointer to the high 32 bits of a signed value
2499 * that specifies the number of bytes to move the file pointer, or
2501 * @method: The starting point for the file pointer move.
2503 * Sets the file pointer of an open file.
2505 * The distance to move the file pointer is calculated from
2506 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2507 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2508 * is the low 32 bits and @highmovedistance a pointer to the high 32
2509 * bits of a 64 bit signed value. A positive distance moves the file
2510 * pointer forward from the position specified by @method; a negative
2511 * distance moves the file pointer backward.
2513 * If the library is compiled without large file support,
2514 * @highmovedistance is ignored and its value is set to zero on a
2515 * successful return.
2517 * Return value: On success, the low 32 bits of the new file pointer.
2518 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2519 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2521 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2522 gint32 *highmovedistance, WapiSeekMethod method)
2524 MonoW32HandleType type;
2526 type = mono_w32handle_get_type (handle);
2528 if (io_ops[type].seek == NULL) {
2529 SetLastError (ERROR_INVALID_HANDLE);
2530 return(INVALID_SET_FILE_POINTER);
2533 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2539 * @handle: The file handle to test.
2541 * Finds the type of file @handle.
2543 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2544 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2545 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2546 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2548 WapiFileType GetFileType(gpointer handle)
2550 MonoW32HandleType type;
2552 type = mono_w32handle_get_type (handle);
2554 if (io_ops[type].getfiletype == NULL) {
2555 SetLastError (ERROR_INVALID_HANDLE);
2556 return(FILE_TYPE_UNKNOWN);
2559 return(io_ops[type].getfiletype ());
2564 * @handle: The file handle to query. The handle must have
2565 * %GENERIC_READ or %GENERIC_WRITE access.
2566 * @highsize: If non-%NULL, the high 32 bits of the file size are
2569 * Retrieves the size of the file @handle.
2571 * If the library is compiled without large file support, @highsize
2572 * has its value set to zero on a successful return.
2574 * Return value: On success, the low 32 bits of the file size. If
2575 * @highsize is non-%NULL then the high 32 bits of the file size are
2576 * stored here. On failure %INVALID_FILE_SIZE is returned.
2578 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2580 MonoW32HandleType type;
2582 type = mono_w32handle_get_type (handle);
2584 if (io_ops[type].getfilesize == NULL) {
2585 SetLastError (ERROR_INVALID_HANDLE);
2586 return(INVALID_FILE_SIZE);
2589 return(io_ops[type].getfilesize (handle, highsize));
2594 * @handle: The file handle to query. The handle must have
2595 * %GENERIC_READ access.
2596 * @create_time: Points to a %WapiFileTime structure to receive the
2597 * number of ticks since the epoch that file was created. May be
2599 * @last_access: Points to a %WapiFileTime structure to receive the
2600 * number of ticks since the epoch when file was last accessed. May be
2602 * @last_write: Points to a %WapiFileTime structure to receive the
2603 * number of ticks since the epoch when file was last written to. May
2606 * Finds the number of ticks since the epoch that the file referenced
2607 * by @handle was created, last accessed and last modified. A tick is
2608 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2611 * Create time isn't recorded on POSIX file systems or reported by
2612 * stat(2), so that time is guessed by returning the oldest of the
2615 * Return value: %TRUE on success, %FALSE otherwise.
2617 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2618 WapiFileTime *last_access, WapiFileTime *last_write)
2620 MonoW32HandleType type;
2622 type = mono_w32handle_get_type (handle);
2624 if (io_ops[type].getfiletime == NULL) {
2625 SetLastError (ERROR_INVALID_HANDLE);
2629 return(io_ops[type].getfiletime (handle, create_time, last_access,
2635 * @handle: The file handle to set. The handle must have
2636 * %GENERIC_WRITE access.
2637 * @create_time: Points to a %WapiFileTime structure that contains the
2638 * number of ticks since the epoch that the file was created. May be
2640 * @last_access: Points to a %WapiFileTime structure that contains the
2641 * number of ticks since the epoch when the file was last accessed.
2643 * @last_write: Points to a %WapiFileTime structure that contains the
2644 * number of ticks since the epoch when the file was last written to.
2647 * Sets the number of ticks since the epoch that the file referenced
2648 * by @handle was created, last accessed or last modified. A tick is
2649 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2652 * Create time isn't recorded on POSIX file systems, and is ignored.
2654 * Return value: %TRUE on success, %FALSE otherwise.
2656 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2657 const WapiFileTime *last_access,
2658 const WapiFileTime *last_write)
2660 MonoW32HandleType type;
2662 type = mono_w32handle_get_type (handle);
2664 if (io_ops[type].setfiletime == NULL) {
2665 SetLastError (ERROR_INVALID_HANDLE);
2669 return(io_ops[type].setfiletime (handle, create_time, last_access,
2673 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2674 * January 1 1601 GMT
2677 #define TICKS_PER_MILLISECOND 10000L
2678 #define TICKS_PER_SECOND 10000000L
2679 #define TICKS_PER_MINUTE 600000000L
2680 #define TICKS_PER_HOUR 36000000000LL
2681 #define TICKS_PER_DAY 864000000000LL
2683 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2685 static const guint16 mon_yday[2][13]={
2686 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2687 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2691 * FileTimeToSystemTime:
2692 * @file_time: Points to a %WapiFileTime structure that contains the
2693 * number of ticks to convert.
2694 * @system_time: Points to a %WapiSystemTime structure to receive the
2697 * Converts a tick count into broken-out time values.
2699 * Return value: %TRUE on success, %FALSE otherwise.
2701 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2702 WapiSystemTime *system_time)
2704 gint64 file_ticks, totaldays, rem, y;
2707 if(system_time==NULL) {
2708 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: system_time NULL", __func__);
2710 SetLastError (ERROR_INVALID_PARAMETER);
2714 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2715 file_time->dwLowDateTime;
2717 /* Really compares if file_ticks>=0x8000000000000000
2718 * (LLONG_MAX+1) but we're working with a signed value for the
2719 * year and day calculation to work later
2722 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file_time too big", __func__);
2724 SetLastError (ERROR_INVALID_PARAMETER);
2728 totaldays=(file_ticks / TICKS_PER_DAY);
2729 rem = file_ticks % TICKS_PER_DAY;
2730 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2732 system_time->wHour=rem/TICKS_PER_HOUR;
2733 rem %= TICKS_PER_HOUR;
2734 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2736 system_time->wMinute = rem / TICKS_PER_MINUTE;
2737 rem %= TICKS_PER_MINUTE;
2738 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2741 system_time->wSecond = rem / TICKS_PER_SECOND;
2742 rem %= TICKS_PER_SECOND;
2743 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2746 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2747 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Milliseconds: %d", __func__,
2748 system_time->wMilliseconds);
2750 /* January 1, 1601 was a Monday, according to Emacs calendar */
2751 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2752 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2754 /* This algorithm to find year and month given days from epoch
2759 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2760 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2762 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2763 /* Guess a corrected year, assuming 365 days per year */
2764 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2765 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld yg: %lld y: %lld", __func__,
2768 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2769 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2771 /* Adjust days and y to match the guessed year. */
2772 totaldays -= ((yg - y) * 365
2773 + LEAPS_THRU_END_OF (yg - 1)
2774 - LEAPS_THRU_END_OF (y - 1));
2775 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2777 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: y: %lld", __func__, y);
2780 system_time->wYear = y;
2781 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Year: %d", __func__, system_time->wYear);
2783 ip = mon_yday[isleap(y)];
2785 for(y=11; totaldays < ip[y]; --y) {
2789 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2791 system_time->wMonth = y + 1;
2792 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Month: %d", __func__, system_time->wMonth);
2794 system_time->wDay = totaldays + 1;
2795 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day: %d", __func__, system_time->wDay);
2800 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2802 struct _WapiHandle_find find_handle = {0};
2804 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2807 if (pattern == NULL) {
2808 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: pattern is NULL", __func__);
2810 SetLastError (ERROR_PATH_NOT_FOUND);
2811 return(INVALID_HANDLE_VALUE);
2814 utf8_pattern = mono_unicode_to_external (pattern);
2815 if (utf8_pattern == NULL) {
2816 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2818 SetLastError (ERROR_INVALID_NAME);
2819 return(INVALID_HANDLE_VALUE);
2822 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for [%s]", __func__, utf8_pattern);
2824 /* Figure out which bit of the pattern is the directory */
2825 dir_part = _wapi_dirname (utf8_pattern);
2826 entry_part = _wapi_basename (utf8_pattern);
2829 /* Don't do this check for now, it breaks if directories
2830 * really do have metachars in their names (see bug 58116).
2831 * FIXME: Figure out a better solution to keep some checks...
2833 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2834 SetLastError (ERROR_INVALID_NAME);
2836 g_free (entry_part);
2837 g_free (utf8_pattern);
2838 return(INVALID_HANDLE_VALUE);
2842 /* The pattern can specify a directory or a set of files.
2844 * The pattern can have wildcard characters ? and *, but only
2845 * in the section after the last directory delimiter. (Return
2846 * ERROR_INVALID_NAME if there are wildcards in earlier path
2847 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2848 * means "match one character", "??" seems to mean "match one
2849 * or two characters", "???" seems to mean "match one, two or
2850 * three characters", etc. Windows will also try and match
2851 * the mangled "short name" of files, so 8 character patterns
2852 * with wildcards will show some surprising results.
2854 * All the written documentation I can find says that '?'
2855 * should only match one character, and doesn't mention '??',
2856 * '???' etc. I'm going to assume that the strict behaviour
2857 * (ie '???' means three and only three characters) is the
2858 * correct one, because that lets me use fnmatch(3) rather
2859 * than mess around with regexes.
2862 find_handle.namelist = NULL;
2863 result = _wapi_io_scandir (dir_part, entry_part,
2864 &find_handle.namelist);
2867 /* No files, which windows seems to call
2870 SetLastError (ERROR_FILE_NOT_FOUND);
2871 g_free (utf8_pattern);
2872 g_free (entry_part);
2874 return (INVALID_HANDLE_VALUE);
2878 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2879 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: scandir error: %s", __func__, g_strerror (errno));
2880 g_free (utf8_pattern);
2881 g_free (entry_part);
2883 return (INVALID_HANDLE_VALUE);
2886 g_free (utf8_pattern);
2887 g_free (entry_part);
2889 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Got %d matches", __func__, result);
2891 find_handle.dir_part = dir_part;
2892 find_handle.num = result;
2893 find_handle.count = 0;
2895 handle = mono_w32handle_new (MONO_W32HANDLE_FIND, &find_handle);
2896 if (handle == INVALID_HANDLE_VALUE) {
2897 g_warning ("%s: error creating find handle", __func__);
2899 g_free (entry_part);
2900 g_free (utf8_pattern);
2901 SetLastError (ERROR_GEN_FAILURE);
2903 return(INVALID_HANDLE_VALUE);
2906 if (handle != INVALID_HANDLE_VALUE &&
2907 !FindNextFile (handle, find_data)) {
2909 SetLastError (ERROR_NO_MORE_FILES);
2910 handle = INVALID_HANDLE_VALUE;
2916 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2918 struct _WapiHandle_find *find_handle;
2920 struct stat buf, linkbuf;
2923 gchar *utf8_filename, *utf8_basename;
2924 gunichar2 *utf16_basename;
2928 gboolean ret = FALSE;
2930 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FIND,
2931 (gpointer *)&find_handle);
2933 g_warning ("%s: error looking up find handle %p", __func__,
2935 SetLastError (ERROR_INVALID_HANDLE);
2939 thr_ret = mono_w32handle_lock_handle (handle);
2940 g_assert (thr_ret == 0);
2943 if (find_handle->count >= find_handle->num) {
2944 SetLastError (ERROR_NO_MORE_FILES);
2948 /* stat next match */
2950 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2952 result = _wapi_stat (filename, &buf);
2953 if (result == -1 && errno == ENOENT) {
2954 /* Might be a dangling symlink */
2955 result = _wapi_lstat (filename, &buf);
2959 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: stat failed: %s", __func__, filename);
2965 #ifndef __native_client__
2966 result = _wapi_lstat (filename, &linkbuf);
2968 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lstat failed: %s", __func__, filename);
2975 utf8_filename = mono_utf8_from_external (filename);
2976 if (utf8_filename == NULL) {
2977 /* We couldn't turn this filename into utf8 (eg the
2978 * encoding of the name wasn't convertible), so just
2981 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2988 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Found [%s]", __func__, utf8_filename);
2990 /* fill data block */
2992 if (buf.st_mtime < buf.st_ctime)
2993 create_time = buf.st_mtime;
2995 create_time = buf.st_ctime;
2997 #ifdef __native_client__
2998 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, NULL);
3000 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
3003 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
3004 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
3005 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
3007 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3008 find_data->nFileSizeHigh = 0;
3009 find_data->nFileSizeLow = 0;
3011 find_data->nFileSizeHigh = buf.st_size >> 32;
3012 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3015 find_data->dwReserved0 = 0;
3016 find_data->dwReserved1 = 0;
3018 utf8_basename = _wapi_basename (utf8_filename);
3019 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
3021 if(utf16_basename==NULL) {
3022 g_free (utf8_basename);
3023 g_free (utf8_filename);
3028 /* utf16 is 2 * utf8 */
3031 memset (find_data->cFileName, '\0', (MAX_PATH*2));
3033 /* Truncating a utf16 string like this might leave the last
3036 memcpy (find_data->cFileName, utf16_basename,
3037 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3039 find_data->cAlternateFileName [0] = 0; /* not used */
3041 g_free (utf8_basename);
3042 g_free (utf8_filename);
3043 g_free (utf16_basename);
3046 thr_ret = mono_w32handle_unlock_handle (handle);
3047 g_assert (thr_ret == 0);
3054 * @wapi_handle: the find handle to close.
3056 * Closes find handle @wapi_handle
3058 * Return value: %TRUE on success, %FALSE otherwise.
3060 gboolean FindClose (gpointer handle)
3062 struct _WapiHandle_find *find_handle;
3066 if (handle == NULL) {
3067 SetLastError (ERROR_INVALID_HANDLE);
3071 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FIND,
3072 (gpointer *)&find_handle);
3074 g_warning ("%s: error looking up find handle %p", __func__,
3076 SetLastError (ERROR_INVALID_HANDLE);
3080 thr_ret = mono_w32handle_lock_handle (handle);
3081 g_assert (thr_ret == 0);
3083 g_strfreev (find_handle->namelist);
3084 g_free (find_handle->dir_part);
3086 thr_ret = mono_w32handle_unlock_handle (handle);
3087 g_assert (thr_ret == 0);
3089 mono_w32handle_unref (handle);
3096 * @name: a pointer to a NULL-terminated unicode string, that names
3097 * the directory to be created.
3098 * @security: ignored for now
3100 * Creates directory @name
3102 * Return value: %TRUE on success, %FALSE otherwise.
3104 gboolean CreateDirectory (const gunichar2 *name,
3105 WapiSecurityAttributes *security)
3111 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3113 SetLastError (ERROR_INVALID_NAME);
3117 utf8_name = mono_unicode_to_external (name);
3118 if (utf8_name == NULL) {
3119 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3121 SetLastError (ERROR_INVALID_NAME);
3125 result = _wapi_mkdir (utf8_name, 0777);
3132 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3139 * @name: a pointer to a NULL-terminated unicode string, that names
3140 * the directory to be removed.
3142 * Removes directory @name
3144 * Return value: %TRUE on success, %FALSE otherwise.
3146 gboolean RemoveDirectory (const gunichar2 *name)
3152 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3154 SetLastError (ERROR_INVALID_NAME);
3158 utf8_name = mono_unicode_to_external (name);
3159 if (utf8_name == NULL) {
3160 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3162 SetLastError (ERROR_INVALID_NAME);
3166 result = _wapi_rmdir (utf8_name);
3168 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3179 * GetFileAttributes:
3180 * @name: a pointer to a NULL-terminated unicode filename.
3182 * Gets the attributes for @name;
3184 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3186 guint32 GetFileAttributes (const gunichar2 *name)
3189 struct stat buf, linkbuf;
3194 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3196 SetLastError (ERROR_INVALID_NAME);
3200 utf8_name = mono_unicode_to_external (name);
3201 if (utf8_name == NULL) {
3202 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3204 SetLastError (ERROR_INVALID_PARAMETER);
3205 return (INVALID_FILE_ATTRIBUTES);
3208 result = _wapi_stat (utf8_name, &buf);
3209 if (result == -1 && errno == ENOENT) {
3210 /* Might be a dangling symlink... */
3211 result = _wapi_lstat (utf8_name, &buf);
3215 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3217 return (INVALID_FILE_ATTRIBUTES);
3220 #ifndef __native_client__
3221 result = _wapi_lstat (utf8_name, &linkbuf);
3223 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3225 return (INVALID_FILE_ATTRIBUTES);
3229 #ifdef __native_client__
3230 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, NULL);
3232 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3241 * GetFileAttributesEx:
3242 * @name: a pointer to a NULL-terminated unicode filename.
3243 * @level: must be GetFileExInfoStandard
3244 * @info: pointer to a WapiFileAttributesData structure
3246 * Gets attributes, size and filetimes for @name;
3248 * Return value: %TRUE on success, %FALSE on failure
3250 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3253 WapiFileAttributesData *data;
3255 struct stat buf, linkbuf;
3259 if (level != GetFileExInfoStandard) {
3260 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: info level %d not supported.", __func__,
3263 SetLastError (ERROR_INVALID_PARAMETER);
3268 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3270 SetLastError (ERROR_INVALID_NAME);
3274 utf8_name = mono_unicode_to_external (name);
3275 if (utf8_name == NULL) {
3276 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3278 SetLastError (ERROR_INVALID_PARAMETER);
3282 result = _wapi_stat (utf8_name, &buf);
3283 if (result == -1 && errno == ENOENT) {
3284 /* Might be a dangling symlink... */
3285 result = _wapi_lstat (utf8_name, &buf);
3289 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3294 result = _wapi_lstat (utf8_name, &linkbuf);
3296 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3301 /* fill data block */
3303 data = (WapiFileAttributesData *)info;
3305 if (buf.st_mtime < buf.st_ctime)
3306 create_time = buf.st_mtime;
3308 create_time = buf.st_ctime;
3310 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3316 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3317 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3318 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3320 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3321 data->nFileSizeHigh = 0;
3322 data->nFileSizeLow = 0;
3325 data->nFileSizeHigh = buf.st_size >> 32;
3326 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3334 * @name: name of file
3335 * @attrs: attributes to set
3337 * Changes the attributes on a named file.
3339 * Return value: %TRUE on success, %FALSE on failure.
3341 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3343 /* FIXME: think of something clever to do on unix */
3349 * Currently we only handle one *internal* case, with a value that is
3350 * not standard: 0x80000000, which means `set executable bit'
3354 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3356 SetLastError (ERROR_INVALID_NAME);
3360 utf8_name = mono_unicode_to_external (name);
3361 if (utf8_name == NULL) {
3362 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3364 SetLastError (ERROR_INVALID_NAME);
3368 result = _wapi_stat (utf8_name, &buf);
3369 if (result == -1 && errno == ENOENT) {
3370 /* Might be a dangling symlink... */
3371 result = _wapi_lstat (utf8_name, &buf);
3375 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3380 /* Contrary to the documentation, ms allows NORMAL to be
3381 * specified along with other attributes, so dont bother to
3382 * catch that case here.
3384 if (attrs & FILE_ATTRIBUTE_READONLY) {
3385 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWUSR | S_IWOTH | S_IWGRP));
3387 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWUSR);
3390 /* Ignore the other attributes for now */
3392 if (attrs & 0x80000000){
3393 mode_t exec_mask = 0;
3395 if ((buf.st_mode & S_IRUSR) != 0)
3396 exec_mask |= S_IXUSR;
3398 if ((buf.st_mode & S_IRGRP) != 0)
3399 exec_mask |= S_IXGRP;
3401 if ((buf.st_mode & S_IROTH) != 0)
3402 exec_mask |= S_IXOTH;
3404 result = chmod (utf8_name, buf.st_mode | exec_mask);
3406 /* Don't bother to reset executable (might need to change this
3416 * GetCurrentDirectory
3417 * @length: size of the buffer
3418 * @buffer: pointer to buffer that recieves path
3420 * Retrieves the current directory for the current process.
3422 * Return value: number of characters in buffer on success, zero on failure
3424 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3426 gunichar2 *utf16_path;
3430 #ifdef __native_client__
3431 gchar *path = g_get_current_dir ();
3432 if (length < strlen(path) + 1 || path == NULL)
3434 memcpy (buffer, path, strlen(path) + 1);
3436 if (getcwd ((char*)buffer, length) == NULL) {
3437 if (errno == ERANGE) { /*buffer length is not big enough */
3438 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*/
3441 utf16_path = mono_unicode_from_external (path, &bytes);
3442 g_free (utf16_path);
3446 _wapi_set_last_error_from_errno ();
3451 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3452 count = (bytes/2)+1;
3453 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3455 /* Add the terminator */
3456 memset (buffer, '\0', bytes+2);
3457 memcpy (buffer, utf16_path, bytes);
3459 g_free (utf16_path);
3465 * SetCurrentDirectory
3466 * @path: path to new directory
3468 * Changes the directory path for the current process.
3470 * Return value: %TRUE on success, %FALSE on failure.
3472 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3478 SetLastError (ERROR_INVALID_PARAMETER);
3482 utf8_path = mono_unicode_to_external (path);
3483 if (_wapi_chdir (utf8_path) != 0) {
3484 _wapi_set_last_error_from_errno ();
3494 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3495 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3497 struct _WapiHandle_file pipe_read_handle = {0};
3498 struct _WapiHandle_file pipe_write_handle = {0};
3499 gpointer read_handle;
3500 gpointer write_handle;
3504 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Creating pipe", __func__);
3508 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error creating pipe: %s", __func__,
3511 _wapi_set_last_error_from_errno ();
3515 if (filedes[0] >= mono_w32handle_fd_reserve ||
3516 filedes[1] >= mono_w32handle_fd_reserve) {
3517 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
3519 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3527 /* filedes[0] is open for reading, filedes[1] for writing */
3529 pipe_read_handle.fd = filedes [0];
3530 pipe_read_handle.fileaccess = GENERIC_READ;
3531 read_handle = mono_w32handle_new_fd (MONO_W32HANDLE_PIPE, filedes[0],
3533 if (read_handle == INVALID_HANDLE_VALUE) {
3534 g_warning ("%s: error creating pipe read handle", __func__);
3537 SetLastError (ERROR_GEN_FAILURE);
3542 pipe_write_handle.fd = filedes [1];
3543 pipe_write_handle.fileaccess = GENERIC_WRITE;
3544 write_handle = mono_w32handle_new_fd (MONO_W32HANDLE_PIPE, filedes[1],
3545 &pipe_write_handle);
3546 if (write_handle == INVALID_HANDLE_VALUE) {
3547 g_warning ("%s: error creating pipe write handle", __func__);
3548 mono_w32handle_unref (read_handle);
3552 SetLastError (ERROR_GEN_FAILURE);
3557 *readpipe = read_handle;
3558 *writepipe = write_handle;
3560 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning pipe: read handle %p, write handle %p",
3561 __func__, read_handle, write_handle);
3566 #ifdef HAVE_GETFSSTAT
3567 /* Darwin has getfsstat */
3568 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3570 struct statfs *stats;
3573 glong length, total = 0;
3575 n = getfsstat (NULL, 0, MNT_NOWAIT);
3578 size = n * sizeof (struct statfs);
3579 stats = (struct statfs *) g_malloc (size);
3582 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3586 for (i = 0; i < n; i++){
3587 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3588 if (total + length < len){
3589 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3590 buf [total+length] = 0;
3593 total += length + 1;
3602 /* In-place octal sequence replacement */
3604 unescape_octal (gchar *str)
3613 while (*rptr != '\0') {
3614 if (*rptr == '\\') {
3617 c = (*(rptr++) - '0') << 6;
3618 c += (*(rptr++) - '0') << 3;
3619 c += *(rptr++) - '0';
3621 } else if (wptr != rptr) {
3629 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3632 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3633 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3634 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3639 guint32 buffer_index;
3640 guint32 mountpoint_index;
3641 guint32 field_number;
3642 guint32 allocated_size;
3643 guint32 fsname_index;
3644 guint32 fstype_index;
3645 gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3646 gchar *mountpoint_allocated;
3647 gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3648 gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3649 gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3652 gboolean check_mount_source;
3653 } LinuxMountInfoParseState;
3655 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3656 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3657 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3658 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3660 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3664 LinuxMountInfoParseState state;
3665 gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3667 memset (buf, 0, len * sizeof (gunichar2));
3668 fd = open ("/proc/self/mountinfo", O_RDONLY);
3670 parser = GetLogicalDriveStrings_MountInfo;
3672 fd = open ("/proc/mounts", O_RDONLY);
3674 parser = GetLogicalDriveStrings_Mounts;
3678 ret = GetLogicalDriveStrings_Mtab (len, buf);
3682 memset (&state, 0, sizeof (LinuxMountInfoParseState));
3683 state.field_number = 1;
3684 state.delimiter = ' ';
3686 while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3687 state.buffer_index = 0;
3689 while ((*parser)(len, buf, &state)) {
3690 if (state.buffer [state.buffer_index] == '\n') {
3691 gboolean quit = add_drive_string (len, buf, &state);
3692 state.field_number = 1;
3693 state.buffer_index++;
3694 if (state.mountpoint_allocated) {
3695 g_free (state.mountpoint_allocated);
3696 state.mountpoint_allocated = NULL;
3713 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3717 if (state->field_number == 1)
3718 state->check_mount_source = TRUE;
3720 while (state->buffer_index < (guint32)state->nbytes) {
3721 if (state->buffer [state->buffer_index] == state->delimiter) {
3722 state->field_number++;
3723 switch (state->field_number) {
3725 state->mountpoint_index = 0;
3729 if (state->mountpoint_allocated)
3730 state->mountpoint_allocated [state->mountpoint_index] = 0;
3732 state->mountpoint [state->mountpoint_index] = 0;
3736 ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3738 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3740 state->buffer_index = state->nbytes;
3743 state->buffer_index++;
3745 } else if (state->buffer [state->buffer_index] == '\n')
3748 switch (state->field_number) {
3750 if (state->check_mount_source) {
3751 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3752 /* We can ignore the rest, it's a device
3754 state->check_mount_source = FALSE;
3755 state->fsname [state->fsname_index++] = '/';
3758 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3759 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3764 append_to_mountpoint (state);
3768 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3769 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3773 state->buffer_index++;
3779 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3781 while (state->buffer_index < (guint32)state->nbytes) {
3782 if (state->buffer [state->buffer_index] == state->delimiter) {
3783 state->field_number++;
3784 switch (state->field_number) {
3786 state->mountpoint_index = 0;
3790 if (state->mountpoint_allocated)
3791 state->mountpoint_allocated [state->mountpoint_index] = 0;
3793 state->mountpoint [state->mountpoint_index] = 0;
3797 state->delimiter = '-';
3801 state->delimiter = ' ';
3805 state->check_mount_source = TRUE;
3808 state->buffer_index++;
3810 } else if (state->buffer [state->buffer_index] == '\n')
3813 switch (state->field_number) {
3815 append_to_mountpoint (state);
3819 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3820 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3824 if (state->check_mount_source) {
3825 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3826 /* We can ignore the rest, it's a device
3828 state->check_mount_source = FALSE;
3829 state->fsname [state->fsname_index++] = '/';
3832 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3833 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3838 state->buffer_index++;
3845 append_to_mountpoint (LinuxMountInfoParseState *state)
3847 gchar ch = state->buffer [state->buffer_index];
3848 if (state->mountpoint_allocated) {
3849 if (state->mountpoint_index >= state->allocated_size) {
3850 guint32 newsize = (state->allocated_size << 1) + 1;
3851 gchar *newbuf = (gchar *)g_malloc0 (newsize * sizeof (gchar));
3853 memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3854 g_free (state->mountpoint_allocated);
3855 state->mountpoint_allocated = newbuf;
3856 state->allocated_size = newsize;
3858 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3860 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3861 state->allocated_size = (state->mountpoint_index << 1) + 1;
3862 state->mountpoint_allocated = (gchar *)g_malloc0 (state->allocated_size * sizeof (gchar));
3863 memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3864 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3866 state->mountpoint [state->mountpoint_index++] = ch;
3871 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3873 gboolean quit = FALSE;
3874 gboolean ignore_entry;
3876 if (state->fsname_index == 1 && state->fsname [0] == '/')
3877 ignore_entry = FALSE;
3878 else if (memcmp ("overlay", state->fsname, state->fsname_index) == 0 ||
3879 memcmp ("aufs", state->fstype, state->fstype_index) == 0) {
3880 /* Don't ignore overlayfs and aufs - these might be used on Docker
3881 * (https://bugzilla.xamarin.com/show_bug.cgi?id=31021) */
3882 ignore_entry = FALSE;
3883 } else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0) {
3884 ignore_entry = TRUE;
3885 } else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3886 /* Ignore GNOME's gvfs */
3887 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3888 ignore_entry = TRUE;
3890 ignore_entry = FALSE;
3891 } else if (state->fstype_index == 3 && memcmp ("nfs", state->fstype, state->fstype_index) == 0)
3892 ignore_entry = FALSE;
3894 ignore_entry = TRUE;
3896 if (!ignore_entry) {
3899 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3901 unescape_octal (mountpoint);
3902 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3903 if (state->total + length + 1 > len) {
3905 state->total = len * 2;
3908 memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3909 state->total += length;
3913 state->fsname_index = 0;
3914 state->fstype_index = 0;
3920 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3922 return GetLogicalDriveStrings_Mtab (len, buf);
3926 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3929 gunichar2 *ptr, *dir;
3930 glong length, total = 0;
3934 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3939 /* Sigh, mntent and friends don't work well.
3940 * It stops on the first line that doesn't begin with a '/'.
3941 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3942 fp = fopen ("/etc/mtab", "rt");
3944 fp = fopen ("/etc/mnttab", "rt");
3950 while (fgets (buffer, 512, fp) != NULL) {
3954 splitted = g_strsplit (buffer, " ", 0);
3955 if (!*splitted || !*(splitted + 1)) {
3956 g_strfreev (splitted);
3960 unescape_octal (*(splitted + 1));
3961 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3962 g_strfreev (splitted);
3963 if (total + length + 1 > len) {
3966 return len * 2; /* guess */
3969 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3971 total += length + 1;
3976 /* Commented out, does not work with my mtab!!! - Gonz */
3977 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3981 gunichar2 *ptr, *dir;
3982 glong len, total = 0;
3985 fp = setmntent ("/etc/mtab", "rt");
3987 fp = setmntent ("/etc/mnttab", "rt");
3993 while ((mnt = getmntent (fp)) != NULL) {
3994 g_print ("GOT %s\n", mnt->mnt_dir);
3995 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3996 if (total + len + 1 > len) {
3997 return len * 2; /* guess */
4000 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
4012 #if defined(HAVE_STATVFS) || defined(HAVE_STATFS)
4013 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4014 WapiULargeInteger *total_number_of_bytes,
4015 WapiULargeInteger *total_number_of_free_bytes)
4018 struct statvfs fsstat;
4019 #elif defined(HAVE_STATFS)
4020 struct statfs fsstat;
4022 gboolean isreadonly;
4023 gchar *utf8_path_name;
4025 unsigned long block_size;
4027 if (path_name == NULL) {
4028 utf8_path_name = g_strdup (g_get_current_dir());
4029 if (utf8_path_name == NULL) {
4030 SetLastError (ERROR_DIRECTORY);
4035 utf8_path_name = mono_unicode_to_external (path_name);
4036 if (utf8_path_name == NULL) {
4037 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4039 SetLastError (ERROR_INVALID_NAME);
4046 ret = statvfs (utf8_path_name, &fsstat);
4047 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
4048 block_size = fsstat.f_frsize;
4049 #elif defined(HAVE_STATFS)
4050 ret = statfs (utf8_path_name, &fsstat);
4051 #if defined (MNT_RDONLY)
4052 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
4053 #elif defined (MS_RDONLY)
4054 isreadonly = ((fsstat.f_flags & MS_RDONLY) == MS_RDONLY);
4056 block_size = fsstat.f_bsize;
4058 } while(ret == -1 && errno == EINTR);
4060 g_free(utf8_path_name);
4063 _wapi_set_last_error_from_errno ();
4064 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: statvfs failed: %s", __func__, strerror (errno));
4068 /* total number of free bytes for non-root */
4069 if (free_bytes_avail != NULL) {
4071 free_bytes_avail->QuadPart = 0;
4074 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
4078 /* total number of bytes available for non-root */
4079 if (total_number_of_bytes != NULL) {
4080 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
4083 /* total number of bytes available for root */
4084 if (total_number_of_free_bytes != NULL) {
4086 total_number_of_free_bytes->QuadPart = 0;
4089 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
4096 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4097 WapiULargeInteger *total_number_of_bytes,
4098 WapiULargeInteger *total_number_of_free_bytes)
4100 if (free_bytes_avail != NULL) {
4101 free_bytes_avail->QuadPart = (guint64) -1;
4104 if (total_number_of_bytes != NULL) {
4105 total_number_of_bytes->QuadPart = (guint64) -1;
4108 if (total_number_of_free_bytes != NULL) {
4109 total_number_of_free_bytes->QuadPart = (guint64) -1;
4117 * General Unix support
4122 const long fstypeid;
4124 const gchar* fstype;
4127 static _wapi_drive_type _wapi_drive_types[] = {
4129 { DRIVE_REMOTE, "afp" },
4130 { DRIVE_REMOTE, "autofs" },
4131 { DRIVE_CDROM, "cddafs" },
4132 { DRIVE_CDROM, "cd9660" },
4133 { DRIVE_RAMDISK, "devfs" },
4134 { DRIVE_FIXED, "exfat" },
4135 { DRIVE_RAMDISK, "fdesc" },
4136 { DRIVE_REMOTE, "ftp" },
4137 { DRIVE_FIXED, "hfs" },
4138 { DRIVE_FIXED, "msdos" },
4139 { DRIVE_REMOTE, "nfs" },
4140 { DRIVE_FIXED, "ntfs" },
4141 { DRIVE_REMOTE, "smbfs" },
4142 { DRIVE_FIXED, "udf" },
4143 { DRIVE_REMOTE, "webdav" },
4144 { DRIVE_UNKNOWN, NULL }
4146 { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
4147 { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
4148 { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
4149 { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
4150 { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
4151 { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
4152 { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
4153 { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
4154 { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
4155 { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
4156 { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
4157 { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
4158 { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
4159 { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
4160 { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
4161 { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
4162 { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
4163 { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4164 { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4165 { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4166 { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4167 { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4168 { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4169 { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4170 { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4171 { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4172 { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4173 { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4174 { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4175 { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4176 { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4177 { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4178 { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4179 { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4180 { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4181 { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4182 { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4183 { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4184 { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4185 { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4186 { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4187 { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4188 { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4189 { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4190 { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4191 { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4192 { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4193 { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4194 { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4195 { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4196 { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4197 { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4198 { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4199 { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4200 { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4201 { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4202 { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4203 { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4204 { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4205 { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4206 { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4207 { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4208 { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4209 { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4210 { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4211 { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4212 { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4213 { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4214 { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4215 { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4216 { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4217 { DRIVE_UNKNOWN, 0, NULL}
4219 { DRIVE_RAMDISK, "ramfs" },
4220 { DRIVE_RAMDISK, "tmpfs" },
4221 { DRIVE_RAMDISK, "proc" },
4222 { DRIVE_RAMDISK, "sysfs" },
4223 { DRIVE_RAMDISK, "debugfs" },
4224 { DRIVE_RAMDISK, "devpts" },
4225 { DRIVE_RAMDISK, "securityfs" },
4226 { DRIVE_CDROM, "iso9660" },
4227 { DRIVE_FIXED, "ext2" },
4228 { DRIVE_FIXED, "ext3" },
4229 { DRIVE_FIXED, "ext4" },
4230 { DRIVE_FIXED, "sysv" },
4231 { DRIVE_FIXED, "reiserfs" },
4232 { DRIVE_FIXED, "ufs" },
4233 { DRIVE_FIXED, "vfat" },
4234 { DRIVE_FIXED, "msdos" },
4235 { DRIVE_FIXED, "udf" },
4236 { DRIVE_FIXED, "hfs" },
4237 { DRIVE_FIXED, "hpfs" },
4238 { DRIVE_FIXED, "qnx4" },
4239 { DRIVE_FIXED, "ntfs" },
4240 { DRIVE_FIXED, "ntfs-3g" },
4241 { DRIVE_REMOTE, "smbfs" },
4242 { DRIVE_REMOTE, "fuse" },
4243 { DRIVE_REMOTE, "nfs" },
4244 { DRIVE_REMOTE, "nfs4" },
4245 { DRIVE_REMOTE, "cifs" },
4246 { DRIVE_REMOTE, "ncpfs" },
4247 { DRIVE_REMOTE, "coda" },
4248 { DRIVE_REMOTE, "afs" },
4249 { DRIVE_UNKNOWN, NULL }
4254 static guint32 _wapi_get_drive_type(long f_type)
4256 _wapi_drive_type *current;
4258 current = &_wapi_drive_types[0];
4259 while (current->drive_type != DRIVE_UNKNOWN) {
4260 if (current->fstypeid == f_type)
4261 return current->drive_type;
4265 return DRIVE_UNKNOWN;
4268 static guint32 _wapi_get_drive_type(const gchar* fstype)
4270 _wapi_drive_type *current;
4272 current = &_wapi_drive_types[0];
4273 while (current->drive_type != DRIVE_UNKNOWN) {
4274 if (strcmp (current->fstype, fstype) == 0)
4280 return current->drive_type;
4284 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4286 GetDriveTypeFromPath (const char *utf8_root_path_name)
4290 if (statfs (utf8_root_path_name, &buf) == -1)
4291 return DRIVE_UNKNOWN;
4293 return _wapi_get_drive_type (buf.f_fstypename);
4295 return _wapi_get_drive_type (buf.f_type);
4300 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4307 fp = fopen ("/etc/mtab", "rt");
4309 fp = fopen ("/etc/mnttab", "rt");
4311 return(DRIVE_UNKNOWN);
4314 drive_type = DRIVE_NO_ROOT_DIR;
4315 while (fgets (buffer, 512, fp) != NULL) {
4316 splitted = g_strsplit (buffer, " ", 0);
4317 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4318 g_strfreev (splitted);
4322 /* compare given root_path_name with the one from mtab,
4323 if length of utf8_root_path_name is zero it must be the root dir */
4324 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4325 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4326 drive_type = _wapi_get_drive_type (*(splitted + 2));
4327 /* it is possible this path might be mounted again with
4328 a known type...keep looking */
4329 if (drive_type != DRIVE_UNKNOWN) {
4330 g_strfreev (splitted);
4335 g_strfreev (splitted);
4343 guint32 GetDriveType(const gunichar2 *root_path_name)
4345 gchar *utf8_root_path_name;
4348 if (root_path_name == NULL) {
4349 utf8_root_path_name = g_strdup (g_get_current_dir());
4350 if (utf8_root_path_name == NULL) {
4351 return(DRIVE_NO_ROOT_DIR);
4355 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4356 if (utf8_root_path_name == NULL) {
4357 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4358 return(DRIVE_NO_ROOT_DIR);
4361 /* strip trailing slash for compare below */
4362 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4363 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4366 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4367 g_free (utf8_root_path_name);
4369 return (drive_type);
4372 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__) || defined(__FreeBSD_kernel__)
4374 get_fstypename (gchar *utfpath)
4376 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4379 _wapi_drive_type *current;
4381 if (statfs (utfpath, &stat) == -1)
4384 return g_strdup (stat.f_fstypename);
4386 current = &_wapi_drive_types[0];
4387 while (current->drive_type != DRIVE_UNKNOWN) {
4388 if (stat.f_type == current->fstypeid)
4389 return g_strdup (current->fstype);
4399 /* Linux has struct statfs which has a different layout */
4401 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4405 gboolean status = FALSE;
4408 // We only support getting the file system type
4409 if (fsbuffer == NULL)
4412 utfpath = mono_unicode_to_external (path);
4413 if ((fstypename = get_fstypename (utfpath)) != NULL){
4414 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4415 if (ret != NULL && len < fsbuffersize){
4416 memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4422 g_free (fstypename);
4430 _wapi_io_init (void)
4432 mono_os_mutex_init (&stdhandle_mutex);
4434 mono_w32handle_register_ops (MONO_W32HANDLE_FILE, &_wapi_file_ops);
4435 mono_w32handle_register_ops (MONO_W32HANDLE_CONSOLE, &_wapi_console_ops);
4436 mono_w32handle_register_ops (MONO_W32HANDLE_FIND, &_wapi_find_ops);
4437 mono_w32handle_register_ops (MONO_W32HANDLE_PIPE, &_wapi_pipe_ops);
4439 /* mono_w32handle_register_capabilities (MONO_W32HANDLE_FILE, */
4440 /* MONO_W32HANDLE_CAP_WAIT); */
4441 /* mono_w32handle_register_capabilities (MONO_W32HANDLE_CONSOLE, */
4442 /* MONO_W32HANDLE_CAP_WAIT); */
4444 if (g_getenv ("MONO_STRICT_IO_EMULATION"))
4445 lock_while_writing = TRUE;
4449 _wapi_io_cleanup (void)
4451 if (file_share_hash) {
4452 g_hash_table_destroy (file_share_hash);
4453 mono_os_mutex_destroy (&file_share_hash_mutex);