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/thread-private.h>
44 #include <mono/io-layer/io-portability.h>
45 #include <mono/io-layer/io-trace.h>
46 #include <mono/utils/strenc.h>
47 #include <mono/utils/mono-once.h>
48 #include <mono/utils/mono-logger-internals.h>
49 #include <mono/utils/w32handle.h>
52 * If SHM is disabled, this will point to a hash of _WapiFileShare structures, otherwise
53 * it will be NULL. We use this instead of _wapi_fileshare_layout to avoid allocating a
56 static GHashTable *file_share_hash;
57 static mono_mutex_t file_share_hash_mutex;
59 #define file_share_hash_lock() mono_os_mutex_lock (&file_share_hash_mutex)
60 #define file_share_hash_unlock() mono_os_mutex_unlock (&file_share_hash_mutex)
63 _wapi_handle_share_release (_WapiFileShare *share_info)
67 g_assert (share_info->handle_refs > 0);
69 /* Prevent new entries racing with us */
70 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_FILESHARE);
71 g_assert(thr_ret == 0);
73 if (InterlockedDecrement ((gint32 *)&share_info->handle_refs) == 0) {
74 file_share_hash_lock ();
75 g_hash_table_remove (file_share_hash, share_info);
76 file_share_hash_unlock ();
79 thr_ret = _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_FILESHARE);
80 g_assert (thr_ret == 0);
84 wapi_share_info_equal (gconstpointer ka, gconstpointer kb)
86 const _WapiFileShare *s1 = (const _WapiFileShare *)ka;
87 const _WapiFileShare *s2 = (const _WapiFileShare *)kb;
89 return (s1->device == s2->device && s1->inode == s2->inode) ? 1 : 0;
93 wapi_share_info_hash (gconstpointer data)
95 const _WapiFileShare *s = (const _WapiFileShare *)data;
101 _wapi_handle_get_or_set_share (guint64 device, guint64 inode, guint32 new_sharemode, guint32 new_access,
102 guint32 *old_sharemode, guint32 *old_access, struct _WapiFileShare **share_info)
104 struct _WapiFileShare *file_share;
106 gboolean exists = FALSE;
108 /* Prevent new entries racing with us */
109 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_FILESHARE);
110 g_assert (thr_ret == 0);
115 * Instead of allocating a 4MB array, we use a hash table to keep track of this
116 * info. This is needed even if SHM is disabled, to track sharing inside
117 * the current process.
119 if (!file_share_hash) {
120 file_share_hash = g_hash_table_new_full (wapi_share_info_hash, wapi_share_info_equal, NULL, g_free);
121 mono_os_mutex_init_recursive (&file_share_hash_mutex);
127 file_share_hash_lock ();
129 file_share = (_WapiFileShare *)g_hash_table_lookup (file_share_hash, &tmp);
131 *old_sharemode = file_share->sharemode;
132 *old_access = file_share->access;
133 *share_info = file_share;
135 InterlockedIncrement ((gint32 *)&file_share->handle_refs);
138 file_share = g_new0 (_WapiFileShare, 1);
140 file_share->device = device;
141 file_share->inode = inode;
142 file_share->opened_by_pid = wapi_getpid ();
143 file_share->sharemode = new_sharemode;
144 file_share->access = new_access;
145 file_share->handle_refs = 1;
146 *share_info = file_share;
148 g_hash_table_insert (file_share_hash, file_share, file_share);
151 file_share_hash_unlock ();
153 thr_ret = _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_FILESHARE);
154 g_assert (thr_ret == 0);
159 static void file_close (gpointer handle, gpointer data);
160 static void file_details (gpointer data);
161 static const gchar* file_typename (void);
162 static gsize file_typesize (void);
163 static WapiFileType file_getfiletype(void);
164 static gboolean file_read(gpointer handle, gpointer buffer,
165 guint32 numbytes, guint32 *bytesread,
166 WapiOverlapped *overlapped);
167 static gboolean file_write(gpointer handle, gconstpointer buffer,
168 guint32 numbytes, guint32 *byteswritten,
169 WapiOverlapped *overlapped);
170 static gboolean file_flush(gpointer handle);
171 static guint32 file_seek(gpointer handle, gint32 movedistance,
172 gint32 *highmovedistance, WapiSeekMethod method);
173 static gboolean file_setendoffile(gpointer handle);
174 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
175 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
176 WapiFileTime *last_access,
177 WapiFileTime *last_write);
178 static gboolean file_setfiletime(gpointer handle,
179 const WapiFileTime *create_time,
180 const WapiFileTime *last_access,
181 const WapiFileTime *last_write);
182 static guint32 GetDriveTypeFromPath (const gchar *utf8_root_path_name);
184 /* File handle is only signalled for overlapped IO */
185 static MonoW32HandleOps _wapi_file_ops = {
186 file_close, /* close */
190 NULL, /* special_wait */
192 file_details, /* details */
193 file_typename, /* typename */
194 file_typesize, /* typesize */
197 static void console_close (gpointer handle, gpointer data);
198 static void console_details (gpointer data);
199 static const gchar* console_typename (void);
200 static gsize console_typesize (void);
201 static WapiFileType console_getfiletype(void);
202 static gboolean console_read(gpointer handle, gpointer buffer,
203 guint32 numbytes, guint32 *bytesread,
204 WapiOverlapped *overlapped);
205 static gboolean console_write(gpointer handle, gconstpointer buffer,
206 guint32 numbytes, guint32 *byteswritten,
207 WapiOverlapped *overlapped);
209 /* Console is mostly the same as file, except it can block waiting for
212 static MonoW32HandleOps _wapi_console_ops = {
213 console_close, /* close */
217 NULL, /* special_wait */
219 console_details, /* details */
220 console_typename, /* typename */
221 console_typesize, /* typesize */
224 static const gchar* find_typename (void);
225 static gsize find_typesize (void);
227 static MonoW32HandleOps _wapi_find_ops = {
232 NULL, /* special_wait */
235 find_typename, /* typename */
236 find_typesize, /* typesize */
239 static void pipe_close (gpointer handle, gpointer data);
240 static void pipe_details (gpointer data);
241 static const gchar* pipe_typename (void);
242 static gsize pipe_typesize (void);
243 static WapiFileType pipe_getfiletype (void);
244 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
245 guint32 *bytesread, WapiOverlapped *overlapped);
246 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
247 guint32 numbytes, guint32 *byteswritten,
248 WapiOverlapped *overlapped);
252 static MonoW32HandleOps _wapi_pipe_ops = {
253 pipe_close, /* close */
257 NULL, /* special_wait */
259 pipe_details, /* details */
260 pipe_typename, /* typename */
261 pipe_typesize, /* typesize */
264 static const struct {
265 /* File, console and pipe handles */
266 WapiFileType (*getfiletype)(void);
268 /* File, console and pipe handles */
269 gboolean (*readfile)(gpointer handle, gpointer buffer,
270 guint32 numbytes, guint32 *bytesread,
271 WapiOverlapped *overlapped);
272 gboolean (*writefile)(gpointer handle, gconstpointer buffer,
273 guint32 numbytes, guint32 *byteswritten,
274 WapiOverlapped *overlapped);
275 gboolean (*flushfile)(gpointer handle);
278 guint32 (*seek)(gpointer handle, gint32 movedistance,
279 gint32 *highmovedistance, WapiSeekMethod method);
280 gboolean (*setendoffile)(gpointer handle);
281 guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
282 gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
283 WapiFileTime *last_access,
284 WapiFileTime *last_write);
285 gboolean (*setfiletime)(gpointer handle,
286 const WapiFileTime *create_time,
287 const WapiFileTime *last_access,
288 const WapiFileTime *last_write);
289 } io_ops[MONO_W32HANDLE_COUNT]={
290 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
293 file_read, file_write,
294 file_flush, file_seek,
300 {console_getfiletype,
303 NULL, NULL, NULL, NULL, NULL, NULL},
305 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
307 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
309 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
311 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
312 /* socket (will need at least read and write) */
313 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
315 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
317 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
322 NULL, NULL, NULL, NULL, NULL, NULL},
325 static gboolean lock_while_writing = FALSE;
327 /* Some utility functions.
331 * Check if a file is writable by the current user.
333 * This is is a best effort kind of thing. It assumes a reasonable sane set
334 * of permissions by the underlying OS.
336 * We generally assume that basic unix permission bits are authoritative. Which might not
337 * be the case under systems with extended permissions systems (posix ACLs, SELinux, OSX/iOS sandboxing, etc)
339 * The choice of access as the fallback is due to the expected lower overhead compared to trying to open the file.
341 * The only expected problem with using access are for root, setuid or setgid programs as access is not consistent
342 * under those situations. It's to be expected that this should not happen in practice as those bits are very dangerous
343 * and should not be used with a dynamic runtime.
346 is_file_writable (struct stat *st, const char *path)
349 // OS X Finder "locked" or `ls -lO` "uchg".
350 // This only covers one of several cases where an OS X file could be unwritable through special flags.
351 if (st->st_flags & (UF_IMMUTABLE|SF_IMMUTABLE))
355 /* Is it globally writable? */
356 if (st->st_mode & S_IWOTH)
359 /* Am I the owner? */
360 if ((st->st_uid == geteuid ()) && (st->st_mode & S_IWUSR))
363 /* Am I in the same group? */
364 if ((st->st_gid == getegid ()) && (st->st_mode & S_IWGRP))
367 /* Fallback to using access(2). It's not ideal as it might not take into consideration euid/egid
368 * but it's the only sane option we have on unix.
370 return access (path, W_OK) == 0;
374 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
381 /* FIXME: this could definitely be better, but there seems to
382 * be no pattern to the attributes that are set
385 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
386 if (S_ISSOCK (buf->st_mode))
387 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
389 filename = _wapi_basename (pathname);
391 if (S_ISDIR (buf->st_mode)) {
392 attrs = FILE_ATTRIBUTE_DIRECTORY;
393 if (!is_file_writable (buf, pathname)) {
394 attrs |= FILE_ATTRIBUTE_READONLY;
396 if (filename[0] == '.') {
397 attrs |= FILE_ATTRIBUTE_HIDDEN;
400 if (!is_file_writable (buf, pathname)) {
401 attrs = FILE_ATTRIBUTE_READONLY;
403 if (filename[0] == '.') {
404 attrs |= FILE_ATTRIBUTE_HIDDEN;
406 } else if (filename[0] == '.') {
407 attrs = FILE_ATTRIBUTE_HIDDEN;
409 attrs = FILE_ATTRIBUTE_NORMAL;
414 if (S_ISLNK (lbuf->st_mode)) {
415 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
425 _wapi_set_last_error_from_errno (void)
427 SetLastError (_wapi_get_win32_file_error (errno));
430 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
433 if (errno == ENOENT) {
434 /* Check the path - if it's a missing directory then
435 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
441 dirname = _wapi_dirname (path);
443 dirname = g_strdup (dir);
446 if (_wapi_access (dirname, F_OK) == 0) {
447 SetLastError (ERROR_FILE_NOT_FOUND);
449 SetLastError (ERROR_PATH_NOT_FOUND);
454 _wapi_set_last_error_from_errno ();
460 static void file_close (gpointer handle, gpointer data)
462 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
463 int fd = file_handle->fd;
465 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing file handle %p [%s]", __func__, handle,
466 file_handle->filename);
468 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
469 _wapi_unlink (file_handle->filename);
471 g_free (file_handle->filename);
473 if (file_handle->share_info)
474 _wapi_handle_share_release (file_handle->share_info);
479 static void file_details (gpointer data)
481 struct _WapiHandle_file *file = (struct _WapiHandle_file *)data;
483 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
485 file->fileaccess&GENERIC_READ?'R':'.',
486 file->fileaccess&GENERIC_WRITE?'W':'.',
487 file->fileaccess&GENERIC_EXECUTE?'X':'.',
488 file->sharemode&FILE_SHARE_READ?'R':'.',
489 file->sharemode&FILE_SHARE_WRITE?'W':'.',
490 file->sharemode&FILE_SHARE_DELETE?'D':'.',
494 static const gchar* file_typename (void)
499 static gsize file_typesize (void)
501 return sizeof (struct _WapiHandle_file);
504 static WapiFileType file_getfiletype(void)
506 return(FILE_TYPE_DISK);
509 static gboolean file_read(gpointer handle, gpointer buffer,
510 guint32 numbytes, guint32 *bytesread,
511 WapiOverlapped *overlapped)
513 struct _WapiHandle_file *file_handle;
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 !_wapi_thread_cur_apc_pending());
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;
570 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
571 (gpointer *)&file_handle);
573 g_warning ("%s: error looking up file handle %p", __func__,
575 SetLastError (ERROR_INVALID_HANDLE);
579 fd = file_handle->fd;
581 if(byteswritten!=NULL) {
585 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
586 !(file_handle->fileaccess & GENERIC_ALL)) {
587 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);
589 SetLastError (ERROR_ACCESS_DENIED);
593 if (lock_while_writing) {
594 /* Need to lock the region we're about to write to,
595 * because we only do advisory locking on POSIX
598 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
599 if (current_pos == -1) {
600 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
601 handle, strerror (errno));
602 _wapi_set_last_error_from_errno ();
606 if (_wapi_lock_file_region (fd, current_pos,
607 numbytes) == FALSE) {
608 /* The error has already been set */
614 ret = write (fd, buffer, numbytes);
615 } while (ret == -1 && errno == EINTR &&
616 !_wapi_thread_cur_apc_pending());
618 if (lock_while_writing) {
619 _wapi_unlock_file_region (fd, current_pos, numbytes);
623 if (errno == EINTR) {
626 _wapi_set_last_error_from_errno ();
628 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
629 __func__, handle, strerror(errno));
634 if (byteswritten != NULL) {
640 static gboolean file_flush(gpointer handle)
642 struct _WapiHandle_file *file_handle;
646 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
647 (gpointer *)&file_handle);
649 g_warning ("%s: error looking up file handle %p", __func__,
651 SetLastError (ERROR_INVALID_HANDLE);
655 fd = file_handle->fd;
657 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
658 !(file_handle->fileaccess & GENERIC_ALL)) {
659 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);
661 SetLastError (ERROR_ACCESS_DENIED);
667 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fsync of handle %p error: %s", __func__, handle,
670 _wapi_set_last_error_from_errno ();
677 static guint32 file_seek(gpointer handle, gint32 movedistance,
678 gint32 *highmovedistance, WapiSeekMethod method)
680 struct _WapiHandle_file *file_handle;
682 gint64 offset, newpos;
686 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
687 (gpointer *)&file_handle);
689 g_warning ("%s: error looking up file handle %p", __func__,
691 SetLastError (ERROR_INVALID_HANDLE);
692 return(INVALID_SET_FILE_POINTER);
695 fd = file_handle->fd;
697 if(!(file_handle->fileaccess & GENERIC_READ) &&
698 !(file_handle->fileaccess & GENERIC_WRITE) &&
699 !(file_handle->fileaccess & GENERIC_ALL)) {
700 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);
702 SetLastError (ERROR_ACCESS_DENIED);
703 return(INVALID_SET_FILE_POINTER);
717 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: invalid seek type %d", __func__, method);
719 SetLastError (ERROR_INVALID_PARAMETER);
720 return(INVALID_SET_FILE_POINTER);
723 #ifdef HAVE_LARGE_FILE_SUPPORT
724 if(highmovedistance==NULL) {
726 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting offset to %lld (low %d)", __func__,
727 offset, movedistance);
729 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
731 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);
737 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: moving handle %p by %lld bytes from %d", __func__,
738 handle, (long long)offset, whence);
740 #ifdef PLATFORM_ANDROID
741 /* bionic doesn't support -D_FILE_OFFSET_BITS=64 */
742 newpos=lseek64(fd, offset, whence);
744 newpos=lseek(fd, offset, whence);
747 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek on handle %p returned error %s",
748 __func__, handle, strerror(errno));
750 _wapi_set_last_error_from_errno ();
751 return(INVALID_SET_FILE_POINTER);
754 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek returns %lld", __func__, newpos);
756 #ifdef HAVE_LARGE_FILE_SUPPORT
757 ret=newpos & 0xFFFFFFFF;
758 if(highmovedistance!=NULL) {
759 *highmovedistance=newpos>>32;
763 if(highmovedistance!=NULL) {
764 /* Accurate, but potentially dodgy :-) */
769 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: move of handle %p returning %d/%d", __func__,
770 handle, ret, highmovedistance==NULL?0:*highmovedistance);
775 static gboolean file_setendoffile(gpointer handle)
777 struct _WapiHandle_file *file_handle;
783 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
784 (gpointer *)&file_handle);
786 g_warning ("%s: error looking up file handle %p", __func__,
788 SetLastError (ERROR_INVALID_HANDLE);
791 fd = file_handle->fd;
793 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
794 !(file_handle->fileaccess & GENERIC_ALL)) {
795 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);
797 SetLastError (ERROR_ACCESS_DENIED);
801 /* Find the current file position, and the file length. If
802 * the file position is greater than the length, write to
803 * extend the file with a hole. If the file position is less
804 * than the length, truncate the file.
807 ret=fstat(fd, &statbuf);
809 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
810 handle, strerror(errno));
812 _wapi_set_last_error_from_errno ();
816 pos=lseek(fd, (off_t)0, SEEK_CUR);
818 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
819 handle, strerror(errno));
821 _wapi_set_last_error_from_errno ();
825 #ifdef FTRUNCATE_DOESNT_EXTEND
826 off_t size = statbuf.st_size;
827 /* I haven't bothered to write the configure.ac stuff for this
828 * because I don't know if any platform needs it. I'm leaving
829 * this code just in case though
832 /* Extend the file. Use write() here, because some
833 * manuals say that ftruncate() behaviour is undefined
834 * when the file needs extending. The POSIX spec says
835 * that on XSI-conformant systems it extends, so if
836 * every system we care about conforms, then we can
840 ret = write (fd, "", 1);
841 } while (ret == -1 && errno == EINTR &&
842 !_wapi_thread_cur_apc_pending());
845 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
847 _wapi_set_last_error_from_errno ();
851 /* And put the file position back after the write */
852 ret = lseek (fd, pos, SEEK_SET);
854 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p second lseek failed: %s",
855 __func__, handle, strerror(errno));
857 _wapi_set_last_error_from_errno ();
863 /* Native Client has no ftruncate function, even in standalone sel_ldr. */
864 #ifndef __native_client__
865 /* always truncate, because the extend write() adds an extra
866 * byte to the end of the file
869 ret=ftruncate(fd, pos);
871 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
873 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ftruncate failed: %s", __func__,
874 handle, strerror(errno));
876 _wapi_set_last_error_from_errno ();
884 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
886 struct _WapiHandle_file *file_handle;
893 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
894 (gpointer *)&file_handle);
896 g_warning ("%s: error looking up file handle %p", __func__,
898 SetLastError (ERROR_INVALID_HANDLE);
899 return(INVALID_FILE_SIZE);
901 fd = file_handle->fd;
903 if(!(file_handle->fileaccess & GENERIC_READ) &&
904 !(file_handle->fileaccess & GENERIC_WRITE) &&
905 !(file_handle->fileaccess & GENERIC_ALL)) {
906 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);
908 SetLastError (ERROR_ACCESS_DENIED);
909 return(INVALID_FILE_SIZE);
912 /* If the file has a size with the low bits 0xFFFFFFFF the
913 * caller can't tell if this is an error, so clear the error
916 SetLastError (ERROR_SUCCESS);
918 ret = fstat(fd, &statbuf);
920 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
921 handle, strerror(errno));
923 _wapi_set_last_error_from_errno ();
924 return(INVALID_FILE_SIZE);
927 /* fstat indicates block devices as zero-length, so go a different path */
929 if (S_ISBLK(statbuf.st_mode)) {
931 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
932 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ioctl BLKGETSIZE64 failed: %s",
933 __func__, handle, strerror(errno));
935 _wapi_set_last_error_from_errno ();
936 return(INVALID_FILE_SIZE);
939 size = bigsize & 0xFFFFFFFF;
940 if (highsize != NULL) {
941 *highsize = bigsize>>32;
944 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning block device size %d/%d",
945 __func__, size, *highsize);
951 #ifdef HAVE_LARGE_FILE_SUPPORT
952 size = statbuf.st_size & 0xFFFFFFFF;
953 if (highsize != NULL) {
954 *highsize = statbuf.st_size>>32;
957 if (highsize != NULL) {
958 /* Accurate, but potentially dodgy :-) */
961 size = statbuf.st_size;
964 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning size %d/%d", __func__, size, *highsize);
969 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
970 WapiFileTime *last_access,
971 WapiFileTime *last_write)
973 struct _WapiHandle_file *file_handle;
976 guint64 create_ticks, access_ticks, write_ticks;
979 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
980 (gpointer *)&file_handle);
982 g_warning ("%s: error looking up file handle %p", __func__,
984 SetLastError (ERROR_INVALID_HANDLE);
987 fd = file_handle->fd;
989 if(!(file_handle->fileaccess & GENERIC_READ) &&
990 !(file_handle->fileaccess & GENERIC_ALL)) {
991 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
992 __func__, handle, file_handle->fileaccess);
994 SetLastError (ERROR_ACCESS_DENIED);
998 ret=fstat(fd, &statbuf);
1000 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
1003 _wapi_set_last_error_from_errno ();
1007 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: atime: %ld ctime: %ld mtime: %ld", __func__,
1008 statbuf.st_atime, statbuf.st_ctime,
1011 /* Try and guess a meaningful create time by using the older
1014 /* The magic constant comes from msdn documentation
1015 * "Converting a time_t Value to a File Time"
1017 if(statbuf.st_atime < statbuf.st_ctime) {
1018 create_ticks=((guint64)statbuf.st_atime*10000000)
1019 + 116444736000000000ULL;
1021 create_ticks=((guint64)statbuf.st_ctime*10000000)
1022 + 116444736000000000ULL;
1025 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
1026 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
1028 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
1029 access_ticks, create_ticks, write_ticks);
1031 if(create_time!=NULL) {
1032 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
1033 create_time->dwHighDateTime = create_ticks >> 32;
1036 if(last_access!=NULL) {
1037 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
1038 last_access->dwHighDateTime = access_ticks >> 32;
1041 if(last_write!=NULL) {
1042 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
1043 last_write->dwHighDateTime = write_ticks >> 32;
1049 static gboolean file_setfiletime(gpointer handle,
1050 const WapiFileTime *create_time G_GNUC_UNUSED,
1051 const WapiFileTime *last_access,
1052 const WapiFileTime *last_write)
1054 struct _WapiHandle_file *file_handle;
1056 struct utimbuf utbuf;
1057 struct stat statbuf;
1058 guint64 access_ticks, write_ticks;
1061 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1062 (gpointer *)&file_handle);
1064 g_warning ("%s: error looking up file handle %p", __func__,
1066 SetLastError (ERROR_INVALID_HANDLE);
1069 fd = file_handle->fd;
1071 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
1072 !(file_handle->fileaccess & GENERIC_ALL)) {
1073 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);
1075 SetLastError (ERROR_ACCESS_DENIED);
1079 if(file_handle->filename == NULL) {
1080 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p unknown filename", __func__, handle);
1082 SetLastError (ERROR_INVALID_HANDLE);
1086 /* Get the current times, so we can put the same times back in
1087 * the event that one of the FileTime structs is NULL
1089 ret=fstat (fd, &statbuf);
1091 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
1094 SetLastError (ERROR_INVALID_PARAMETER);
1098 if(last_access!=NULL) {
1099 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
1100 last_access->dwLowDateTime;
1101 /* This is (time_t)0. We can actually go to INT_MIN,
1102 * but this will do for now.
1104 if (access_ticks < 116444736000000000ULL) {
1105 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set access time too early",
1107 SetLastError (ERROR_INVALID_PARAMETER);
1111 if (sizeof (utbuf.actime) == 4 && ((access_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
1112 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",
1114 SetLastError (ERROR_INVALID_PARAMETER);
1118 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
1120 utbuf.actime=statbuf.st_atime;
1123 if(last_write!=NULL) {
1124 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
1125 last_write->dwLowDateTime;
1126 /* This is (time_t)0. We can actually go to INT_MIN,
1127 * but this will do for now.
1129 if (write_ticks < 116444736000000000ULL) {
1130 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set write time too early",
1132 SetLastError (ERROR_INVALID_PARAMETER);
1135 if (sizeof (utbuf.modtime) == 4 && ((write_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
1136 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",
1138 SetLastError (ERROR_INVALID_PARAMETER);
1142 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1144 utbuf.modtime=statbuf.st_mtime;
1147 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting handle %p access %ld write %ld", __func__,
1148 handle, utbuf.actime, utbuf.modtime);
1150 ret = _wapi_utime (file_handle->filename, &utbuf);
1152 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p [%s] utime failed: %s", __func__,
1153 handle, file_handle->filename, strerror(errno));
1155 SetLastError (ERROR_INVALID_PARAMETER);
1162 static void console_close (gpointer handle, gpointer data)
1164 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1165 int fd = console_handle->fd;
1167 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing console handle %p", __func__, handle);
1169 g_free (console_handle->filename);
1172 if (console_handle->share_info)
1173 _wapi_handle_share_release (console_handle->share_info);
1178 static void console_details (gpointer data)
1180 file_details (data);
1183 static const gchar* console_typename (void)
1188 static gsize console_typesize (void)
1190 return sizeof (struct _WapiHandle_file);
1193 static WapiFileType console_getfiletype(void)
1195 return(FILE_TYPE_CHAR);
1198 static gboolean console_read(gpointer handle, gpointer buffer,
1199 guint32 numbytes, guint32 *bytesread,
1200 WapiOverlapped *overlapped G_GNUC_UNUSED)
1202 struct _WapiHandle_file *console_handle;
1206 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_CONSOLE,
1207 (gpointer *)&console_handle);
1209 g_warning ("%s: error looking up console handle %p", __func__,
1211 SetLastError (ERROR_INVALID_HANDLE);
1214 fd = console_handle->fd;
1216 if(bytesread!=NULL) {
1220 if(!(console_handle->fileaccess & GENERIC_READ) &&
1221 !(console_handle->fileaccess & GENERIC_ALL)) {
1222 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1223 __func__, handle, console_handle->fileaccess);
1225 SetLastError (ERROR_ACCESS_DENIED);
1230 ret=read(fd, buffer, numbytes);
1231 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1234 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__, handle,
1237 _wapi_set_last_error_from_errno ();
1241 if(bytesread!=NULL) {
1248 static gboolean console_write(gpointer handle, gconstpointer buffer,
1249 guint32 numbytes, guint32 *byteswritten,
1250 WapiOverlapped *overlapped G_GNUC_UNUSED)
1252 struct _WapiHandle_file *console_handle;
1256 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_CONSOLE,
1257 (gpointer *)&console_handle);
1259 g_warning ("%s: error looking up console handle %p", __func__,
1261 SetLastError (ERROR_INVALID_HANDLE);
1264 fd = console_handle->fd;
1266 if(byteswritten!=NULL) {
1270 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1271 !(console_handle->fileaccess & GENERIC_ALL)) {
1272 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);
1274 SetLastError (ERROR_ACCESS_DENIED);
1279 ret = write(fd, buffer, numbytes);
1280 } while (ret == -1 && errno == EINTR &&
1281 !_wapi_thread_cur_apc_pending());
1284 if (errno == EINTR) {
1287 _wapi_set_last_error_from_errno ();
1289 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
1290 __func__, handle, strerror(errno));
1295 if(byteswritten!=NULL) {
1302 static const gchar* find_typename (void)
1307 static gsize find_typesize (void)
1309 return sizeof (struct _WapiHandle_find);
1312 static void pipe_close (gpointer handle, gpointer data)
1314 struct _WapiHandle_file *pipe_handle = (struct _WapiHandle_file*)data;
1315 int fd = pipe_handle->fd;
1317 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing pipe handle %p fd %d", __func__, handle, fd);
1319 /* No filename with pipe handles */
1321 if (pipe_handle->share_info)
1322 _wapi_handle_share_release (pipe_handle->share_info);
1327 static void pipe_details (gpointer data)
1329 file_details (data);
1332 static const gchar* pipe_typename (void)
1337 static gsize pipe_typesize (void)
1339 return sizeof (struct _WapiHandle_file);
1342 static WapiFileType pipe_getfiletype(void)
1344 return(FILE_TYPE_PIPE);
1347 static gboolean pipe_read (gpointer handle, gpointer buffer,
1348 guint32 numbytes, guint32 *bytesread,
1349 WapiOverlapped *overlapped G_GNUC_UNUSED)
1351 struct _WapiHandle_file *pipe_handle;
1355 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_PIPE,
1356 (gpointer *)&pipe_handle);
1358 g_warning ("%s: error looking up pipe handle %p", __func__,
1360 SetLastError (ERROR_INVALID_HANDLE);
1363 fd = pipe_handle->fd;
1365 if(bytesread!=NULL) {
1369 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1370 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1371 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1372 __func__, handle, pipe_handle->fileaccess);
1374 SetLastError (ERROR_ACCESS_DENIED);
1378 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: reading up to %d bytes from pipe %p", __func__,
1382 ret=read(fd, buffer, numbytes);
1383 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1386 if (errno == EINTR) {
1389 _wapi_set_last_error_from_errno ();
1391 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
1392 handle, strerror(errno));
1398 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read %d bytes from pipe %p", __func__, ret, handle);
1400 if(bytesread!=NULL) {
1407 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1408 guint32 numbytes, guint32 *byteswritten,
1409 WapiOverlapped *overlapped G_GNUC_UNUSED)
1411 struct _WapiHandle_file *pipe_handle;
1415 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_PIPE,
1416 (gpointer *)&pipe_handle);
1418 g_warning ("%s: error looking up pipe handle %p", __func__,
1420 SetLastError (ERROR_INVALID_HANDLE);
1423 fd = pipe_handle->fd;
1425 if(byteswritten!=NULL) {
1429 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1430 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1431 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);
1433 SetLastError (ERROR_ACCESS_DENIED);
1437 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1441 ret = write (fd, buffer, numbytes);
1442 } while (ret == -1 && errno == EINTR &&
1443 !_wapi_thread_cur_apc_pending());
1446 if (errno == EINTR) {
1449 _wapi_set_last_error_from_errno ();
1451 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s", __func__,
1452 handle, strerror(errno));
1457 if(byteswritten!=NULL) {
1464 static int convert_flags(guint32 fileaccess, guint32 createmode)
1468 switch(fileaccess) {
1475 case GENERIC_READ|GENERIC_WRITE:
1479 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown access type 0x%x", __func__,
1484 switch(createmode) {
1486 flags|=O_CREAT|O_EXCL;
1489 flags|=O_CREAT|O_TRUNC;
1496 case TRUNCATE_EXISTING:
1500 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown create mode 0x%x", __func__,
1509 static mode_t convert_perms(guint32 sharemode)
1513 if(sharemode&FILE_SHARE_READ) {
1516 if(sharemode&FILE_SHARE_WRITE) {
1524 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1526 struct _WapiFileShare **share_info)
1528 gboolean file_already_shared;
1529 guint32 file_existing_share, file_existing_access;
1531 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);
1533 if (file_already_shared) {
1534 /* The reference to this share info was incremented
1535 * when we looked it up, so be careful to put it back
1536 * if we conclude we can't use this file.
1538 if (file_existing_share == 0) {
1539 /* Quick and easy, no possibility to share */
1540 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);
1542 _wapi_handle_share_release (*share_info);
1547 if (((file_existing_share == FILE_SHARE_READ) &&
1548 (fileaccess != GENERIC_READ)) ||
1549 ((file_existing_share == FILE_SHARE_WRITE) &&
1550 (fileaccess != GENERIC_WRITE))) {
1551 /* New access mode doesn't match up */
1552 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);
1554 _wapi_handle_share_release (*share_info);
1559 if (((file_existing_access & GENERIC_READ) &&
1560 !(sharemode & FILE_SHARE_READ)) ||
1561 ((file_existing_access & GENERIC_WRITE) &&
1562 !(sharemode & FILE_SHARE_WRITE))) {
1563 /* New share mode doesn't match up */
1564 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);
1566 _wapi_handle_share_release (*share_info);
1571 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
1579 share_allows_delete (struct stat *statbuf, struct _WapiFileShare **share_info)
1581 gboolean file_already_shared;
1582 guint32 file_existing_share, file_existing_access;
1584 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);
1586 if (file_already_shared) {
1587 /* The reference to this share info was incremented
1588 * when we looked it up, so be careful to put it back
1589 * if we conclude we can't use this file.
1591 if (file_existing_share == 0) {
1592 /* Quick and easy, no possibility to share */
1593 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);
1595 _wapi_handle_share_release (*share_info);
1600 if (!(file_existing_share & FILE_SHARE_DELETE)) {
1601 /* New access mode doesn't match up */
1602 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);
1604 _wapi_handle_share_release (*share_info);
1609 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
1617 * @name: a pointer to a NULL-terminated unicode string, that names
1618 * the file or other object to create.
1619 * @fileaccess: specifies the file access mode
1620 * @sharemode: whether the file should be shared. This parameter is
1621 * currently ignored.
1622 * @security: Ignored for now.
1623 * @createmode: specifies whether to create a new file, whether to
1624 * overwrite an existing file, whether to truncate the file, etc.
1625 * @attrs: specifies file attributes and flags. On win32 attributes
1626 * are characteristics of the file, not the handle, and are ignored
1627 * when an existing file is opened. Flags give the library hints on
1628 * how to process a file to optimise performance.
1629 * @template: the handle of an open %GENERIC_READ file that specifies
1630 * attributes to apply to a newly created file, ignoring @attrs.
1631 * Normally this parameter is NULL. This parameter is ignored when an
1632 * existing file is opened.
1634 * Creates a new file handle. This only applies to normal files:
1635 * pipes are handled by CreatePipe(), and console handles are created
1636 * with GetStdHandle().
1638 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1640 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1641 guint32 sharemode, WapiSecurityAttributes *security,
1642 guint32 createmode, guint32 attrs,
1643 gpointer template_ G_GNUC_UNUSED)
1645 struct _WapiHandle_file file_handle = {0};
1647 int flags=convert_flags(fileaccess, createmode);
1648 /*mode_t perms=convert_perms(sharemode);*/
1649 /* we don't use sharemode, because that relates to sharing of
1650 * the file when the file is open and is already handled by
1651 * other code, perms instead are the on-disk permissions and
1652 * this is a sane default.
1657 MonoW32HandleType handle_type;
1658 struct stat statbuf;
1660 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1663 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1664 SetLastError (ERROR_ENCRYPTION_FAILED);
1665 return INVALID_HANDLE_VALUE;
1669 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1671 SetLastError (ERROR_INVALID_NAME);
1672 return(INVALID_HANDLE_VALUE);
1675 filename = mono_unicode_to_external (name);
1676 if (filename == NULL) {
1677 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1679 SetLastError (ERROR_INVALID_NAME);
1680 return(INVALID_HANDLE_VALUE);
1683 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Opening %s with share 0x%x and access 0x%x", __func__,
1684 filename, sharemode, fileaccess);
1686 fd = _wapi_open (filename, flags, perms);
1688 /* If we were trying to open a directory with write permissions
1689 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1690 * EISDIR. However, this is a bit bogus because calls to
1691 * manipulate the directory (e.g. SetFileTime) will still work on
1692 * the directory because they use other API calls
1693 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1694 * to open the directory again without write permission.
1696 if (fd == -1 && errno == EISDIR)
1698 /* Try again but don't try to make it writable */
1699 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1703 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s: %s", __func__, filename,
1705 _wapi_set_last_path_error_from_errno (NULL, filename);
1708 return(INVALID_HANDLE_VALUE);
1711 if (fd >= mono_w32handle_fd_reserve) {
1712 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
1714 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1719 return(INVALID_HANDLE_VALUE);
1722 ret = fstat (fd, &statbuf);
1724 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fstat error of file %s: %s", __func__,
1725 filename, strerror (errno));
1726 _wapi_set_last_error_from_errno ();
1730 return(INVALID_HANDLE_VALUE);
1732 #ifdef __native_client__
1733 /* Workaround: Native Client currently returns the same fake inode
1734 * for all files, so do a simple hash on the filename so we don't
1735 * use the same share info for each file.
1737 statbuf.st_ino = g_str_hash(filename);
1740 if (share_allows_open (&statbuf, sharemode, fileaccess,
1741 &file_handle.share_info) == FALSE) {
1742 SetLastError (ERROR_SHARING_VIOLATION);
1746 return (INVALID_HANDLE_VALUE);
1748 if (file_handle.share_info == NULL) {
1749 /* No space, so no more files can be opened */
1750 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No space in the share table", __func__);
1752 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1756 return(INVALID_HANDLE_VALUE);
1759 file_handle.filename = filename;
1761 if(security!=NULL) {
1762 //file_handle->security_attributes=_wapi_handle_scratch_store (
1763 //security, sizeof(WapiSecurityAttributes));
1766 file_handle.fd = fd;
1767 file_handle.fileaccess=fileaccess;
1768 file_handle.sharemode=sharemode;
1769 file_handle.attrs=attrs;
1771 #ifdef HAVE_POSIX_FADVISE
1772 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1773 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1774 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1775 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1779 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1781 if (S_ISFIFO (statbuf.st_mode)) {
1782 handle_type = MONO_W32HANDLE_PIPE;
1783 /* maintain invariant that pipes have no filename */
1784 file_handle.filename = NULL;
1787 } else if (S_ISCHR (statbuf.st_mode)) {
1788 handle_type = MONO_W32HANDLE_CONSOLE;
1790 handle_type = MONO_W32HANDLE_FILE;
1793 handle = mono_w32handle_new_fd (handle_type, fd, &file_handle);
1794 if (handle == INVALID_HANDLE_VALUE) {
1795 g_warning ("%s: error creating file handle", __func__);
1799 SetLastError (ERROR_GEN_FAILURE);
1800 return(INVALID_HANDLE_VALUE);
1803 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p", __func__, handle);
1810 * @name: a pointer to a NULL-terminated unicode string, that names
1811 * the file to be deleted.
1813 * Deletes file @name.
1815 * Return value: %TRUE on success, %FALSE otherwise.
1817 gboolean DeleteFile(const gunichar2 *name)
1821 gboolean ret = FALSE;
1824 struct stat statbuf;
1825 struct _WapiFileShare *shareinfo;
1829 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1831 SetLastError (ERROR_INVALID_NAME);
1835 filename=mono_unicode_to_external(name);
1836 if(filename==NULL) {
1837 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1839 SetLastError (ERROR_INVALID_NAME);
1843 attrs = GetFileAttributes (name);
1844 if (attrs == INVALID_FILE_ATTRIBUTES) {
1845 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file attributes error", __func__);
1846 /* Error set by GetFileAttributes() */
1852 /* Check to make sure sharing allows us to open the file for
1853 * writing. See bug 323389.
1855 * Do the checks that don't need an open file descriptor, for
1856 * simplicity's sake. If we really have to do the full checks
1857 * then we can implement that later.
1859 if (_wapi_stat (filename, &statbuf) < 0) {
1860 _wapi_set_last_path_error_from_errno (NULL, filename);
1865 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1866 &shareinfo) == FALSE) {
1867 SetLastError (ERROR_SHARING_VIOLATION);
1872 _wapi_handle_share_release (shareinfo);
1875 retval = _wapi_unlink (filename);
1878 _wapi_set_last_path_error_from_errno (NULL, filename);
1890 * @name: a pointer to a NULL-terminated unicode string, that names
1891 * the file to be moved.
1892 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1893 * new name for the file.
1895 * Renames file @name to @dest_name.
1896 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1897 * when it is the same file as the source. In that case it silently succeeds.
1899 * Return value: %TRUE on success, %FALSE otherwise.
1901 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1903 gchar *utf8_name, *utf8_dest_name;
1904 int result, errno_copy;
1905 struct stat stat_src, stat_dest;
1906 gboolean ret = FALSE;
1907 struct _WapiFileShare *shareinfo;
1910 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1912 SetLastError (ERROR_INVALID_NAME);
1916 utf8_name = mono_unicode_to_external (name);
1917 if (utf8_name == NULL) {
1918 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1920 SetLastError (ERROR_INVALID_NAME);
1924 if(dest_name==NULL) {
1925 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1928 SetLastError (ERROR_INVALID_NAME);
1932 utf8_dest_name = mono_unicode_to_external (dest_name);
1933 if (utf8_dest_name == NULL) {
1934 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1937 SetLastError (ERROR_INVALID_NAME);
1942 * In C# land we check for the existence of src, but not for dest.
1943 * We check it here and return the failure if dest exists and is not
1944 * the same file as src.
1946 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1947 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1948 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1950 g_free (utf8_dest_name);
1955 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1956 if (stat_dest.st_dev != stat_src.st_dev ||
1957 stat_dest.st_ino != stat_src.st_ino) {
1959 g_free (utf8_dest_name);
1960 SetLastError (ERROR_ALREADY_EXISTS);
1965 /* Check to make that we have delete sharing permission.
1966 * See https://bugzilla.xamarin.com/show_bug.cgi?id=17009
1968 * Do the checks that don't need an open file descriptor, for
1969 * simplicity's sake. If we really have to do the full checks
1970 * then we can implement that later.
1972 if (share_allows_delete (&stat_src, &shareinfo) == FALSE) {
1973 SetLastError (ERROR_SHARING_VIOLATION);
1977 _wapi_handle_share_release (shareinfo);
1979 result = _wapi_rename (utf8_name, utf8_dest_name);
1983 switch(errno_copy) {
1985 SetLastError (ERROR_ALREADY_EXISTS);
1989 /* Ignore here, it is dealt with below */
1993 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1998 g_free (utf8_dest_name);
2000 if (result != 0 && errno_copy == EXDEV) {
2001 if (S_ISDIR (stat_src.st_mode)) {
2002 SetLastError (ERROR_NOT_SAME_DEVICE);
2005 /* Try a copy to the new location, and delete the source */
2006 if (CopyFile (name, dest_name, TRUE)==FALSE) {
2007 /* CopyFile will set the error */
2011 return(DeleteFile (name));
2022 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
2026 int buf_size = st_src->st_blksize;
2028 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
2029 buf = (char *) malloc (buf_size);
2032 remain = read (src_fd, buf, buf_size);
2034 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
2038 _wapi_set_last_error_from_errno ();
2048 while (remain > 0) {
2049 if ((n = write (dest_fd, wbuf, remain)) < 0) {
2050 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
2054 _wapi_set_last_error_from_errno ();
2055 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write failed.", __func__);
2071 * @name: a pointer to a NULL-terminated unicode string, that names
2072 * the file to be copied.
2073 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
2074 * new name for the file.
2075 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
2077 * Copies file @name to @dest_name
2079 * Return value: %TRUE on success, %FALSE otherwise.
2081 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
2082 gboolean fail_if_exists)
2084 gchar *utf8_src, *utf8_dest;
2085 int src_fd, dest_fd;
2086 struct stat st, dest_st;
2087 struct utimbuf dest_time;
2088 gboolean ret = TRUE;
2092 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2094 SetLastError (ERROR_INVALID_NAME);
2098 utf8_src = mono_unicode_to_external (name);
2099 if (utf8_src == NULL) {
2100 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of source returned NULL",
2103 SetLastError (ERROR_INVALID_PARAMETER);
2107 if(dest_name==NULL) {
2108 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: dest is NULL", __func__);
2111 SetLastError (ERROR_INVALID_NAME);
2115 utf8_dest = mono_unicode_to_external (dest_name);
2116 if (utf8_dest == NULL) {
2117 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of dest returned NULL",
2120 SetLastError (ERROR_INVALID_PARAMETER);
2127 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2129 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2137 if (fstat (src_fd, &st) < 0) {
2138 _wapi_set_last_error_from_errno ();
2147 /* Before trying to open/create the dest, we need to report a 'file busy'
2148 * error if src and dest are actually the same file. We do the check here to take
2149 * advantage of the IOMAP capability */
2150 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
2151 st.st_ino == dest_st.st_ino) {
2157 SetLastError (ERROR_SHARING_VIOLATION);
2161 if (fail_if_exists) {
2162 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2164 /* FIXME: it kinda sucks that this code path potentially scans
2165 * the directory twice due to the weird SetLastError()
2167 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2169 /* The file does not exist, try creating it */
2170 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2172 /* Apparently this error is set if we
2173 * overwrite the dest file
2175 SetLastError (ERROR_ALREADY_EXISTS);
2179 _wapi_set_last_error_from_errno ();
2188 if (!write_file (src_fd, dest_fd, &st, TRUE))
2194 dest_time.modtime = st.st_mtime;
2195 dest_time.actime = st.st_atime;
2196 ret_utime = utime (utf8_dest, &dest_time);
2197 if (ret_utime == -1)
2198 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file [%s] utime failed: %s", __func__, utf8_dest, strerror(errno));
2207 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2212 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: %s is NULL", __func__, arg_name);
2213 SetLastError (ERROR_INVALID_NAME);
2217 utf8_ret = mono_unicode_to_external (arg);
2218 if (utf8_ret == NULL) {
2219 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of %s returned NULL",
2220 __func__, arg_name);
2221 SetLastError (ERROR_INVALID_PARAMETER);
2229 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2230 const gunichar2 *backupFileName, guint32 replaceFlags,
2231 gpointer exclude, gpointer reserved)
2233 int result, backup_fd = -1,replaced_fd = -1;
2234 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2235 struct stat stBackup;
2236 gboolean ret = FALSE;
2238 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2240 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2241 goto replace_cleanup;
2242 if (backupFileName != NULL) {
2243 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2244 goto replace_cleanup;
2247 if (utf8_backupFileName) {
2248 // Open the backup file for read so we can restore the file if an error occurs.
2249 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2250 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2252 goto replace_cleanup;
2255 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2257 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2258 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2259 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2260 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2263 if (replaced_fd == -1)
2264 goto replace_cleanup;
2266 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2269 goto replace_cleanup;
2275 g_free (utf8_replacedFileName);
2276 g_free (utf8_replacementFileName);
2277 g_free (utf8_backupFileName);
2278 if (backup_fd != -1)
2280 if (replaced_fd != -1)
2281 close (replaced_fd);
2287 * @stdhandle: specifies the file descriptor
2289 * Returns a handle for stdin, stdout, or stderr. Always returns the
2290 * same handle for the same @stdhandle.
2292 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2295 static mono_mutex_t stdhandle_mutex;
2297 gpointer GetStdHandle(WapiStdHandle stdhandle)
2299 struct _WapiHandle_file *file_handle;
2306 case STD_INPUT_HANDLE:
2311 case STD_OUTPUT_HANDLE:
2316 case STD_ERROR_HANDLE:
2322 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unknown standard handle type", __func__);
2324 SetLastError (ERROR_INVALID_PARAMETER);
2325 return(INVALID_HANDLE_VALUE);
2328 handle = GINT_TO_POINTER (fd);
2330 mono_os_mutex_lock (&stdhandle_mutex);
2332 ok = mono_w32handle_lookup (handle, MONO_W32HANDLE_CONSOLE,
2333 (gpointer *)&file_handle);
2335 /* Need to create this console handle */
2336 handle = _wapi_stdhandle_create (fd, name);
2338 if (handle == INVALID_HANDLE_VALUE) {
2339 SetLastError (ERROR_NO_MORE_FILES);
2343 /* Add a reference to this handle */
2344 mono_w32handle_ref (handle);
2348 mono_os_mutex_unlock (&stdhandle_mutex);
2355 * @handle: The file handle to read from. The handle must have
2356 * %GENERIC_READ access.
2357 * @buffer: The buffer to store read data in
2358 * @numbytes: The maximum number of bytes to read
2359 * @bytesread: The actual number of bytes read is stored here. This
2360 * value can be zero if the handle is positioned at the end of the
2362 * @overlapped: points to a required %WapiOverlapped structure if
2363 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2366 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2367 * function reads up to @numbytes bytes from the file from the current
2368 * file position, and stores them in @buffer. If there are not enough
2369 * bytes left in the file, just the amount available will be read.
2370 * The actual number of bytes read is stored in @bytesread.
2372 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2373 * file position is ignored and the read position is taken from data
2374 * in the @overlapped structure.
2376 * Return value: %TRUE if the read succeeds (even if no bytes were
2377 * read due to an attempt to read past the end of the file), %FALSE on
2380 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2381 guint32 *bytesread, WapiOverlapped *overlapped)
2383 MonoW32HandleType type;
2385 type = mono_w32handle_get_type (handle);
2387 if(io_ops[type].readfile==NULL) {
2388 SetLastError (ERROR_INVALID_HANDLE);
2392 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2398 * @handle: The file handle to write to. The handle must have
2399 * %GENERIC_WRITE access.
2400 * @buffer: The buffer to read data from.
2401 * @numbytes: The maximum number of bytes to write.
2402 * @byteswritten: The actual number of bytes written is stored here.
2403 * If the handle is positioned at the file end, the length of the file
2404 * is extended. This parameter may be %NULL.
2405 * @overlapped: points to a required %WapiOverlapped structure if
2406 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2409 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2410 * function writes up to @numbytes bytes from @buffer to the file at
2411 * the current file position. If @handle is positioned at the end of
2412 * the file, the file is extended. The actual number of bytes written
2413 * is stored in @byteswritten.
2415 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2416 * file position is ignored and the write position is taken from data
2417 * in the @overlapped structure.
2419 * Return value: %TRUE if the write succeeds, %FALSE on error.
2421 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2422 guint32 *byteswritten, WapiOverlapped *overlapped)
2424 MonoW32HandleType type;
2426 type = mono_w32handle_get_type (handle);
2428 if(io_ops[type].writefile==NULL) {
2429 SetLastError (ERROR_INVALID_HANDLE);
2433 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2439 * @handle: Handle to open file. The handle must have
2440 * %GENERIC_WRITE access.
2442 * Flushes buffers of the file and causes all unwritten data to
2445 * Return value: %TRUE on success, %FALSE otherwise.
2447 gboolean FlushFileBuffers(gpointer handle)
2449 MonoW32HandleType type;
2451 type = mono_w32handle_get_type (handle);
2453 if(io_ops[type].flushfile==NULL) {
2454 SetLastError (ERROR_INVALID_HANDLE);
2458 return(io_ops[type].flushfile (handle));
2463 * @handle: The file handle to set. The handle must have
2464 * %GENERIC_WRITE access.
2466 * Moves the end-of-file position to the current position of the file
2467 * pointer. This function is used to truncate or extend a file.
2469 * Return value: %TRUE on success, %FALSE otherwise.
2471 gboolean SetEndOfFile(gpointer handle)
2473 MonoW32HandleType type;
2475 type = mono_w32handle_get_type (handle);
2477 if (io_ops[type].setendoffile == NULL) {
2478 SetLastError (ERROR_INVALID_HANDLE);
2482 return(io_ops[type].setendoffile (handle));
2487 * @handle: The file handle to set. The handle must have
2488 * %GENERIC_READ or %GENERIC_WRITE access.
2489 * @movedistance: Low 32 bits of a signed value that specifies the
2490 * number of bytes to move the file pointer.
2491 * @highmovedistance: Pointer to the high 32 bits of a signed value
2492 * that specifies the number of bytes to move the file pointer, or
2494 * @method: The starting point for the file pointer move.
2496 * Sets the file pointer of an open file.
2498 * The distance to move the file pointer is calculated from
2499 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2500 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2501 * is the low 32 bits and @highmovedistance a pointer to the high 32
2502 * bits of a 64 bit signed value. A positive distance moves the file
2503 * pointer forward from the position specified by @method; a negative
2504 * distance moves the file pointer backward.
2506 * If the library is compiled without large file support,
2507 * @highmovedistance is ignored and its value is set to zero on a
2508 * successful return.
2510 * Return value: On success, the low 32 bits of the new file pointer.
2511 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2512 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2514 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2515 gint32 *highmovedistance, WapiSeekMethod method)
2517 MonoW32HandleType type;
2519 type = mono_w32handle_get_type (handle);
2521 if (io_ops[type].seek == NULL) {
2522 SetLastError (ERROR_INVALID_HANDLE);
2523 return(INVALID_SET_FILE_POINTER);
2526 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2532 * @handle: The file handle to test.
2534 * Finds the type of file @handle.
2536 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2537 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2538 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2539 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2541 WapiFileType GetFileType(gpointer handle)
2543 MonoW32HandleType type;
2545 type = mono_w32handle_get_type (handle);
2547 if (io_ops[type].getfiletype == NULL) {
2548 SetLastError (ERROR_INVALID_HANDLE);
2549 return(FILE_TYPE_UNKNOWN);
2552 return(io_ops[type].getfiletype ());
2557 * @handle: The file handle to query. The handle must have
2558 * %GENERIC_READ or %GENERIC_WRITE access.
2559 * @highsize: If non-%NULL, the high 32 bits of the file size are
2562 * Retrieves the size of the file @handle.
2564 * If the library is compiled without large file support, @highsize
2565 * has its value set to zero on a successful return.
2567 * Return value: On success, the low 32 bits of the file size. If
2568 * @highsize is non-%NULL then the high 32 bits of the file size are
2569 * stored here. On failure %INVALID_FILE_SIZE is returned.
2571 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2573 MonoW32HandleType type;
2575 type = mono_w32handle_get_type (handle);
2577 if (io_ops[type].getfilesize == NULL) {
2578 SetLastError (ERROR_INVALID_HANDLE);
2579 return(INVALID_FILE_SIZE);
2582 return(io_ops[type].getfilesize (handle, highsize));
2587 * @handle: The file handle to query. The handle must have
2588 * %GENERIC_READ access.
2589 * @create_time: Points to a %WapiFileTime structure to receive the
2590 * number of ticks since the epoch that file was created. May be
2592 * @last_access: Points to a %WapiFileTime structure to receive the
2593 * number of ticks since the epoch when file was last accessed. May be
2595 * @last_write: Points to a %WapiFileTime structure to receive the
2596 * number of ticks since the epoch when file was last written to. May
2599 * Finds the number of ticks since the epoch that the file referenced
2600 * by @handle was created, last accessed and last modified. A tick is
2601 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2604 * Create time isn't recorded on POSIX file systems or reported by
2605 * stat(2), so that time is guessed by returning the oldest of the
2608 * Return value: %TRUE on success, %FALSE otherwise.
2610 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2611 WapiFileTime *last_access, WapiFileTime *last_write)
2613 MonoW32HandleType type;
2615 type = mono_w32handle_get_type (handle);
2617 if (io_ops[type].getfiletime == NULL) {
2618 SetLastError (ERROR_INVALID_HANDLE);
2622 return(io_ops[type].getfiletime (handle, create_time, last_access,
2628 * @handle: The file handle to set. The handle must have
2629 * %GENERIC_WRITE access.
2630 * @create_time: Points to a %WapiFileTime structure that contains the
2631 * number of ticks since the epoch that the file was created. May be
2633 * @last_access: Points to a %WapiFileTime structure that contains the
2634 * number of ticks since the epoch when the file was last accessed.
2636 * @last_write: Points to a %WapiFileTime structure that contains the
2637 * number of ticks since the epoch when the file was last written to.
2640 * Sets the number of ticks since the epoch that the file referenced
2641 * by @handle was created, last accessed or last modified. A tick is
2642 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2645 * Create time isn't recorded on POSIX file systems, and is ignored.
2647 * Return value: %TRUE on success, %FALSE otherwise.
2649 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2650 const WapiFileTime *last_access,
2651 const WapiFileTime *last_write)
2653 MonoW32HandleType type;
2655 type = mono_w32handle_get_type (handle);
2657 if (io_ops[type].setfiletime == NULL) {
2658 SetLastError (ERROR_INVALID_HANDLE);
2662 return(io_ops[type].setfiletime (handle, create_time, last_access,
2666 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2667 * January 1 1601 GMT
2670 #define TICKS_PER_MILLISECOND 10000L
2671 #define TICKS_PER_SECOND 10000000L
2672 #define TICKS_PER_MINUTE 600000000L
2673 #define TICKS_PER_HOUR 36000000000LL
2674 #define TICKS_PER_DAY 864000000000LL
2676 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2678 static const guint16 mon_yday[2][13]={
2679 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2680 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2684 * FileTimeToSystemTime:
2685 * @file_time: Points to a %WapiFileTime structure that contains the
2686 * number of ticks to convert.
2687 * @system_time: Points to a %WapiSystemTime structure to receive the
2690 * Converts a tick count into broken-out time values.
2692 * Return value: %TRUE on success, %FALSE otherwise.
2694 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2695 WapiSystemTime *system_time)
2697 gint64 file_ticks, totaldays, rem, y;
2700 if(system_time==NULL) {
2701 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: system_time NULL", __func__);
2703 SetLastError (ERROR_INVALID_PARAMETER);
2707 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2708 file_time->dwLowDateTime;
2710 /* Really compares if file_ticks>=0x8000000000000000
2711 * (LLONG_MAX+1) but we're working with a signed value for the
2712 * year and day calculation to work later
2715 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file_time too big", __func__);
2717 SetLastError (ERROR_INVALID_PARAMETER);
2721 totaldays=(file_ticks / TICKS_PER_DAY);
2722 rem = file_ticks % TICKS_PER_DAY;
2723 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2725 system_time->wHour=rem/TICKS_PER_HOUR;
2726 rem %= TICKS_PER_HOUR;
2727 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2729 system_time->wMinute = rem / TICKS_PER_MINUTE;
2730 rem %= TICKS_PER_MINUTE;
2731 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2734 system_time->wSecond = rem / TICKS_PER_SECOND;
2735 rem %= TICKS_PER_SECOND;
2736 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2739 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2740 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Milliseconds: %d", __func__,
2741 system_time->wMilliseconds);
2743 /* January 1, 1601 was a Monday, according to Emacs calendar */
2744 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2745 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2747 /* This algorithm to find year and month given days from epoch
2752 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2753 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2755 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2756 /* Guess a corrected year, assuming 365 days per year */
2757 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2758 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld yg: %lld y: %lld", __func__,
2761 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2762 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2764 /* Adjust days and y to match the guessed year. */
2765 totaldays -= ((yg - y) * 365
2766 + LEAPS_THRU_END_OF (yg - 1)
2767 - LEAPS_THRU_END_OF (y - 1));
2768 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2770 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: y: %lld", __func__, y);
2773 system_time->wYear = y;
2774 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Year: %d", __func__, system_time->wYear);
2776 ip = mon_yday[isleap(y)];
2778 for(y=11; totaldays < ip[y]; --y) {
2782 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2784 system_time->wMonth = y + 1;
2785 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Month: %d", __func__, system_time->wMonth);
2787 system_time->wDay = totaldays + 1;
2788 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day: %d", __func__, system_time->wDay);
2793 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2795 struct _WapiHandle_find find_handle = {0};
2797 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2800 if (pattern == NULL) {
2801 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: pattern is NULL", __func__);
2803 SetLastError (ERROR_PATH_NOT_FOUND);
2804 return(INVALID_HANDLE_VALUE);
2807 utf8_pattern = mono_unicode_to_external (pattern);
2808 if (utf8_pattern == NULL) {
2809 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2811 SetLastError (ERROR_INVALID_NAME);
2812 return(INVALID_HANDLE_VALUE);
2815 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for [%s]", __func__, utf8_pattern);
2817 /* Figure out which bit of the pattern is the directory */
2818 dir_part = _wapi_dirname (utf8_pattern);
2819 entry_part = _wapi_basename (utf8_pattern);
2822 /* Don't do this check for now, it breaks if directories
2823 * really do have metachars in their names (see bug 58116).
2824 * FIXME: Figure out a better solution to keep some checks...
2826 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2827 SetLastError (ERROR_INVALID_NAME);
2829 g_free (entry_part);
2830 g_free (utf8_pattern);
2831 return(INVALID_HANDLE_VALUE);
2835 /* The pattern can specify a directory or a set of files.
2837 * The pattern can have wildcard characters ? and *, but only
2838 * in the section after the last directory delimiter. (Return
2839 * ERROR_INVALID_NAME if there are wildcards in earlier path
2840 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2841 * means "match one character", "??" seems to mean "match one
2842 * or two characters", "???" seems to mean "match one, two or
2843 * three characters", etc. Windows will also try and match
2844 * the mangled "short name" of files, so 8 character patterns
2845 * with wildcards will show some surprising results.
2847 * All the written documentation I can find says that '?'
2848 * should only match one character, and doesn't mention '??',
2849 * '???' etc. I'm going to assume that the strict behaviour
2850 * (ie '???' means three and only three characters) is the
2851 * correct one, because that lets me use fnmatch(3) rather
2852 * than mess around with regexes.
2855 find_handle.namelist = NULL;
2856 result = _wapi_io_scandir (dir_part, entry_part,
2857 &find_handle.namelist);
2860 /* No files, which windows seems to call
2863 SetLastError (ERROR_FILE_NOT_FOUND);
2864 g_free (utf8_pattern);
2865 g_free (entry_part);
2867 return (INVALID_HANDLE_VALUE);
2871 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2872 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: scandir error: %s", __func__, g_strerror (errno));
2873 g_free (utf8_pattern);
2874 g_free (entry_part);
2876 return (INVALID_HANDLE_VALUE);
2879 g_free (utf8_pattern);
2880 g_free (entry_part);
2882 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Got %d matches", __func__, result);
2884 find_handle.dir_part = dir_part;
2885 find_handle.num = result;
2886 find_handle.count = 0;
2888 handle = mono_w32handle_new (MONO_W32HANDLE_FIND, &find_handle);
2889 if (handle == INVALID_HANDLE_VALUE) {
2890 g_warning ("%s: error creating find handle", __func__);
2892 g_free (entry_part);
2893 g_free (utf8_pattern);
2894 SetLastError (ERROR_GEN_FAILURE);
2896 return(INVALID_HANDLE_VALUE);
2899 if (handle != INVALID_HANDLE_VALUE &&
2900 !FindNextFile (handle, find_data)) {
2902 SetLastError (ERROR_NO_MORE_FILES);
2903 handle = INVALID_HANDLE_VALUE;
2909 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2911 struct _WapiHandle_find *find_handle;
2913 struct stat buf, linkbuf;
2916 gchar *utf8_filename, *utf8_basename;
2917 gunichar2 *utf16_basename;
2921 gboolean ret = FALSE;
2923 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FIND,
2924 (gpointer *)&find_handle);
2926 g_warning ("%s: error looking up find handle %p", __func__,
2928 SetLastError (ERROR_INVALID_HANDLE);
2932 thr_ret = mono_w32handle_lock_handle (handle);
2933 g_assert (thr_ret == 0);
2936 if (find_handle->count >= find_handle->num) {
2937 SetLastError (ERROR_NO_MORE_FILES);
2941 /* stat next match */
2943 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2945 result = _wapi_stat (filename, &buf);
2946 if (result == -1 && errno == ENOENT) {
2947 /* Might be a dangling symlink */
2948 result = _wapi_lstat (filename, &buf);
2952 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: stat failed: %s", __func__, filename);
2958 #ifndef __native_client__
2959 result = _wapi_lstat (filename, &linkbuf);
2961 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lstat failed: %s", __func__, filename);
2968 utf8_filename = mono_utf8_from_external (filename);
2969 if (utf8_filename == NULL) {
2970 /* We couldn't turn this filename into utf8 (eg the
2971 * encoding of the name wasn't convertible), so just
2974 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2981 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Found [%s]", __func__, utf8_filename);
2983 /* fill data block */
2985 if (buf.st_mtime < buf.st_ctime)
2986 create_time = buf.st_mtime;
2988 create_time = buf.st_ctime;
2990 #ifdef __native_client__
2991 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, NULL);
2993 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2996 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2997 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2998 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
3000 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3001 find_data->nFileSizeHigh = 0;
3002 find_data->nFileSizeLow = 0;
3004 find_data->nFileSizeHigh = buf.st_size >> 32;
3005 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3008 find_data->dwReserved0 = 0;
3009 find_data->dwReserved1 = 0;
3011 utf8_basename = _wapi_basename (utf8_filename);
3012 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
3014 if(utf16_basename==NULL) {
3015 g_free (utf8_basename);
3016 g_free (utf8_filename);
3021 /* utf16 is 2 * utf8 */
3024 memset (find_data->cFileName, '\0', (MAX_PATH*2));
3026 /* Truncating a utf16 string like this might leave the last
3029 memcpy (find_data->cFileName, utf16_basename,
3030 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3032 find_data->cAlternateFileName [0] = 0; /* not used */
3034 g_free (utf8_basename);
3035 g_free (utf8_filename);
3036 g_free (utf16_basename);
3039 thr_ret = mono_w32handle_unlock_handle (handle);
3040 g_assert (thr_ret == 0);
3047 * @wapi_handle: the find handle to close.
3049 * Closes find handle @wapi_handle
3051 * Return value: %TRUE on success, %FALSE otherwise.
3053 gboolean FindClose (gpointer handle)
3055 struct _WapiHandle_find *find_handle;
3059 if (handle == NULL) {
3060 SetLastError (ERROR_INVALID_HANDLE);
3064 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FIND,
3065 (gpointer *)&find_handle);
3067 g_warning ("%s: error looking up find handle %p", __func__,
3069 SetLastError (ERROR_INVALID_HANDLE);
3073 thr_ret = mono_w32handle_lock_handle (handle);
3074 g_assert (thr_ret == 0);
3076 g_strfreev (find_handle->namelist);
3077 g_free (find_handle->dir_part);
3079 thr_ret = mono_w32handle_unlock_handle (handle);
3080 g_assert (thr_ret == 0);
3082 mono_w32handle_unref (handle);
3089 * @name: a pointer to a NULL-terminated unicode string, that names
3090 * the directory to be created.
3091 * @security: ignored for now
3093 * Creates directory @name
3095 * Return value: %TRUE on success, %FALSE otherwise.
3097 gboolean CreateDirectory (const gunichar2 *name,
3098 WapiSecurityAttributes *security)
3104 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3106 SetLastError (ERROR_INVALID_NAME);
3110 utf8_name = mono_unicode_to_external (name);
3111 if (utf8_name == NULL) {
3112 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3114 SetLastError (ERROR_INVALID_NAME);
3118 result = _wapi_mkdir (utf8_name, 0777);
3125 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3132 * @name: a pointer to a NULL-terminated unicode string, that names
3133 * the directory to be removed.
3135 * Removes directory @name
3137 * Return value: %TRUE on success, %FALSE otherwise.
3139 gboolean RemoveDirectory (const gunichar2 *name)
3145 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3147 SetLastError (ERROR_INVALID_NAME);
3151 utf8_name = mono_unicode_to_external (name);
3152 if (utf8_name == NULL) {
3153 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3155 SetLastError (ERROR_INVALID_NAME);
3159 result = _wapi_rmdir (utf8_name);
3161 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3172 * GetFileAttributes:
3173 * @name: a pointer to a NULL-terminated unicode filename.
3175 * Gets the attributes for @name;
3177 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3179 guint32 GetFileAttributes (const gunichar2 *name)
3182 struct stat buf, linkbuf;
3187 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3189 SetLastError (ERROR_INVALID_NAME);
3193 utf8_name = mono_unicode_to_external (name);
3194 if (utf8_name == NULL) {
3195 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3197 SetLastError (ERROR_INVALID_PARAMETER);
3198 return (INVALID_FILE_ATTRIBUTES);
3201 result = _wapi_stat (utf8_name, &buf);
3202 if (result == -1 && errno == ENOENT) {
3203 /* Might be a dangling symlink... */
3204 result = _wapi_lstat (utf8_name, &buf);
3208 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3210 return (INVALID_FILE_ATTRIBUTES);
3213 #ifndef __native_client__
3214 result = _wapi_lstat (utf8_name, &linkbuf);
3216 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3218 return (INVALID_FILE_ATTRIBUTES);
3222 #ifdef __native_client__
3223 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, NULL);
3225 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3234 * GetFileAttributesEx:
3235 * @name: a pointer to a NULL-terminated unicode filename.
3236 * @level: must be GetFileExInfoStandard
3237 * @info: pointer to a WapiFileAttributesData structure
3239 * Gets attributes, size and filetimes for @name;
3241 * Return value: %TRUE on success, %FALSE on failure
3243 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3246 WapiFileAttributesData *data;
3248 struct stat buf, linkbuf;
3252 if (level != GetFileExInfoStandard) {
3253 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: info level %d not supported.", __func__,
3256 SetLastError (ERROR_INVALID_PARAMETER);
3261 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3263 SetLastError (ERROR_INVALID_NAME);
3267 utf8_name = mono_unicode_to_external (name);
3268 if (utf8_name == NULL) {
3269 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3271 SetLastError (ERROR_INVALID_PARAMETER);
3275 result = _wapi_stat (utf8_name, &buf);
3276 if (result == -1 && errno == ENOENT) {
3277 /* Might be a dangling symlink... */
3278 result = _wapi_lstat (utf8_name, &buf);
3282 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3287 result = _wapi_lstat (utf8_name, &linkbuf);
3289 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3294 /* fill data block */
3296 data = (WapiFileAttributesData *)info;
3298 if (buf.st_mtime < buf.st_ctime)
3299 create_time = buf.st_mtime;
3301 create_time = buf.st_ctime;
3303 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3309 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3310 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3311 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3313 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3314 data->nFileSizeHigh = 0;
3315 data->nFileSizeLow = 0;
3318 data->nFileSizeHigh = buf.st_size >> 32;
3319 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3327 * @name: name of file
3328 * @attrs: attributes to set
3330 * Changes the attributes on a named file.
3332 * Return value: %TRUE on success, %FALSE on failure.
3334 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3336 /* FIXME: think of something clever to do on unix */
3342 * Currently we only handle one *internal* case, with a value that is
3343 * not standard: 0x80000000, which means `set executable bit'
3347 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3349 SetLastError (ERROR_INVALID_NAME);
3353 utf8_name = mono_unicode_to_external (name);
3354 if (utf8_name == NULL) {
3355 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3357 SetLastError (ERROR_INVALID_NAME);
3361 result = _wapi_stat (utf8_name, &buf);
3362 if (result == -1 && errno == ENOENT) {
3363 /* Might be a dangling symlink... */
3364 result = _wapi_lstat (utf8_name, &buf);
3368 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3373 /* Contrary to the documentation, ms allows NORMAL to be
3374 * specified along with other attributes, so dont bother to
3375 * catch that case here.
3377 if (attrs & FILE_ATTRIBUTE_READONLY) {
3378 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWUSR | S_IWOTH | S_IWGRP));
3380 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWUSR);
3383 /* Ignore the other attributes for now */
3385 if (attrs & 0x80000000){
3386 mode_t exec_mask = 0;
3388 if ((buf.st_mode & S_IRUSR) != 0)
3389 exec_mask |= S_IXUSR;
3391 if ((buf.st_mode & S_IRGRP) != 0)
3392 exec_mask |= S_IXGRP;
3394 if ((buf.st_mode & S_IROTH) != 0)
3395 exec_mask |= S_IXOTH;
3397 result = chmod (utf8_name, buf.st_mode | exec_mask);
3399 /* Don't bother to reset executable (might need to change this
3409 * GetCurrentDirectory
3410 * @length: size of the buffer
3411 * @buffer: pointer to buffer that recieves path
3413 * Retrieves the current directory for the current process.
3415 * Return value: number of characters in buffer on success, zero on failure
3417 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3419 gunichar2 *utf16_path;
3423 #ifdef __native_client__
3424 gchar *path = g_get_current_dir ();
3425 if (length < strlen(path) + 1 || path == NULL)
3427 memcpy (buffer, path, strlen(path) + 1);
3429 if (getcwd ((char*)buffer, length) == NULL) {
3430 if (errno == ERANGE) { /*buffer length is not big enough */
3431 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*/
3434 utf16_path = mono_unicode_from_external (path, &bytes);
3435 g_free (utf16_path);
3439 _wapi_set_last_error_from_errno ();
3444 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3445 count = (bytes/2)+1;
3446 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3448 /* Add the terminator */
3449 memset (buffer, '\0', bytes+2);
3450 memcpy (buffer, utf16_path, bytes);
3452 g_free (utf16_path);
3458 * SetCurrentDirectory
3459 * @path: path to new directory
3461 * Changes the directory path for the current process.
3463 * Return value: %TRUE on success, %FALSE on failure.
3465 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3471 SetLastError (ERROR_INVALID_PARAMETER);
3475 utf8_path = mono_unicode_to_external (path);
3476 if (_wapi_chdir (utf8_path) != 0) {
3477 _wapi_set_last_error_from_errno ();
3487 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3488 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3490 struct _WapiHandle_file pipe_read_handle = {0};
3491 struct _WapiHandle_file pipe_write_handle = {0};
3492 gpointer read_handle;
3493 gpointer write_handle;
3497 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Creating pipe", __func__);
3501 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error creating pipe: %s", __func__,
3504 _wapi_set_last_error_from_errno ();
3508 if (filedes[0] >= mono_w32handle_fd_reserve ||
3509 filedes[1] >= mono_w32handle_fd_reserve) {
3510 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
3512 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3520 /* filedes[0] is open for reading, filedes[1] for writing */
3522 pipe_read_handle.fd = filedes [0];
3523 pipe_read_handle.fileaccess = GENERIC_READ;
3524 read_handle = mono_w32handle_new_fd (MONO_W32HANDLE_PIPE, filedes[0],
3526 if (read_handle == INVALID_HANDLE_VALUE) {
3527 g_warning ("%s: error creating pipe read handle", __func__);
3530 SetLastError (ERROR_GEN_FAILURE);
3535 pipe_write_handle.fd = filedes [1];
3536 pipe_write_handle.fileaccess = GENERIC_WRITE;
3537 write_handle = mono_w32handle_new_fd (MONO_W32HANDLE_PIPE, filedes[1],
3538 &pipe_write_handle);
3539 if (write_handle == INVALID_HANDLE_VALUE) {
3540 g_warning ("%s: error creating pipe write handle", __func__);
3541 mono_w32handle_unref (read_handle);
3545 SetLastError (ERROR_GEN_FAILURE);
3550 *readpipe = read_handle;
3551 *writepipe = write_handle;
3553 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning pipe: read handle %p, write handle %p",
3554 __func__, read_handle, write_handle);
3559 #ifdef HAVE_GETFSSTAT
3560 /* Darwin has getfsstat */
3561 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3563 struct statfs *stats;
3566 glong length, total = 0;
3568 n = getfsstat (NULL, 0, MNT_NOWAIT);
3571 size = n * sizeof (struct statfs);
3572 stats = (struct statfs *) g_malloc (size);
3575 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3579 for (i = 0; i < n; i++){
3580 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3581 if (total + length < len){
3582 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3583 buf [total+length] = 0;
3586 total += length + 1;
3595 /* In-place octal sequence replacement */
3597 unescape_octal (gchar *str)
3606 while (*rptr != '\0') {
3607 if (*rptr == '\\') {
3610 c = (*(rptr++) - '0') << 6;
3611 c += (*(rptr++) - '0') << 3;
3612 c += *(rptr++) - '0';
3614 } else if (wptr != rptr) {
3622 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3625 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3626 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3627 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3632 guint32 buffer_index;
3633 guint32 mountpoint_index;
3634 guint32 field_number;
3635 guint32 allocated_size;
3636 guint32 fsname_index;
3637 guint32 fstype_index;
3638 gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3639 gchar *mountpoint_allocated;
3640 gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3641 gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3642 gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3645 gboolean check_mount_source;
3646 } LinuxMountInfoParseState;
3648 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3649 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3650 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3651 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3653 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3657 LinuxMountInfoParseState state;
3658 gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3660 memset (buf, 0, len * sizeof (gunichar2));
3661 fd = open ("/proc/self/mountinfo", O_RDONLY);
3663 parser = GetLogicalDriveStrings_MountInfo;
3665 fd = open ("/proc/mounts", O_RDONLY);
3667 parser = GetLogicalDriveStrings_Mounts;
3671 ret = GetLogicalDriveStrings_Mtab (len, buf);
3675 memset (&state, 0, sizeof (LinuxMountInfoParseState));
3676 state.field_number = 1;
3677 state.delimiter = ' ';
3679 while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3680 state.buffer_index = 0;
3682 while ((*parser)(len, buf, &state)) {
3683 if (state.buffer [state.buffer_index] == '\n') {
3684 gboolean quit = add_drive_string (len, buf, &state);
3685 state.field_number = 1;
3686 state.buffer_index++;
3687 if (state.mountpoint_allocated) {
3688 g_free (state.mountpoint_allocated);
3689 state.mountpoint_allocated = NULL;
3706 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3710 if (state->field_number == 1)
3711 state->check_mount_source = TRUE;
3713 while (state->buffer_index < (guint32)state->nbytes) {
3714 if (state->buffer [state->buffer_index] == state->delimiter) {
3715 state->field_number++;
3716 switch (state->field_number) {
3718 state->mountpoint_index = 0;
3722 if (state->mountpoint_allocated)
3723 state->mountpoint_allocated [state->mountpoint_index] = 0;
3725 state->mountpoint [state->mountpoint_index] = 0;
3729 ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3731 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3733 state->buffer_index = state->nbytes;
3736 state->buffer_index++;
3738 } else if (state->buffer [state->buffer_index] == '\n')
3741 switch (state->field_number) {
3743 if (state->check_mount_source) {
3744 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3745 /* We can ignore the rest, it's a device
3747 state->check_mount_source = FALSE;
3748 state->fsname [state->fsname_index++] = '/';
3751 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3752 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3757 append_to_mountpoint (state);
3761 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3762 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3766 state->buffer_index++;
3772 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3774 while (state->buffer_index < (guint32)state->nbytes) {
3775 if (state->buffer [state->buffer_index] == state->delimiter) {
3776 state->field_number++;
3777 switch (state->field_number) {
3779 state->mountpoint_index = 0;
3783 if (state->mountpoint_allocated)
3784 state->mountpoint_allocated [state->mountpoint_index] = 0;
3786 state->mountpoint [state->mountpoint_index] = 0;
3790 state->delimiter = '-';
3794 state->delimiter = ' ';
3798 state->check_mount_source = TRUE;
3801 state->buffer_index++;
3803 } else if (state->buffer [state->buffer_index] == '\n')
3806 switch (state->field_number) {
3808 append_to_mountpoint (state);
3812 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3813 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3817 if (state->check_mount_source) {
3818 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3819 /* We can ignore the rest, it's a device
3821 state->check_mount_source = FALSE;
3822 state->fsname [state->fsname_index++] = '/';
3825 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3826 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3831 state->buffer_index++;
3838 append_to_mountpoint (LinuxMountInfoParseState *state)
3840 gchar ch = state->buffer [state->buffer_index];
3841 if (state->mountpoint_allocated) {
3842 if (state->mountpoint_index >= state->allocated_size) {
3843 guint32 newsize = (state->allocated_size << 1) + 1;
3844 gchar *newbuf = (gchar *)g_malloc0 (newsize * sizeof (gchar));
3846 memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3847 g_free (state->mountpoint_allocated);
3848 state->mountpoint_allocated = newbuf;
3849 state->allocated_size = newsize;
3851 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3853 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3854 state->allocated_size = (state->mountpoint_index << 1) + 1;
3855 state->mountpoint_allocated = (gchar *)g_malloc0 (state->allocated_size * sizeof (gchar));
3856 memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3857 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3859 state->mountpoint [state->mountpoint_index++] = ch;
3864 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3866 gboolean quit = FALSE;
3867 gboolean ignore_entry;
3869 if (state->fsname_index == 1 && state->fsname [0] == '/')
3870 ignore_entry = FALSE;
3871 else if (memcmp ("overlay", state->fsname, state->fsname_index) == 0 ||
3872 memcmp ("aufs", state->fstype, state->fstype_index) == 0) {
3873 /* Don't ignore overlayfs and aufs - these might be used on Docker
3874 * (https://bugzilla.xamarin.com/show_bug.cgi?id=31021) */
3875 ignore_entry = FALSE;
3876 } else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0) {
3877 ignore_entry = TRUE;
3878 } else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3879 /* Ignore GNOME's gvfs */
3880 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3881 ignore_entry = TRUE;
3883 ignore_entry = FALSE;
3884 } else if (state->fstype_index == 3 && memcmp ("nfs", state->fstype, state->fstype_index) == 0)
3885 ignore_entry = FALSE;
3887 ignore_entry = TRUE;
3889 if (!ignore_entry) {
3892 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3894 unescape_octal (mountpoint);
3895 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3896 if (state->total + length + 1 > len) {
3898 state->total = len * 2;
3901 memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3902 state->total += length;
3906 state->fsname_index = 0;
3907 state->fstype_index = 0;
3913 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3915 return GetLogicalDriveStrings_Mtab (len, buf);
3919 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3922 gunichar2 *ptr, *dir;
3923 glong length, total = 0;
3927 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3932 /* Sigh, mntent and friends don't work well.
3933 * It stops on the first line that doesn't begin with a '/'.
3934 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3935 fp = fopen ("/etc/mtab", "rt");
3937 fp = fopen ("/etc/mnttab", "rt");
3943 while (fgets (buffer, 512, fp) != NULL) {
3947 splitted = g_strsplit (buffer, " ", 0);
3948 if (!*splitted || !*(splitted + 1)) {
3949 g_strfreev (splitted);
3953 unescape_octal (*(splitted + 1));
3954 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3955 g_strfreev (splitted);
3956 if (total + length + 1 > len) {
3959 return len * 2; /* guess */
3962 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3964 total += length + 1;
3969 /* Commented out, does not work with my mtab!!! - Gonz */
3970 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3974 gunichar2 *ptr, *dir;
3975 glong len, total = 0;
3978 fp = setmntent ("/etc/mtab", "rt");
3980 fp = setmntent ("/etc/mnttab", "rt");
3986 while ((mnt = getmntent (fp)) != NULL) {
3987 g_print ("GOT %s\n", mnt->mnt_dir);
3988 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3989 if (total + len + 1 > len) {
3990 return len * 2; /* guess */
3993 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
4005 #if defined(HAVE_STATVFS) || defined(HAVE_STATFS)
4006 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4007 WapiULargeInteger *total_number_of_bytes,
4008 WapiULargeInteger *total_number_of_free_bytes)
4011 struct statvfs fsstat;
4012 #elif defined(HAVE_STATFS)
4013 struct statfs fsstat;
4015 gboolean isreadonly;
4016 gchar *utf8_path_name;
4018 unsigned long block_size;
4020 if (path_name == NULL) {
4021 utf8_path_name = g_strdup (g_get_current_dir());
4022 if (utf8_path_name == NULL) {
4023 SetLastError (ERROR_DIRECTORY);
4028 utf8_path_name = mono_unicode_to_external (path_name);
4029 if (utf8_path_name == NULL) {
4030 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4032 SetLastError (ERROR_INVALID_NAME);
4039 ret = statvfs (utf8_path_name, &fsstat);
4040 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
4041 block_size = fsstat.f_frsize;
4042 #elif defined(HAVE_STATFS)
4043 ret = statfs (utf8_path_name, &fsstat);
4044 #if defined (MNT_RDONLY)
4045 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
4046 #elif defined (MS_RDONLY)
4047 isreadonly = ((fsstat.f_flags & MS_RDONLY) == MS_RDONLY);
4049 block_size = fsstat.f_bsize;
4051 } while(ret == -1 && errno == EINTR);
4053 g_free(utf8_path_name);
4056 _wapi_set_last_error_from_errno ();
4057 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: statvfs failed: %s", __func__, strerror (errno));
4061 /* total number of free bytes for non-root */
4062 if (free_bytes_avail != NULL) {
4064 free_bytes_avail->QuadPart = 0;
4067 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
4071 /* total number of bytes available for non-root */
4072 if (total_number_of_bytes != NULL) {
4073 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
4076 /* total number of bytes available for root */
4077 if (total_number_of_free_bytes != NULL) {
4079 total_number_of_free_bytes->QuadPart = 0;
4082 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
4089 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4090 WapiULargeInteger *total_number_of_bytes,
4091 WapiULargeInteger *total_number_of_free_bytes)
4093 if (free_bytes_avail != NULL) {
4094 free_bytes_avail->QuadPart = (guint64) -1;
4097 if (total_number_of_bytes != NULL) {
4098 total_number_of_bytes->QuadPart = (guint64) -1;
4101 if (total_number_of_free_bytes != NULL) {
4102 total_number_of_free_bytes->QuadPart = (guint64) -1;
4110 * General Unix support
4115 const long fstypeid;
4117 const gchar* fstype;
4120 static _wapi_drive_type _wapi_drive_types[] = {
4122 { DRIVE_REMOTE, "afp" },
4123 { DRIVE_REMOTE, "autofs" },
4124 { DRIVE_CDROM, "cddafs" },
4125 { DRIVE_CDROM, "cd9660" },
4126 { DRIVE_RAMDISK, "devfs" },
4127 { DRIVE_FIXED, "exfat" },
4128 { DRIVE_RAMDISK, "fdesc" },
4129 { DRIVE_REMOTE, "ftp" },
4130 { DRIVE_FIXED, "hfs" },
4131 { DRIVE_FIXED, "msdos" },
4132 { DRIVE_REMOTE, "nfs" },
4133 { DRIVE_FIXED, "ntfs" },
4134 { DRIVE_REMOTE, "smbfs" },
4135 { DRIVE_FIXED, "udf" },
4136 { DRIVE_REMOTE, "webdav" },
4137 { DRIVE_UNKNOWN, NULL }
4139 { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
4140 { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
4141 { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
4142 { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
4143 { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
4144 { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
4145 { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
4146 { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
4147 { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
4148 { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
4149 { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
4150 { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
4151 { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
4152 { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
4153 { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
4154 { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
4155 { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
4156 { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4157 { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4158 { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4159 { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4160 { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4161 { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4162 { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4163 { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4164 { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4165 { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4166 { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4167 { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4168 { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4169 { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4170 { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4171 { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4172 { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4173 { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4174 { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4175 { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4176 { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4177 { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4178 { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4179 { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4180 { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4181 { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4182 { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4183 { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4184 { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4185 { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4186 { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4187 { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4188 { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4189 { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4190 { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4191 { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4192 { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4193 { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4194 { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4195 { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4196 { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4197 { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4198 { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4199 { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4200 { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4201 { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4202 { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4203 { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4204 { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4205 { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4206 { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4207 { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4208 { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4209 { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4210 { DRIVE_UNKNOWN, 0, NULL}
4212 { DRIVE_RAMDISK, "ramfs" },
4213 { DRIVE_RAMDISK, "tmpfs" },
4214 { DRIVE_RAMDISK, "proc" },
4215 { DRIVE_RAMDISK, "sysfs" },
4216 { DRIVE_RAMDISK, "debugfs" },
4217 { DRIVE_RAMDISK, "devpts" },
4218 { DRIVE_RAMDISK, "securityfs" },
4219 { DRIVE_CDROM, "iso9660" },
4220 { DRIVE_FIXED, "ext2" },
4221 { DRIVE_FIXED, "ext3" },
4222 { DRIVE_FIXED, "ext4" },
4223 { DRIVE_FIXED, "sysv" },
4224 { DRIVE_FIXED, "reiserfs" },
4225 { DRIVE_FIXED, "ufs" },
4226 { DRIVE_FIXED, "vfat" },
4227 { DRIVE_FIXED, "msdos" },
4228 { DRIVE_FIXED, "udf" },
4229 { DRIVE_FIXED, "hfs" },
4230 { DRIVE_FIXED, "hpfs" },
4231 { DRIVE_FIXED, "qnx4" },
4232 { DRIVE_FIXED, "ntfs" },
4233 { DRIVE_FIXED, "ntfs-3g" },
4234 { DRIVE_REMOTE, "smbfs" },
4235 { DRIVE_REMOTE, "fuse" },
4236 { DRIVE_REMOTE, "nfs" },
4237 { DRIVE_REMOTE, "nfs4" },
4238 { DRIVE_REMOTE, "cifs" },
4239 { DRIVE_REMOTE, "ncpfs" },
4240 { DRIVE_REMOTE, "coda" },
4241 { DRIVE_REMOTE, "afs" },
4242 { DRIVE_UNKNOWN, NULL }
4247 static guint32 _wapi_get_drive_type(long f_type)
4249 _wapi_drive_type *current;
4251 current = &_wapi_drive_types[0];
4252 while (current->drive_type != DRIVE_UNKNOWN) {
4253 if (current->fstypeid == f_type)
4254 return current->drive_type;
4258 return DRIVE_UNKNOWN;
4261 static guint32 _wapi_get_drive_type(const gchar* fstype)
4263 _wapi_drive_type *current;
4265 current = &_wapi_drive_types[0];
4266 while (current->drive_type != DRIVE_UNKNOWN) {
4267 if (strcmp (current->fstype, fstype) == 0)
4273 return current->drive_type;
4277 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4279 GetDriveTypeFromPath (const char *utf8_root_path_name)
4283 if (statfs (utf8_root_path_name, &buf) == -1)
4284 return DRIVE_UNKNOWN;
4286 return _wapi_get_drive_type (buf.f_fstypename);
4288 return _wapi_get_drive_type (buf.f_type);
4293 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4300 fp = fopen ("/etc/mtab", "rt");
4302 fp = fopen ("/etc/mnttab", "rt");
4304 return(DRIVE_UNKNOWN);
4307 drive_type = DRIVE_NO_ROOT_DIR;
4308 while (fgets (buffer, 512, fp) != NULL) {
4309 splitted = g_strsplit (buffer, " ", 0);
4310 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4311 g_strfreev (splitted);
4315 /* compare given root_path_name with the one from mtab,
4316 if length of utf8_root_path_name is zero it must be the root dir */
4317 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4318 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4319 drive_type = _wapi_get_drive_type (*(splitted + 2));
4320 /* it is possible this path might be mounted again with
4321 a known type...keep looking */
4322 if (drive_type != DRIVE_UNKNOWN) {
4323 g_strfreev (splitted);
4328 g_strfreev (splitted);
4336 guint32 GetDriveType(const gunichar2 *root_path_name)
4338 gchar *utf8_root_path_name;
4341 if (root_path_name == NULL) {
4342 utf8_root_path_name = g_strdup (g_get_current_dir());
4343 if (utf8_root_path_name == NULL) {
4344 return(DRIVE_NO_ROOT_DIR);
4348 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4349 if (utf8_root_path_name == NULL) {
4350 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4351 return(DRIVE_NO_ROOT_DIR);
4354 /* strip trailing slash for compare below */
4355 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4356 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4359 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4360 g_free (utf8_root_path_name);
4362 return (drive_type);
4365 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__) || defined(__FreeBSD_kernel__)
4367 get_fstypename (gchar *utfpath)
4369 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4372 _wapi_drive_type *current;
4374 if (statfs (utfpath, &stat) == -1)
4377 return g_strdup (stat.f_fstypename);
4379 current = &_wapi_drive_types[0];
4380 while (current->drive_type != DRIVE_UNKNOWN) {
4381 if (stat.f_type == current->fstypeid)
4382 return g_strdup (current->fstype);
4392 /* Linux has struct statfs which has a different layout */
4394 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4398 gboolean status = FALSE;
4401 // We only support getting the file system type
4402 if (fsbuffer == NULL)
4405 utfpath = mono_unicode_to_external (path);
4406 if ((fstypename = get_fstypename (utfpath)) != NULL){
4407 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4408 if (ret != NULL && len < fsbuffersize){
4409 memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4415 g_free (fstypename);
4423 _wapi_io_init (void)
4425 mono_os_mutex_init (&stdhandle_mutex);
4427 mono_w32handle_register_ops (MONO_W32HANDLE_FILE, &_wapi_file_ops);
4428 mono_w32handle_register_ops (MONO_W32HANDLE_CONSOLE, &_wapi_console_ops);
4429 mono_w32handle_register_ops (MONO_W32HANDLE_FIND, &_wapi_find_ops);
4430 mono_w32handle_register_ops (MONO_W32HANDLE_PIPE, &_wapi_pipe_ops);
4432 /* mono_w32handle_register_capabilities (MONO_W32HANDLE_FILE, */
4433 /* MONO_W32HANDLE_CAP_WAIT); */
4434 /* mono_w32handle_register_capabilities (MONO_W32HANDLE_CONSOLE, */
4435 /* MONO_W32HANDLE_CAP_WAIT); */
4437 if (g_getenv ("MONO_STRICT_IO_EMULATION"))
4438 lock_while_writing = TRUE;
4442 _wapi_io_cleanup (void)
4444 if (file_share_hash) {
4445 g_hash_table_destroy (file_share_hash);
4446 mono_os_mutex_destroy (&file_share_hash_mutex);