2 * io.c: File, console and find handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002 Ximian, Inc.
8 * Copyright (c) 2002-2006 Novell, Inc.
9 * Copyright 2011 Xamarin Inc (http://www.xamarin.com).
10 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
20 #ifdef HAVE_SYS_STATVFS_H
21 #include <sys/statvfs.h>
23 #if defined(HAVE_SYS_STATFS_H)
24 #include <sys/statfs.h>
26 #if defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H)
27 #include <sys/param.h>
28 #include <sys/mount.h>
30 #include <sys/types.h>
34 #include <sys/ioctl.h>
36 #include <mono/utils/linux_magic.h>
39 #include <mono/io-layer/wapi.h>
40 #include <mono/io-layer/wapi-private.h>
41 #include <mono/io-layer/handles-private.h>
42 #include <mono/io-layer/io-private.h>
43 #include <mono/io-layer/timefuncs-private.h>
44 #include <mono/io-layer/thread-private.h>
45 #include <mono/io-layer/io-portability.h>
46 #include <mono/io-layer/io-trace.h>
47 #include <mono/utils/strenc.h>
48 #include <mono/utils/mono-once.h>
49 #include <mono/utils/mono-logger-internals.h>
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 WapiHandleOps _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 WapiHandleOps _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 WapiHandleOps _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 WapiHandleOps _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[WAPI_HANDLE_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 mono_once_t io_ops_once=MONO_ONCE_INIT;
326 static gboolean lock_while_writing = FALSE;
328 static void io_ops_init (void)
330 /* _wapi_handle_register_capabilities (WAPI_HANDLE_FILE, */
331 /* WAPI_HANDLE_CAP_WAIT); */
332 /* _wapi_handle_register_capabilities (WAPI_HANDLE_CONSOLE, */
333 /* WAPI_HANDLE_CAP_WAIT); */
335 if (g_getenv ("MONO_STRICT_IO_EMULATION") != NULL) {
336 lock_while_writing = TRUE;
340 /* Some utility functions.
344 * Check if a file is writable by the current user.
346 * This is is a best effort kind of thing. It assumes a reasonable sane set
347 * of permissions by the underlying OS.
349 * We generally assume that basic unix permission bits are authoritative. Which might not
350 * be the case under systems with extended permissions systems (posix ACLs, SELinux, OSX/iOS sandboxing, etc)
352 * The choice of access as the fallback is due to the expected lower overhead compared to trying to open the file.
354 * The only expected problem with using access are for root, setuid or setgid programs as access is not consistent
355 * under those situations. It's to be expected that this should not happen in practice as those bits are very dangerous
356 * and should not be used with a dynamic runtime.
359 is_file_writable (struct stat *st, const char *path)
362 // OS X Finder "locked" or `ls -lO` "uchg".
363 // This only covers one of several cases where an OS X file could be unwritable through special flags.
364 if (st->st_flags & (UF_IMMUTABLE|SF_IMMUTABLE))
368 /* Is it globally writable? */
369 if (st->st_mode & S_IWOTH)
372 /* Am I the owner? */
373 if ((st->st_uid == geteuid ()) && (st->st_mode & S_IWUSR))
376 /* Am I in the same group? */
377 if ((st->st_gid == getegid ()) && (st->st_mode & S_IWGRP))
380 /* Fallback to using access(2). It's not ideal as it might not take into consideration euid/egid
381 * but it's the only sane option we have on unix.
383 return access (path, W_OK) == 0;
387 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
394 /* FIXME: this could definitely be better, but there seems to
395 * be no pattern to the attributes that are set
398 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
399 if (S_ISSOCK (buf->st_mode))
400 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
402 filename = _wapi_basename (pathname);
404 if (S_ISDIR (buf->st_mode)) {
405 attrs = FILE_ATTRIBUTE_DIRECTORY;
406 if (!is_file_writable (buf, pathname)) {
407 attrs |= FILE_ATTRIBUTE_READONLY;
409 if (filename[0] == '.') {
410 attrs |= FILE_ATTRIBUTE_HIDDEN;
413 if (!is_file_writable (buf, pathname)) {
414 attrs = FILE_ATTRIBUTE_READONLY;
416 if (filename[0] == '.') {
417 attrs |= FILE_ATTRIBUTE_HIDDEN;
419 } else if (filename[0] == '.') {
420 attrs = FILE_ATTRIBUTE_HIDDEN;
422 attrs = FILE_ATTRIBUTE_NORMAL;
427 if (S_ISLNK (lbuf->st_mode)) {
428 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
438 _wapi_set_last_error_from_errno (void)
440 SetLastError (_wapi_get_win32_file_error (errno));
443 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
446 if (errno == ENOENT) {
447 /* Check the path - if it's a missing directory then
448 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
454 dirname = _wapi_dirname (path);
456 dirname = g_strdup (dir);
459 if (_wapi_access (dirname, F_OK) == 0) {
460 SetLastError (ERROR_FILE_NOT_FOUND);
462 SetLastError (ERROR_PATH_NOT_FOUND);
467 _wapi_set_last_error_from_errno ();
473 static void file_close (gpointer handle, gpointer data)
475 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
476 int fd = file_handle->fd;
478 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing file handle %p [%s]", __func__, handle,
479 file_handle->filename);
481 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
482 _wapi_unlink (file_handle->filename);
484 g_free (file_handle->filename);
486 if (file_handle->share_info)
487 _wapi_handle_share_release (file_handle->share_info);
492 static void file_details (gpointer data)
494 struct _WapiHandle_file *file = (struct _WapiHandle_file *)data;
496 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
498 file->fileaccess&GENERIC_READ?'R':'.',
499 file->fileaccess&GENERIC_WRITE?'W':'.',
500 file->fileaccess&GENERIC_EXECUTE?'X':'.',
501 file->sharemode&FILE_SHARE_READ?'R':'.',
502 file->sharemode&FILE_SHARE_WRITE?'W':'.',
503 file->sharemode&FILE_SHARE_DELETE?'D':'.',
507 static const gchar* file_typename (void)
512 static gsize file_typesize (void)
514 return sizeof (struct _WapiHandle_file);
517 static WapiFileType file_getfiletype(void)
519 return(FILE_TYPE_DISK);
522 static gboolean file_read(gpointer handle, gpointer buffer,
523 guint32 numbytes, guint32 *bytesread,
524 WapiOverlapped *overlapped)
526 struct _WapiHandle_file *file_handle;
530 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
531 (gpointer *)&file_handle);
533 g_warning ("%s: error looking up file handle %p", __func__,
535 SetLastError (ERROR_INVALID_HANDLE);
539 fd = file_handle->fd;
540 if(bytesread!=NULL) {
544 if(!(file_handle->fileaccess & GENERIC_READ) &&
545 !(file_handle->fileaccess & GENERIC_ALL)) {
546 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
547 __func__, handle, file_handle->fileaccess);
549 SetLastError (ERROR_ACCESS_DENIED);
554 ret = read (fd, buffer, numbytes);
555 } while (ret == -1 && errno == EINTR &&
556 !_wapi_thread_cur_apc_pending());
561 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
562 handle, strerror(err));
563 SetLastError (_wapi_get_win32_file_error (err));
567 if (bytesread != NULL) {
574 static gboolean file_write(gpointer handle, gconstpointer buffer,
575 guint32 numbytes, guint32 *byteswritten,
576 WapiOverlapped *overlapped G_GNUC_UNUSED)
578 struct _WapiHandle_file *file_handle;
581 off_t current_pos = 0;
583 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
584 (gpointer *)&file_handle);
586 g_warning ("%s: error looking up file handle %p", __func__,
588 SetLastError (ERROR_INVALID_HANDLE);
592 fd = file_handle->fd;
594 if(byteswritten!=NULL) {
598 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
599 !(file_handle->fileaccess & GENERIC_ALL)) {
600 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);
602 SetLastError (ERROR_ACCESS_DENIED);
606 if (lock_while_writing) {
607 /* Need to lock the region we're about to write to,
608 * because we only do advisory locking on POSIX
611 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
612 if (current_pos == -1) {
613 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
614 handle, strerror (errno));
615 _wapi_set_last_error_from_errno ();
619 if (_wapi_lock_file_region (fd, current_pos,
620 numbytes) == FALSE) {
621 /* The error has already been set */
627 ret = write (fd, buffer, numbytes);
628 } while (ret == -1 && errno == EINTR &&
629 !_wapi_thread_cur_apc_pending());
631 if (lock_while_writing) {
632 _wapi_unlock_file_region (fd, current_pos, numbytes);
636 if (errno == EINTR) {
639 _wapi_set_last_error_from_errno ();
641 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
642 __func__, handle, strerror(errno));
647 if (byteswritten != NULL) {
653 static gboolean file_flush(gpointer handle)
655 struct _WapiHandle_file *file_handle;
659 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
660 (gpointer *)&file_handle);
662 g_warning ("%s: error looking up file handle %p", __func__,
664 SetLastError (ERROR_INVALID_HANDLE);
668 fd = file_handle->fd;
670 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
671 !(file_handle->fileaccess & GENERIC_ALL)) {
672 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);
674 SetLastError (ERROR_ACCESS_DENIED);
680 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fsync of handle %p error: %s", __func__, handle,
683 _wapi_set_last_error_from_errno ();
690 static guint32 file_seek(gpointer handle, gint32 movedistance,
691 gint32 *highmovedistance, WapiSeekMethod method)
693 struct _WapiHandle_file *file_handle;
695 gint64 offset, newpos;
699 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
700 (gpointer *)&file_handle);
702 g_warning ("%s: error looking up file handle %p", __func__,
704 SetLastError (ERROR_INVALID_HANDLE);
705 return(INVALID_SET_FILE_POINTER);
708 fd = file_handle->fd;
710 if(!(file_handle->fileaccess & GENERIC_READ) &&
711 !(file_handle->fileaccess & GENERIC_WRITE) &&
712 !(file_handle->fileaccess & GENERIC_ALL)) {
713 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);
715 SetLastError (ERROR_ACCESS_DENIED);
716 return(INVALID_SET_FILE_POINTER);
730 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: invalid seek type %d", __func__, method);
732 SetLastError (ERROR_INVALID_PARAMETER);
733 return(INVALID_SET_FILE_POINTER);
736 #ifdef HAVE_LARGE_FILE_SUPPORT
737 if(highmovedistance==NULL) {
739 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting offset to %lld (low %d)", __func__,
740 offset, movedistance);
742 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
744 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);
750 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: moving handle %p by %lld bytes from %d", __func__,
751 handle, (long long)offset, whence);
753 #ifdef PLATFORM_ANDROID
754 /* bionic doesn't support -D_FILE_OFFSET_BITS=64 */
755 newpos=lseek64(fd, offset, whence);
757 newpos=lseek(fd, offset, whence);
760 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek on handle %p returned error %s",
761 __func__, handle, strerror(errno));
763 _wapi_set_last_error_from_errno ();
764 return(INVALID_SET_FILE_POINTER);
767 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek returns %lld", __func__, newpos);
769 #ifdef HAVE_LARGE_FILE_SUPPORT
770 ret=newpos & 0xFFFFFFFF;
771 if(highmovedistance!=NULL) {
772 *highmovedistance=newpos>>32;
776 if(highmovedistance!=NULL) {
777 /* Accurate, but potentially dodgy :-) */
782 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: move of handle %p returning %d/%d", __func__,
783 handle, ret, highmovedistance==NULL?0:*highmovedistance);
788 static gboolean file_setendoffile(gpointer handle)
790 struct _WapiHandle_file *file_handle;
796 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
797 (gpointer *)&file_handle);
799 g_warning ("%s: error looking up file handle %p", __func__,
801 SetLastError (ERROR_INVALID_HANDLE);
804 fd = file_handle->fd;
806 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
807 !(file_handle->fileaccess & GENERIC_ALL)) {
808 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);
810 SetLastError (ERROR_ACCESS_DENIED);
814 /* Find the current file position, and the file length. If
815 * the file position is greater than the length, write to
816 * extend the file with a hole. If the file position is less
817 * than the length, truncate the file.
820 ret=fstat(fd, &statbuf);
822 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
823 handle, strerror(errno));
825 _wapi_set_last_error_from_errno ();
829 pos=lseek(fd, (off_t)0, SEEK_CUR);
831 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
832 handle, strerror(errno));
834 _wapi_set_last_error_from_errno ();
838 #ifdef FTRUNCATE_DOESNT_EXTEND
839 off_t size = statbuf.st_size;
840 /* I haven't bothered to write the configure.ac stuff for this
841 * because I don't know if any platform needs it. I'm leaving
842 * this code just in case though
845 /* Extend the file. Use write() here, because some
846 * manuals say that ftruncate() behaviour is undefined
847 * when the file needs extending. The POSIX spec says
848 * that on XSI-conformant systems it extends, so if
849 * every system we care about conforms, then we can
853 ret = write (fd, "", 1);
854 } while (ret == -1 && errno == EINTR &&
855 !_wapi_thread_cur_apc_pending());
858 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
860 _wapi_set_last_error_from_errno ();
864 /* And put the file position back after the write */
865 ret = lseek (fd, pos, SEEK_SET);
867 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p second lseek failed: %s",
868 __func__, handle, strerror(errno));
870 _wapi_set_last_error_from_errno ();
876 /* Native Client has no ftruncate function, even in standalone sel_ldr. */
877 #ifndef __native_client__
878 /* always truncate, because the extend write() adds an extra
879 * byte to the end of the file
882 ret=ftruncate(fd, pos);
884 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
886 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ftruncate failed: %s", __func__,
887 handle, strerror(errno));
889 _wapi_set_last_error_from_errno ();
897 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
899 struct _WapiHandle_file *file_handle;
906 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
907 (gpointer *)&file_handle);
909 g_warning ("%s: error looking up file handle %p", __func__,
911 SetLastError (ERROR_INVALID_HANDLE);
912 return(INVALID_FILE_SIZE);
914 fd = file_handle->fd;
916 if(!(file_handle->fileaccess & GENERIC_READ) &&
917 !(file_handle->fileaccess & GENERIC_WRITE) &&
918 !(file_handle->fileaccess & GENERIC_ALL)) {
919 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);
921 SetLastError (ERROR_ACCESS_DENIED);
922 return(INVALID_FILE_SIZE);
925 /* If the file has a size with the low bits 0xFFFFFFFF the
926 * caller can't tell if this is an error, so clear the error
929 SetLastError (ERROR_SUCCESS);
931 ret = fstat(fd, &statbuf);
933 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
934 handle, strerror(errno));
936 _wapi_set_last_error_from_errno ();
937 return(INVALID_FILE_SIZE);
940 /* fstat indicates block devices as zero-length, so go a different path */
942 if (S_ISBLK(statbuf.st_mode)) {
944 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
945 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ioctl BLKGETSIZE64 failed: %s",
946 __func__, handle, strerror(errno));
948 _wapi_set_last_error_from_errno ();
949 return(INVALID_FILE_SIZE);
952 size = bigsize & 0xFFFFFFFF;
953 if (highsize != NULL) {
954 *highsize = bigsize>>32;
957 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning block device size %d/%d",
958 __func__, size, *highsize);
964 #ifdef HAVE_LARGE_FILE_SUPPORT
965 size = statbuf.st_size & 0xFFFFFFFF;
966 if (highsize != NULL) {
967 *highsize = statbuf.st_size>>32;
970 if (highsize != NULL) {
971 /* Accurate, but potentially dodgy :-) */
974 size = statbuf.st_size;
977 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning size %d/%d", __func__, size, *highsize);
982 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
983 WapiFileTime *last_access,
984 WapiFileTime *last_write)
986 struct _WapiHandle_file *file_handle;
989 guint64 create_ticks, access_ticks, write_ticks;
992 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
993 (gpointer *)&file_handle);
995 g_warning ("%s: error looking up file handle %p", __func__,
997 SetLastError (ERROR_INVALID_HANDLE);
1000 fd = file_handle->fd;
1002 if(!(file_handle->fileaccess & GENERIC_READ) &&
1003 !(file_handle->fileaccess & GENERIC_ALL)) {
1004 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1005 __func__, handle, file_handle->fileaccess);
1007 SetLastError (ERROR_ACCESS_DENIED);
1011 ret=fstat(fd, &statbuf);
1013 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
1016 _wapi_set_last_error_from_errno ();
1020 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: atime: %ld ctime: %ld mtime: %ld", __func__,
1021 statbuf.st_atime, statbuf.st_ctime,
1024 /* Try and guess a meaningful create time by using the older
1027 /* The magic constant comes from msdn documentation
1028 * "Converting a time_t Value to a File Time"
1030 if(statbuf.st_atime < statbuf.st_ctime) {
1031 create_ticks=((guint64)statbuf.st_atime*10000000)
1032 + 116444736000000000ULL;
1034 create_ticks=((guint64)statbuf.st_ctime*10000000)
1035 + 116444736000000000ULL;
1038 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
1039 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
1041 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
1042 access_ticks, create_ticks, write_ticks);
1044 if(create_time!=NULL) {
1045 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
1046 create_time->dwHighDateTime = create_ticks >> 32;
1049 if(last_access!=NULL) {
1050 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
1051 last_access->dwHighDateTime = access_ticks >> 32;
1054 if(last_write!=NULL) {
1055 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
1056 last_write->dwHighDateTime = write_ticks >> 32;
1062 static gboolean file_setfiletime(gpointer handle,
1063 const WapiFileTime *create_time G_GNUC_UNUSED,
1064 const WapiFileTime *last_access,
1065 const WapiFileTime *last_write)
1067 struct _WapiHandle_file *file_handle;
1069 struct utimbuf utbuf;
1070 struct stat statbuf;
1071 guint64 access_ticks, write_ticks;
1074 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
1075 (gpointer *)&file_handle);
1077 g_warning ("%s: error looking up file handle %p", __func__,
1079 SetLastError (ERROR_INVALID_HANDLE);
1082 fd = file_handle->fd;
1084 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
1085 !(file_handle->fileaccess & GENERIC_ALL)) {
1086 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);
1088 SetLastError (ERROR_ACCESS_DENIED);
1092 if(file_handle->filename == NULL) {
1093 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p unknown filename", __func__, handle);
1095 SetLastError (ERROR_INVALID_HANDLE);
1099 /* Get the current times, so we can put the same times back in
1100 * the event that one of the FileTime structs is NULL
1102 ret=fstat (fd, &statbuf);
1104 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
1107 SetLastError (ERROR_INVALID_PARAMETER);
1111 if(last_access!=NULL) {
1112 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
1113 last_access->dwLowDateTime;
1114 /* This is (time_t)0. We can actually go to INT_MIN,
1115 * but this will do for now.
1117 if (access_ticks < 116444736000000000ULL) {
1118 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set access time too early",
1120 SetLastError (ERROR_INVALID_PARAMETER);
1124 if (sizeof (utbuf.actime) == 4 && ((access_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
1125 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",
1127 SetLastError (ERROR_INVALID_PARAMETER);
1131 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
1133 utbuf.actime=statbuf.st_atime;
1136 if(last_write!=NULL) {
1137 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
1138 last_write->dwLowDateTime;
1139 /* This is (time_t)0. We can actually go to INT_MIN,
1140 * but this will do for now.
1142 if (write_ticks < 116444736000000000ULL) {
1143 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set write time too early",
1145 SetLastError (ERROR_INVALID_PARAMETER);
1148 if (sizeof (utbuf.modtime) == 4 && ((write_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
1149 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",
1151 SetLastError (ERROR_INVALID_PARAMETER);
1155 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1157 utbuf.modtime=statbuf.st_mtime;
1160 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting handle %p access %ld write %ld", __func__,
1161 handle, utbuf.actime, utbuf.modtime);
1163 ret = _wapi_utime (file_handle->filename, &utbuf);
1165 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p [%s] utime failed: %s", __func__,
1166 handle, file_handle->filename, strerror(errno));
1168 SetLastError (ERROR_INVALID_PARAMETER);
1175 static void console_close (gpointer handle, gpointer data)
1177 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1178 int fd = console_handle->fd;
1180 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing console handle %p", __func__, handle);
1182 g_free (console_handle->filename);
1185 if (console_handle->share_info)
1186 _wapi_handle_share_release (console_handle->share_info);
1191 static void console_details (gpointer data)
1193 file_details (data);
1196 static const gchar* console_typename (void)
1201 static gsize console_typesize (void)
1203 return sizeof (struct _WapiHandle_file);
1206 static WapiFileType console_getfiletype(void)
1208 return(FILE_TYPE_CHAR);
1211 static gboolean console_read(gpointer handle, gpointer buffer,
1212 guint32 numbytes, guint32 *bytesread,
1213 WapiOverlapped *overlapped G_GNUC_UNUSED)
1215 struct _WapiHandle_file *console_handle;
1219 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1220 (gpointer *)&console_handle);
1222 g_warning ("%s: error looking up console handle %p", __func__,
1224 SetLastError (ERROR_INVALID_HANDLE);
1227 fd = console_handle->fd;
1229 if(bytesread!=NULL) {
1233 if(!(console_handle->fileaccess & GENERIC_READ) &&
1234 !(console_handle->fileaccess & GENERIC_ALL)) {
1235 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1236 __func__, handle, console_handle->fileaccess);
1238 SetLastError (ERROR_ACCESS_DENIED);
1243 ret=read(fd, buffer, numbytes);
1244 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1247 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__, handle,
1250 _wapi_set_last_error_from_errno ();
1254 if(bytesread!=NULL) {
1261 static gboolean console_write(gpointer handle, gconstpointer buffer,
1262 guint32 numbytes, guint32 *byteswritten,
1263 WapiOverlapped *overlapped G_GNUC_UNUSED)
1265 struct _WapiHandle_file *console_handle;
1269 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1270 (gpointer *)&console_handle);
1272 g_warning ("%s: error looking up console handle %p", __func__,
1274 SetLastError (ERROR_INVALID_HANDLE);
1277 fd = console_handle->fd;
1279 if(byteswritten!=NULL) {
1283 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1284 !(console_handle->fileaccess & GENERIC_ALL)) {
1285 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);
1287 SetLastError (ERROR_ACCESS_DENIED);
1292 ret = write(fd, buffer, numbytes);
1293 } while (ret == -1 && errno == EINTR &&
1294 !_wapi_thread_cur_apc_pending());
1297 if (errno == EINTR) {
1300 _wapi_set_last_error_from_errno ();
1302 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
1303 __func__, handle, strerror(errno));
1308 if(byteswritten!=NULL) {
1315 static const gchar* find_typename (void)
1320 static gsize find_typesize (void)
1322 return sizeof (struct _WapiHandle_find);
1325 static void pipe_close (gpointer handle, gpointer data)
1327 struct _WapiHandle_file *pipe_handle = (struct _WapiHandle_file*)data;
1328 int fd = pipe_handle->fd;
1330 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing pipe handle %p fd %d", __func__, handle, fd);
1332 /* No filename with pipe handles */
1334 if (pipe_handle->share_info)
1335 _wapi_handle_share_release (pipe_handle->share_info);
1340 static void pipe_details (gpointer data)
1342 file_details (data);
1345 static const gchar* pipe_typename (void)
1350 static gsize pipe_typesize (void)
1352 return sizeof (struct _WapiHandle_file);
1355 static WapiFileType pipe_getfiletype(void)
1357 return(FILE_TYPE_PIPE);
1360 static gboolean pipe_read (gpointer handle, gpointer buffer,
1361 guint32 numbytes, guint32 *bytesread,
1362 WapiOverlapped *overlapped G_GNUC_UNUSED)
1364 struct _WapiHandle_file *pipe_handle;
1368 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1369 (gpointer *)&pipe_handle);
1371 g_warning ("%s: error looking up pipe handle %p", __func__,
1373 SetLastError (ERROR_INVALID_HANDLE);
1376 fd = pipe_handle->fd;
1378 if(bytesread!=NULL) {
1382 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1383 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1384 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1385 __func__, handle, pipe_handle->fileaccess);
1387 SetLastError (ERROR_ACCESS_DENIED);
1391 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: reading up to %d bytes from pipe %p", __func__,
1395 ret=read(fd, buffer, numbytes);
1396 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1399 if (errno == EINTR) {
1402 _wapi_set_last_error_from_errno ();
1404 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
1405 handle, strerror(errno));
1411 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read %d bytes from pipe %p", __func__, ret, handle);
1413 if(bytesread!=NULL) {
1420 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1421 guint32 numbytes, guint32 *byteswritten,
1422 WapiOverlapped *overlapped G_GNUC_UNUSED)
1424 struct _WapiHandle_file *pipe_handle;
1428 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1429 (gpointer *)&pipe_handle);
1431 g_warning ("%s: error looking up pipe handle %p", __func__,
1433 SetLastError (ERROR_INVALID_HANDLE);
1436 fd = pipe_handle->fd;
1438 if(byteswritten!=NULL) {
1442 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1443 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1444 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);
1446 SetLastError (ERROR_ACCESS_DENIED);
1450 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1454 ret = write (fd, buffer, numbytes);
1455 } while (ret == -1 && errno == EINTR &&
1456 !_wapi_thread_cur_apc_pending());
1459 if (errno == EINTR) {
1462 _wapi_set_last_error_from_errno ();
1464 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s", __func__,
1465 handle, strerror(errno));
1470 if(byteswritten!=NULL) {
1477 static int convert_flags(guint32 fileaccess, guint32 createmode)
1481 switch(fileaccess) {
1488 case GENERIC_READ|GENERIC_WRITE:
1492 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown access type 0x%x", __func__,
1497 switch(createmode) {
1499 flags|=O_CREAT|O_EXCL;
1502 flags|=O_CREAT|O_TRUNC;
1509 case TRUNCATE_EXISTING:
1513 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown create mode 0x%x", __func__,
1522 static mode_t convert_perms(guint32 sharemode)
1526 if(sharemode&FILE_SHARE_READ) {
1529 if(sharemode&FILE_SHARE_WRITE) {
1537 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1539 struct _WapiFileShare **share_info)
1541 gboolean file_already_shared;
1542 guint32 file_existing_share, file_existing_access;
1544 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);
1546 if (file_already_shared) {
1547 /* The reference to this share info was incremented
1548 * when we looked it up, so be careful to put it back
1549 * if we conclude we can't use this file.
1551 if (file_existing_share == 0) {
1552 /* Quick and easy, no possibility to share */
1553 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);
1555 _wapi_handle_share_release (*share_info);
1560 if (((file_existing_share == FILE_SHARE_READ) &&
1561 (fileaccess != GENERIC_READ)) ||
1562 ((file_existing_share == FILE_SHARE_WRITE) &&
1563 (fileaccess != GENERIC_WRITE))) {
1564 /* New access mode doesn't match up */
1565 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);
1567 _wapi_handle_share_release (*share_info);
1572 if (((file_existing_access & GENERIC_READ) &&
1573 !(sharemode & FILE_SHARE_READ)) ||
1574 ((file_existing_access & GENERIC_WRITE) &&
1575 !(sharemode & FILE_SHARE_WRITE))) {
1576 /* New share mode doesn't match up */
1577 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);
1579 _wapi_handle_share_release (*share_info);
1584 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
1592 share_allows_delete (struct stat *statbuf, struct _WapiFileShare **share_info)
1594 gboolean file_already_shared;
1595 guint32 file_existing_share, file_existing_access;
1597 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);
1599 if (file_already_shared) {
1600 /* The reference to this share info was incremented
1601 * when we looked it up, so be careful to put it back
1602 * if we conclude we can't use this file.
1604 if (file_existing_share == 0) {
1605 /* Quick and easy, no possibility to share */
1606 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);
1608 _wapi_handle_share_release (*share_info);
1613 if (!(file_existing_share & FILE_SHARE_DELETE)) {
1614 /* New access mode doesn't match up */
1615 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);
1617 _wapi_handle_share_release (*share_info);
1622 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
1630 * @name: a pointer to a NULL-terminated unicode string, that names
1631 * the file or other object to create.
1632 * @fileaccess: specifies the file access mode
1633 * @sharemode: whether the file should be shared. This parameter is
1634 * currently ignored.
1635 * @security: Ignored for now.
1636 * @createmode: specifies whether to create a new file, whether to
1637 * overwrite an existing file, whether to truncate the file, etc.
1638 * @attrs: specifies file attributes and flags. On win32 attributes
1639 * are characteristics of the file, not the handle, and are ignored
1640 * when an existing file is opened. Flags give the library hints on
1641 * how to process a file to optimise performance.
1642 * @template: the handle of an open %GENERIC_READ file that specifies
1643 * attributes to apply to a newly created file, ignoring @attrs.
1644 * Normally this parameter is NULL. This parameter is ignored when an
1645 * existing file is opened.
1647 * Creates a new file handle. This only applies to normal files:
1648 * pipes are handled by CreatePipe(), and console handles are created
1649 * with GetStdHandle().
1651 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1653 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1654 guint32 sharemode, WapiSecurityAttributes *security,
1655 guint32 createmode, guint32 attrs,
1656 gpointer template_ G_GNUC_UNUSED)
1658 struct _WapiHandle_file file_handle = {0};
1660 int flags=convert_flags(fileaccess, createmode);
1661 /*mode_t perms=convert_perms(sharemode);*/
1662 /* we don't use sharemode, because that relates to sharing of
1663 * the file when the file is open and is already handled by
1664 * other code, perms instead are the on-disk permissions and
1665 * this is a sane default.
1670 WapiHandleType handle_type;
1671 struct stat statbuf;
1673 mono_once (&io_ops_once, io_ops_init);
1675 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1678 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1679 SetLastError (ERROR_ENCRYPTION_FAILED);
1680 return INVALID_HANDLE_VALUE;
1684 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1686 SetLastError (ERROR_INVALID_NAME);
1687 return(INVALID_HANDLE_VALUE);
1690 filename = mono_unicode_to_external (name);
1691 if (filename == NULL) {
1692 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1694 SetLastError (ERROR_INVALID_NAME);
1695 return(INVALID_HANDLE_VALUE);
1698 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Opening %s with share 0x%x and access 0x%x", __func__,
1699 filename, sharemode, fileaccess);
1701 fd = _wapi_open (filename, flags, perms);
1703 /* If we were trying to open a directory with write permissions
1704 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1705 * EISDIR. However, this is a bit bogus because calls to
1706 * manipulate the directory (e.g. SetFileTime) will still work on
1707 * the directory because they use other API calls
1708 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1709 * to open the directory again without write permission.
1711 if (fd == -1 && errno == EISDIR)
1713 /* Try again but don't try to make it writable */
1714 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1718 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s: %s", __func__, filename,
1720 _wapi_set_last_path_error_from_errno (NULL, filename);
1723 return(INVALID_HANDLE_VALUE);
1726 if (fd >= _wapi_fd_reserve) {
1727 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
1729 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1734 return(INVALID_HANDLE_VALUE);
1737 ret = fstat (fd, &statbuf);
1739 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fstat error of file %s: %s", __func__,
1740 filename, strerror (errno));
1741 _wapi_set_last_error_from_errno ();
1745 return(INVALID_HANDLE_VALUE);
1747 #ifdef __native_client__
1748 /* Workaround: Native Client currently returns the same fake inode
1749 * for all files, so do a simple hash on the filename so we don't
1750 * use the same share info for each file.
1752 statbuf.st_ino = g_str_hash(filename);
1755 if (share_allows_open (&statbuf, sharemode, fileaccess,
1756 &file_handle.share_info) == FALSE) {
1757 SetLastError (ERROR_SHARING_VIOLATION);
1761 return (INVALID_HANDLE_VALUE);
1763 if (file_handle.share_info == NULL) {
1764 /* No space, so no more files can be opened */
1765 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No space in the share table", __func__);
1767 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1771 return(INVALID_HANDLE_VALUE);
1774 file_handle.filename = filename;
1776 if(security!=NULL) {
1777 //file_handle->security_attributes=_wapi_handle_scratch_store (
1778 //security, sizeof(WapiSecurityAttributes));
1781 file_handle.fd = fd;
1782 file_handle.fileaccess=fileaccess;
1783 file_handle.sharemode=sharemode;
1784 file_handle.attrs=attrs;
1786 #ifdef HAVE_POSIX_FADVISE
1787 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1788 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1789 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1790 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1794 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1796 if (S_ISFIFO (statbuf.st_mode)) {
1797 handle_type = WAPI_HANDLE_PIPE;
1798 /* maintain invariant that pipes have no filename */
1799 file_handle.filename = NULL;
1802 } else if (S_ISCHR (statbuf.st_mode)) {
1803 handle_type = WAPI_HANDLE_CONSOLE;
1805 handle_type = WAPI_HANDLE_FILE;
1808 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1809 if (handle == _WAPI_HANDLE_INVALID) {
1810 g_warning ("%s: error creating file handle", __func__);
1814 SetLastError (ERROR_GEN_FAILURE);
1815 return(INVALID_HANDLE_VALUE);
1818 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p", __func__, handle);
1825 * @name: a pointer to a NULL-terminated unicode string, that names
1826 * the file to be deleted.
1828 * Deletes file @name.
1830 * Return value: %TRUE on success, %FALSE otherwise.
1832 gboolean DeleteFile(const gunichar2 *name)
1836 gboolean ret = FALSE;
1839 struct stat statbuf;
1840 struct _WapiFileShare *shareinfo;
1844 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1846 SetLastError (ERROR_INVALID_NAME);
1850 filename=mono_unicode_to_external(name);
1851 if(filename==NULL) {
1852 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1854 SetLastError (ERROR_INVALID_NAME);
1858 attrs = GetFileAttributes (name);
1859 if (attrs == INVALID_FILE_ATTRIBUTES) {
1860 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file attributes error", __func__);
1861 /* Error set by GetFileAttributes() */
1867 /* Check to make sure sharing allows us to open the file for
1868 * writing. See bug 323389.
1870 * Do the checks that don't need an open file descriptor, for
1871 * simplicity's sake. If we really have to do the full checks
1872 * then we can implement that later.
1874 if (_wapi_stat (filename, &statbuf) < 0) {
1875 _wapi_set_last_path_error_from_errno (NULL, filename);
1880 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1881 &shareinfo) == FALSE) {
1882 SetLastError (ERROR_SHARING_VIOLATION);
1887 _wapi_handle_share_release (shareinfo);
1890 retval = _wapi_unlink (filename);
1893 _wapi_set_last_path_error_from_errno (NULL, filename);
1905 * @name: a pointer to a NULL-terminated unicode string, that names
1906 * the file to be moved.
1907 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1908 * new name for the file.
1910 * Renames file @name to @dest_name.
1911 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1912 * when it is the same file as the source. In that case it silently succeeds.
1914 * Return value: %TRUE on success, %FALSE otherwise.
1916 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1918 gchar *utf8_name, *utf8_dest_name;
1919 int result, errno_copy;
1920 struct stat stat_src, stat_dest;
1921 gboolean ret = FALSE;
1922 struct _WapiFileShare *shareinfo;
1925 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1927 SetLastError (ERROR_INVALID_NAME);
1931 utf8_name = mono_unicode_to_external (name);
1932 if (utf8_name == NULL) {
1933 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1935 SetLastError (ERROR_INVALID_NAME);
1939 if(dest_name==NULL) {
1940 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1943 SetLastError (ERROR_INVALID_NAME);
1947 utf8_dest_name = mono_unicode_to_external (dest_name);
1948 if (utf8_dest_name == NULL) {
1949 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1952 SetLastError (ERROR_INVALID_NAME);
1957 * In C# land we check for the existence of src, but not for dest.
1958 * We check it here and return the failure if dest exists and is not
1959 * the same file as src.
1961 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1962 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1963 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1965 g_free (utf8_dest_name);
1970 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1971 if (stat_dest.st_dev != stat_src.st_dev ||
1972 stat_dest.st_ino != stat_src.st_ino) {
1974 g_free (utf8_dest_name);
1975 SetLastError (ERROR_ALREADY_EXISTS);
1980 /* Check to make that we have delete sharing permission.
1981 * See https://bugzilla.xamarin.com/show_bug.cgi?id=17009
1983 * Do the checks that don't need an open file descriptor, for
1984 * simplicity's sake. If we really have to do the full checks
1985 * then we can implement that later.
1987 if (share_allows_delete (&stat_src, &shareinfo) == FALSE) {
1988 SetLastError (ERROR_SHARING_VIOLATION);
1992 _wapi_handle_share_release (shareinfo);
1994 result = _wapi_rename (utf8_name, utf8_dest_name);
1998 switch(errno_copy) {
2000 SetLastError (ERROR_ALREADY_EXISTS);
2004 /* Ignore here, it is dealt with below */
2008 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2013 g_free (utf8_dest_name);
2015 if (result != 0 && errno_copy == EXDEV) {
2016 if (S_ISDIR (stat_src.st_mode)) {
2017 SetLastError (ERROR_NOT_SAME_DEVICE);
2020 /* Try a copy to the new location, and delete the source */
2021 if (CopyFile (name, dest_name, TRUE)==FALSE) {
2022 /* CopyFile will set the error */
2026 return(DeleteFile (name));
2037 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
2041 int buf_size = st_src->st_blksize;
2043 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
2044 buf = (char *) malloc (buf_size);
2047 remain = read (src_fd, buf, buf_size);
2049 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
2053 _wapi_set_last_error_from_errno ();
2063 while (remain > 0) {
2064 if ((n = write (dest_fd, wbuf, remain)) < 0) {
2065 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
2069 _wapi_set_last_error_from_errno ();
2070 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write failed.", __func__);
2086 * @name: a pointer to a NULL-terminated unicode string, that names
2087 * the file to be copied.
2088 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
2089 * new name for the file.
2090 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
2092 * Copies file @name to @dest_name
2094 * Return value: %TRUE on success, %FALSE otherwise.
2096 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
2097 gboolean fail_if_exists)
2099 gchar *utf8_src, *utf8_dest;
2100 int src_fd, dest_fd;
2101 struct stat st, dest_st;
2102 struct utimbuf dest_time;
2103 gboolean ret = TRUE;
2107 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2109 SetLastError (ERROR_INVALID_NAME);
2113 utf8_src = mono_unicode_to_external (name);
2114 if (utf8_src == NULL) {
2115 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of source returned NULL",
2118 SetLastError (ERROR_INVALID_PARAMETER);
2122 if(dest_name==NULL) {
2123 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: dest is NULL", __func__);
2126 SetLastError (ERROR_INVALID_NAME);
2130 utf8_dest = mono_unicode_to_external (dest_name);
2131 if (utf8_dest == NULL) {
2132 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of dest returned NULL",
2135 SetLastError (ERROR_INVALID_PARAMETER);
2142 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2144 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2152 if (fstat (src_fd, &st) < 0) {
2153 _wapi_set_last_error_from_errno ();
2162 /* Before trying to open/create the dest, we need to report a 'file busy'
2163 * error if src and dest are actually the same file. We do the check here to take
2164 * advantage of the IOMAP capability */
2165 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
2166 st.st_ino == dest_st.st_ino) {
2172 SetLastError (ERROR_SHARING_VIOLATION);
2176 if (fail_if_exists) {
2177 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2179 /* FIXME: it kinda sucks that this code path potentially scans
2180 * the directory twice due to the weird SetLastError()
2182 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2184 /* The file does not exist, try creating it */
2185 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2187 /* Apparently this error is set if we
2188 * overwrite the dest file
2190 SetLastError (ERROR_ALREADY_EXISTS);
2194 _wapi_set_last_error_from_errno ();
2203 if (!write_file (src_fd, dest_fd, &st, TRUE))
2209 dest_time.modtime = st.st_mtime;
2210 dest_time.actime = st.st_atime;
2211 ret_utime = utime (utf8_dest, &dest_time);
2212 if (ret_utime == -1)
2213 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file [%s] utime failed: %s", __func__, utf8_dest, strerror(errno));
2222 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2227 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: %s is NULL", __func__, arg_name);
2228 SetLastError (ERROR_INVALID_NAME);
2232 utf8_ret = mono_unicode_to_external (arg);
2233 if (utf8_ret == NULL) {
2234 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of %s returned NULL",
2235 __func__, arg_name);
2236 SetLastError (ERROR_INVALID_PARAMETER);
2244 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2245 const gunichar2 *backupFileName, guint32 replaceFlags,
2246 gpointer exclude, gpointer reserved)
2248 int result, backup_fd = -1,replaced_fd = -1;
2249 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2250 struct stat stBackup;
2251 gboolean ret = FALSE;
2253 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2255 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2256 goto replace_cleanup;
2257 if (backupFileName != NULL) {
2258 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2259 goto replace_cleanup;
2262 if (utf8_backupFileName) {
2263 // Open the backup file for read so we can restore the file if an error occurs.
2264 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2265 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2267 goto replace_cleanup;
2270 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2272 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2273 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2274 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2275 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2278 if (replaced_fd == -1)
2279 goto replace_cleanup;
2281 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2284 goto replace_cleanup;
2290 g_free (utf8_replacedFileName);
2291 g_free (utf8_replacementFileName);
2292 g_free (utf8_backupFileName);
2293 if (backup_fd != -1)
2295 if (replaced_fd != -1)
2296 close (replaced_fd);
2302 * @stdhandle: specifies the file descriptor
2304 * Returns a handle for stdin, stdout, or stderr. Always returns the
2305 * same handle for the same @stdhandle.
2307 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2310 static mono_mutex_t stdhandle_mutex;
2312 gpointer GetStdHandle(WapiStdHandle stdhandle)
2314 struct _WapiHandle_file *file_handle;
2321 case STD_INPUT_HANDLE:
2326 case STD_OUTPUT_HANDLE:
2331 case STD_ERROR_HANDLE:
2337 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unknown standard handle type", __func__);
2339 SetLastError (ERROR_INVALID_PARAMETER);
2340 return(INVALID_HANDLE_VALUE);
2343 handle = GINT_TO_POINTER (fd);
2345 thr_ret = mono_os_mutex_lock (&stdhandle_mutex);
2346 g_assert (thr_ret == 0);
2348 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2349 (gpointer *)&file_handle);
2351 /* Need to create this console handle */
2352 handle = _wapi_stdhandle_create (fd, name);
2354 if (handle == INVALID_HANDLE_VALUE) {
2355 SetLastError (ERROR_NO_MORE_FILES);
2359 /* Add a reference to this handle */
2360 _wapi_handle_ref (handle);
2364 thr_ret = mono_os_mutex_unlock (&stdhandle_mutex);
2365 g_assert (thr_ret == 0);
2372 * @handle: The file handle to read from. The handle must have
2373 * %GENERIC_READ access.
2374 * @buffer: The buffer to store read data in
2375 * @numbytes: The maximum number of bytes to read
2376 * @bytesread: The actual number of bytes read is stored here. This
2377 * value can be zero if the handle is positioned at the end of the
2379 * @overlapped: points to a required %WapiOverlapped structure if
2380 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2383 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2384 * function reads up to @numbytes bytes from the file from the current
2385 * file position, and stores them in @buffer. If there are not enough
2386 * bytes left in the file, just the amount available will be read.
2387 * The actual number of bytes read is stored in @bytesread.
2389 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2390 * file position is ignored and the read position is taken from data
2391 * in the @overlapped structure.
2393 * Return value: %TRUE if the read succeeds (even if no bytes were
2394 * read due to an attempt to read past the end of the file), %FALSE on
2397 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2398 guint32 *bytesread, WapiOverlapped *overlapped)
2400 WapiHandleType type;
2402 type = _wapi_handle_type (handle);
2404 if(io_ops[type].readfile==NULL) {
2405 SetLastError (ERROR_INVALID_HANDLE);
2409 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2415 * @handle: The file handle to write to. The handle must have
2416 * %GENERIC_WRITE access.
2417 * @buffer: The buffer to read data from.
2418 * @numbytes: The maximum number of bytes to write.
2419 * @byteswritten: The actual number of bytes written is stored here.
2420 * If the handle is positioned at the file end, the length of the file
2421 * is extended. This parameter may be %NULL.
2422 * @overlapped: points to a required %WapiOverlapped structure if
2423 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2426 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2427 * function writes up to @numbytes bytes from @buffer to the file at
2428 * the current file position. If @handle is positioned at the end of
2429 * the file, the file is extended. The actual number of bytes written
2430 * is stored in @byteswritten.
2432 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2433 * file position is ignored and the write position is taken from data
2434 * in the @overlapped structure.
2436 * Return value: %TRUE if the write succeeds, %FALSE on error.
2438 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2439 guint32 *byteswritten, WapiOverlapped *overlapped)
2441 WapiHandleType type;
2443 type = _wapi_handle_type (handle);
2445 if(io_ops[type].writefile==NULL) {
2446 SetLastError (ERROR_INVALID_HANDLE);
2450 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2456 * @handle: Handle to open file. The handle must have
2457 * %GENERIC_WRITE access.
2459 * Flushes buffers of the file and causes all unwritten data to
2462 * Return value: %TRUE on success, %FALSE otherwise.
2464 gboolean FlushFileBuffers(gpointer handle)
2466 WapiHandleType type;
2468 type = _wapi_handle_type (handle);
2470 if(io_ops[type].flushfile==NULL) {
2471 SetLastError (ERROR_INVALID_HANDLE);
2475 return(io_ops[type].flushfile (handle));
2480 * @handle: The file handle to set. The handle must have
2481 * %GENERIC_WRITE access.
2483 * Moves the end-of-file position to the current position of the file
2484 * pointer. This function is used to truncate or extend a file.
2486 * Return value: %TRUE on success, %FALSE otherwise.
2488 gboolean SetEndOfFile(gpointer handle)
2490 WapiHandleType type;
2492 type = _wapi_handle_type (handle);
2494 if (io_ops[type].setendoffile == NULL) {
2495 SetLastError (ERROR_INVALID_HANDLE);
2499 return(io_ops[type].setendoffile (handle));
2504 * @handle: The file handle to set. The handle must have
2505 * %GENERIC_READ or %GENERIC_WRITE access.
2506 * @movedistance: Low 32 bits of a signed value that specifies the
2507 * number of bytes to move the file pointer.
2508 * @highmovedistance: Pointer to the high 32 bits of a signed value
2509 * that specifies the number of bytes to move the file pointer, or
2511 * @method: The starting point for the file pointer move.
2513 * Sets the file pointer of an open file.
2515 * The distance to move the file pointer is calculated from
2516 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2517 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2518 * is the low 32 bits and @highmovedistance a pointer to the high 32
2519 * bits of a 64 bit signed value. A positive distance moves the file
2520 * pointer forward from the position specified by @method; a negative
2521 * distance moves the file pointer backward.
2523 * If the library is compiled without large file support,
2524 * @highmovedistance is ignored and its value is set to zero on a
2525 * successful return.
2527 * Return value: On success, the low 32 bits of the new file pointer.
2528 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2529 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2531 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2532 gint32 *highmovedistance, WapiSeekMethod method)
2534 WapiHandleType type;
2536 type = _wapi_handle_type (handle);
2538 if (io_ops[type].seek == NULL) {
2539 SetLastError (ERROR_INVALID_HANDLE);
2540 return(INVALID_SET_FILE_POINTER);
2543 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2549 * @handle: The file handle to test.
2551 * Finds the type of file @handle.
2553 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2554 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2555 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2556 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2558 WapiFileType GetFileType(gpointer handle)
2560 WapiHandleType type;
2562 type = _wapi_handle_type (handle);
2564 if (io_ops[type].getfiletype == NULL) {
2565 SetLastError (ERROR_INVALID_HANDLE);
2566 return(FILE_TYPE_UNKNOWN);
2569 return(io_ops[type].getfiletype ());
2574 * @handle: The file handle to query. The handle must have
2575 * %GENERIC_READ or %GENERIC_WRITE access.
2576 * @highsize: If non-%NULL, the high 32 bits of the file size are
2579 * Retrieves the size of the file @handle.
2581 * If the library is compiled without large file support, @highsize
2582 * has its value set to zero on a successful return.
2584 * Return value: On success, the low 32 bits of the file size. If
2585 * @highsize is non-%NULL then the high 32 bits of the file size are
2586 * stored here. On failure %INVALID_FILE_SIZE is returned.
2588 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2590 WapiHandleType type;
2592 type = _wapi_handle_type (handle);
2594 if (io_ops[type].getfilesize == NULL) {
2595 SetLastError (ERROR_INVALID_HANDLE);
2596 return(INVALID_FILE_SIZE);
2599 return(io_ops[type].getfilesize (handle, highsize));
2604 * @handle: The file handle to query. The handle must have
2605 * %GENERIC_READ access.
2606 * @create_time: Points to a %WapiFileTime structure to receive the
2607 * number of ticks since the epoch that file was created. May be
2609 * @last_access: Points to a %WapiFileTime structure to receive the
2610 * number of ticks since the epoch when file was last accessed. May be
2612 * @last_write: Points to a %WapiFileTime structure to receive the
2613 * number of ticks since the epoch when file was last written to. May
2616 * Finds the number of ticks since the epoch that the file referenced
2617 * by @handle was created, last accessed and last modified. A tick is
2618 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2621 * Create time isn't recorded on POSIX file systems or reported by
2622 * stat(2), so that time is guessed by returning the oldest of the
2625 * Return value: %TRUE on success, %FALSE otherwise.
2627 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2628 WapiFileTime *last_access, WapiFileTime *last_write)
2630 WapiHandleType type;
2632 type = _wapi_handle_type (handle);
2634 if (io_ops[type].getfiletime == NULL) {
2635 SetLastError (ERROR_INVALID_HANDLE);
2639 return(io_ops[type].getfiletime (handle, create_time, last_access,
2645 * @handle: The file handle to set. The handle must have
2646 * %GENERIC_WRITE access.
2647 * @create_time: Points to a %WapiFileTime structure that contains the
2648 * number of ticks since the epoch that the file was created. May be
2650 * @last_access: Points to a %WapiFileTime structure that contains the
2651 * number of ticks since the epoch when the file was last accessed.
2653 * @last_write: Points to a %WapiFileTime structure that contains the
2654 * number of ticks since the epoch when the file was last written to.
2657 * Sets the number of ticks since the epoch that the file referenced
2658 * by @handle was created, last accessed or last modified. A tick is
2659 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2662 * Create time isn't recorded on POSIX file systems, and is ignored.
2664 * Return value: %TRUE on success, %FALSE otherwise.
2666 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2667 const WapiFileTime *last_access,
2668 const WapiFileTime *last_write)
2670 WapiHandleType type;
2672 type = _wapi_handle_type (handle);
2674 if (io_ops[type].setfiletime == NULL) {
2675 SetLastError (ERROR_INVALID_HANDLE);
2679 return(io_ops[type].setfiletime (handle, create_time, last_access,
2683 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2684 * January 1 1601 GMT
2687 #define TICKS_PER_MILLISECOND 10000L
2688 #define TICKS_PER_SECOND 10000000L
2689 #define TICKS_PER_MINUTE 600000000L
2690 #define TICKS_PER_HOUR 36000000000LL
2691 #define TICKS_PER_DAY 864000000000LL
2693 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2695 static const guint16 mon_yday[2][13]={
2696 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2697 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2701 * FileTimeToSystemTime:
2702 * @file_time: Points to a %WapiFileTime structure that contains the
2703 * number of ticks to convert.
2704 * @system_time: Points to a %WapiSystemTime structure to receive the
2707 * Converts a tick count into broken-out time values.
2709 * Return value: %TRUE on success, %FALSE otherwise.
2711 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2712 WapiSystemTime *system_time)
2714 gint64 file_ticks, totaldays, rem, y;
2717 if(system_time==NULL) {
2718 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: system_time NULL", __func__);
2720 SetLastError (ERROR_INVALID_PARAMETER);
2724 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2725 file_time->dwLowDateTime;
2727 /* Really compares if file_ticks>=0x8000000000000000
2728 * (LLONG_MAX+1) but we're working with a signed value for the
2729 * year and day calculation to work later
2732 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file_time too big", __func__);
2734 SetLastError (ERROR_INVALID_PARAMETER);
2738 totaldays=(file_ticks / TICKS_PER_DAY);
2739 rem = file_ticks % TICKS_PER_DAY;
2740 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2742 system_time->wHour=rem/TICKS_PER_HOUR;
2743 rem %= TICKS_PER_HOUR;
2744 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2746 system_time->wMinute = rem / TICKS_PER_MINUTE;
2747 rem %= TICKS_PER_MINUTE;
2748 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2751 system_time->wSecond = rem / TICKS_PER_SECOND;
2752 rem %= TICKS_PER_SECOND;
2753 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2756 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2757 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Milliseconds: %d", __func__,
2758 system_time->wMilliseconds);
2760 /* January 1, 1601 was a Monday, according to Emacs calendar */
2761 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2762 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2764 /* This algorithm to find year and month given days from epoch
2769 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2770 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2772 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2773 /* Guess a corrected year, assuming 365 days per year */
2774 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2775 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld yg: %lld y: %lld", __func__,
2778 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2779 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2781 /* Adjust days and y to match the guessed year. */
2782 totaldays -= ((yg - y) * 365
2783 + LEAPS_THRU_END_OF (yg - 1)
2784 - LEAPS_THRU_END_OF (y - 1));
2785 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2787 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: y: %lld", __func__, y);
2790 system_time->wYear = y;
2791 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Year: %d", __func__, system_time->wYear);
2793 ip = mon_yday[isleap(y)];
2795 for(y=11; totaldays < ip[y]; --y) {
2799 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2801 system_time->wMonth = y + 1;
2802 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Month: %d", __func__, system_time->wMonth);
2804 system_time->wDay = totaldays + 1;
2805 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day: %d", __func__, system_time->wDay);
2810 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2812 struct _WapiHandle_find find_handle = {0};
2814 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2817 if (pattern == NULL) {
2818 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: pattern is NULL", __func__);
2820 SetLastError (ERROR_PATH_NOT_FOUND);
2821 return(INVALID_HANDLE_VALUE);
2824 utf8_pattern = mono_unicode_to_external (pattern);
2825 if (utf8_pattern == NULL) {
2826 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2828 SetLastError (ERROR_INVALID_NAME);
2829 return(INVALID_HANDLE_VALUE);
2832 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for [%s]", __func__, utf8_pattern);
2834 /* Figure out which bit of the pattern is the directory */
2835 dir_part = _wapi_dirname (utf8_pattern);
2836 entry_part = _wapi_basename (utf8_pattern);
2839 /* Don't do this check for now, it breaks if directories
2840 * really do have metachars in their names (see bug 58116).
2841 * FIXME: Figure out a better solution to keep some checks...
2843 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2844 SetLastError (ERROR_INVALID_NAME);
2846 g_free (entry_part);
2847 g_free (utf8_pattern);
2848 return(INVALID_HANDLE_VALUE);
2852 /* The pattern can specify a directory or a set of files.
2854 * The pattern can have wildcard characters ? and *, but only
2855 * in the section after the last directory delimiter. (Return
2856 * ERROR_INVALID_NAME if there are wildcards in earlier path
2857 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2858 * means "match one character", "??" seems to mean "match one
2859 * or two characters", "???" seems to mean "match one, two or
2860 * three characters", etc. Windows will also try and match
2861 * the mangled "short name" of files, so 8 character patterns
2862 * with wildcards will show some surprising results.
2864 * All the written documentation I can find says that '?'
2865 * should only match one character, and doesn't mention '??',
2866 * '???' etc. I'm going to assume that the strict behaviour
2867 * (ie '???' means three and only three characters) is the
2868 * correct one, because that lets me use fnmatch(3) rather
2869 * than mess around with regexes.
2872 find_handle.namelist = NULL;
2873 result = _wapi_io_scandir (dir_part, entry_part,
2874 &find_handle.namelist);
2877 /* No files, which windows seems to call
2880 SetLastError (ERROR_FILE_NOT_FOUND);
2881 g_free (utf8_pattern);
2882 g_free (entry_part);
2884 return (INVALID_HANDLE_VALUE);
2888 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2889 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: scandir error: %s", __func__, g_strerror (errno));
2890 g_free (utf8_pattern);
2891 g_free (entry_part);
2893 return (INVALID_HANDLE_VALUE);
2896 g_free (utf8_pattern);
2897 g_free (entry_part);
2899 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Got %d matches", __func__, result);
2901 find_handle.dir_part = dir_part;
2902 find_handle.num = result;
2903 find_handle.count = 0;
2905 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2906 if (handle == _WAPI_HANDLE_INVALID) {
2907 g_warning ("%s: error creating find handle", __func__);
2909 g_free (entry_part);
2910 g_free (utf8_pattern);
2911 SetLastError (ERROR_GEN_FAILURE);
2913 return(INVALID_HANDLE_VALUE);
2916 if (handle != INVALID_HANDLE_VALUE &&
2917 !FindNextFile (handle, find_data)) {
2919 SetLastError (ERROR_NO_MORE_FILES);
2920 handle = INVALID_HANDLE_VALUE;
2926 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2928 struct _WapiHandle_find *find_handle;
2930 struct stat buf, linkbuf;
2933 gchar *utf8_filename, *utf8_basename;
2934 gunichar2 *utf16_basename;
2938 gboolean ret = FALSE;
2940 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2941 (gpointer *)&find_handle);
2943 g_warning ("%s: error looking up find handle %p", __func__,
2945 SetLastError (ERROR_INVALID_HANDLE);
2949 thr_ret = _wapi_handle_lock_handle (handle);
2950 g_assert (thr_ret == 0);
2953 if (find_handle->count >= find_handle->num) {
2954 SetLastError (ERROR_NO_MORE_FILES);
2958 /* stat next match */
2960 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2962 result = _wapi_stat (filename, &buf);
2963 if (result == -1 && errno == ENOENT) {
2964 /* Might be a dangling symlink */
2965 result = _wapi_lstat (filename, &buf);
2969 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: stat failed: %s", __func__, filename);
2975 #ifndef __native_client__
2976 result = _wapi_lstat (filename, &linkbuf);
2978 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lstat failed: %s", __func__, filename);
2985 utf8_filename = mono_utf8_from_external (filename);
2986 if (utf8_filename == NULL) {
2987 /* We couldn't turn this filename into utf8 (eg the
2988 * encoding of the name wasn't convertible), so just
2991 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2998 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Found [%s]", __func__, utf8_filename);
3000 /* fill data block */
3002 if (buf.st_mtime < buf.st_ctime)
3003 create_time = buf.st_mtime;
3005 create_time = buf.st_ctime;
3007 #ifdef __native_client__
3008 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, NULL);
3010 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
3013 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
3014 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
3015 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
3017 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3018 find_data->nFileSizeHigh = 0;
3019 find_data->nFileSizeLow = 0;
3021 find_data->nFileSizeHigh = buf.st_size >> 32;
3022 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3025 find_data->dwReserved0 = 0;
3026 find_data->dwReserved1 = 0;
3028 utf8_basename = _wapi_basename (utf8_filename);
3029 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
3031 if(utf16_basename==NULL) {
3032 g_free (utf8_basename);
3033 g_free (utf8_filename);
3038 /* utf16 is 2 * utf8 */
3041 memset (find_data->cFileName, '\0', (MAX_PATH*2));
3043 /* Truncating a utf16 string like this might leave the last
3046 memcpy (find_data->cFileName, utf16_basename,
3047 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3049 find_data->cAlternateFileName [0] = 0; /* not used */
3051 g_free (utf8_basename);
3052 g_free (utf8_filename);
3053 g_free (utf16_basename);
3056 thr_ret = _wapi_handle_unlock_handle (handle);
3057 g_assert (thr_ret == 0);
3064 * @wapi_handle: the find handle to close.
3066 * Closes find handle @wapi_handle
3068 * Return value: %TRUE on success, %FALSE otherwise.
3070 gboolean FindClose (gpointer handle)
3072 struct _WapiHandle_find *find_handle;
3076 if (handle == NULL) {
3077 SetLastError (ERROR_INVALID_HANDLE);
3081 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
3082 (gpointer *)&find_handle);
3084 g_warning ("%s: error looking up find handle %p", __func__,
3086 SetLastError (ERROR_INVALID_HANDLE);
3090 thr_ret = _wapi_handle_lock_handle (handle);
3091 g_assert (thr_ret == 0);
3093 g_strfreev (find_handle->namelist);
3094 g_free (find_handle->dir_part);
3096 thr_ret = _wapi_handle_unlock_handle (handle);
3097 g_assert (thr_ret == 0);
3099 _wapi_handle_unref (handle);
3106 * @name: a pointer to a NULL-terminated unicode string, that names
3107 * the directory to be created.
3108 * @security: ignored for now
3110 * Creates directory @name
3112 * Return value: %TRUE on success, %FALSE otherwise.
3114 gboolean CreateDirectory (const gunichar2 *name,
3115 WapiSecurityAttributes *security)
3121 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3123 SetLastError (ERROR_INVALID_NAME);
3127 utf8_name = mono_unicode_to_external (name);
3128 if (utf8_name == NULL) {
3129 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3131 SetLastError (ERROR_INVALID_NAME);
3135 result = _wapi_mkdir (utf8_name, 0777);
3142 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3149 * @name: a pointer to a NULL-terminated unicode string, that names
3150 * the directory to be removed.
3152 * Removes directory @name
3154 * Return value: %TRUE on success, %FALSE otherwise.
3156 gboolean RemoveDirectory (const gunichar2 *name)
3162 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3164 SetLastError (ERROR_INVALID_NAME);
3168 utf8_name = mono_unicode_to_external (name);
3169 if (utf8_name == NULL) {
3170 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3172 SetLastError (ERROR_INVALID_NAME);
3176 result = _wapi_rmdir (utf8_name);
3178 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3189 * GetFileAttributes:
3190 * @name: a pointer to a NULL-terminated unicode filename.
3192 * Gets the attributes for @name;
3194 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3196 guint32 GetFileAttributes (const gunichar2 *name)
3199 struct stat buf, linkbuf;
3204 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3206 SetLastError (ERROR_INVALID_NAME);
3210 utf8_name = mono_unicode_to_external (name);
3211 if (utf8_name == NULL) {
3212 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3214 SetLastError (ERROR_INVALID_PARAMETER);
3215 return (INVALID_FILE_ATTRIBUTES);
3218 result = _wapi_stat (utf8_name, &buf);
3219 if (result == -1 && errno == ENOENT) {
3220 /* Might be a dangling symlink... */
3221 result = _wapi_lstat (utf8_name, &buf);
3225 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3227 return (INVALID_FILE_ATTRIBUTES);
3230 #ifndef __native_client__
3231 result = _wapi_lstat (utf8_name, &linkbuf);
3233 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3235 return (INVALID_FILE_ATTRIBUTES);
3239 #ifdef __native_client__
3240 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, NULL);
3242 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3251 * GetFileAttributesEx:
3252 * @name: a pointer to a NULL-terminated unicode filename.
3253 * @level: must be GetFileExInfoStandard
3254 * @info: pointer to a WapiFileAttributesData structure
3256 * Gets attributes, size and filetimes for @name;
3258 * Return value: %TRUE on success, %FALSE on failure
3260 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3263 WapiFileAttributesData *data;
3265 struct stat buf, linkbuf;
3269 if (level != GetFileExInfoStandard) {
3270 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: info level %d not supported.", __func__,
3273 SetLastError (ERROR_INVALID_PARAMETER);
3278 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3280 SetLastError (ERROR_INVALID_NAME);
3284 utf8_name = mono_unicode_to_external (name);
3285 if (utf8_name == NULL) {
3286 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3288 SetLastError (ERROR_INVALID_PARAMETER);
3292 result = _wapi_stat (utf8_name, &buf);
3293 if (result == -1 && errno == ENOENT) {
3294 /* Might be a dangling symlink... */
3295 result = _wapi_lstat (utf8_name, &buf);
3299 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3304 result = _wapi_lstat (utf8_name, &linkbuf);
3306 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3311 /* fill data block */
3313 data = (WapiFileAttributesData *)info;
3315 if (buf.st_mtime < buf.st_ctime)
3316 create_time = buf.st_mtime;
3318 create_time = buf.st_ctime;
3320 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3326 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3327 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3328 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3330 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3331 data->nFileSizeHigh = 0;
3332 data->nFileSizeLow = 0;
3335 data->nFileSizeHigh = buf.st_size >> 32;
3336 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3344 * @name: name of file
3345 * @attrs: attributes to set
3347 * Changes the attributes on a named file.
3349 * Return value: %TRUE on success, %FALSE on failure.
3351 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3353 /* FIXME: think of something clever to do on unix */
3359 * Currently we only handle one *internal* case, with a value that is
3360 * not standard: 0x80000000, which means `set executable bit'
3364 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3366 SetLastError (ERROR_INVALID_NAME);
3370 utf8_name = mono_unicode_to_external (name);
3371 if (utf8_name == NULL) {
3372 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3374 SetLastError (ERROR_INVALID_NAME);
3378 result = _wapi_stat (utf8_name, &buf);
3379 if (result == -1 && errno == ENOENT) {
3380 /* Might be a dangling symlink... */
3381 result = _wapi_lstat (utf8_name, &buf);
3385 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3390 /* Contrary to the documentation, ms allows NORMAL to be
3391 * specified along with other attributes, so dont bother to
3392 * catch that case here.
3394 if (attrs & FILE_ATTRIBUTE_READONLY) {
3395 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWUSR | S_IWOTH | S_IWGRP));
3397 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWUSR);
3400 /* Ignore the other attributes for now */
3402 if (attrs & 0x80000000){
3403 mode_t exec_mask = 0;
3405 if ((buf.st_mode & S_IRUSR) != 0)
3406 exec_mask |= S_IXUSR;
3408 if ((buf.st_mode & S_IRGRP) != 0)
3409 exec_mask |= S_IXGRP;
3411 if ((buf.st_mode & S_IROTH) != 0)
3412 exec_mask |= S_IXOTH;
3414 result = chmod (utf8_name, buf.st_mode | exec_mask);
3416 /* Don't bother to reset executable (might need to change this
3426 * GetCurrentDirectory
3427 * @length: size of the buffer
3428 * @buffer: pointer to buffer that recieves path
3430 * Retrieves the current directory for the current process.
3432 * Return value: number of characters in buffer on success, zero on failure
3434 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3436 gunichar2 *utf16_path;
3440 #ifdef __native_client__
3441 gchar *path = g_get_current_dir ();
3442 if (length < strlen(path) + 1 || path == NULL)
3444 memcpy (buffer, path, strlen(path) + 1);
3446 if (getcwd ((char*)buffer, length) == NULL) {
3447 if (errno == ERANGE) { /*buffer length is not big enough */
3448 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*/
3451 utf16_path = mono_unicode_from_external (path, &bytes);
3452 g_free (utf16_path);
3456 _wapi_set_last_error_from_errno ();
3461 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3462 count = (bytes/2)+1;
3463 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3465 /* Add the terminator */
3466 memset (buffer, '\0', bytes+2);
3467 memcpy (buffer, utf16_path, bytes);
3469 g_free (utf16_path);
3475 * SetCurrentDirectory
3476 * @path: path to new directory
3478 * Changes the directory path for the current process.
3480 * Return value: %TRUE on success, %FALSE on failure.
3482 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3488 SetLastError (ERROR_INVALID_PARAMETER);
3492 utf8_path = mono_unicode_to_external (path);
3493 if (_wapi_chdir (utf8_path) != 0) {
3494 _wapi_set_last_error_from_errno ();
3504 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3505 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3507 struct _WapiHandle_file pipe_read_handle = {0};
3508 struct _WapiHandle_file pipe_write_handle = {0};
3509 gpointer read_handle;
3510 gpointer write_handle;
3514 mono_once (&io_ops_once, io_ops_init);
3516 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Creating pipe", __func__);
3520 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error creating pipe: %s", __func__,
3523 _wapi_set_last_error_from_errno ();
3527 if (filedes[0] >= _wapi_fd_reserve ||
3528 filedes[1] >= _wapi_fd_reserve) {
3529 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
3531 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3539 /* filedes[0] is open for reading, filedes[1] for writing */
3541 pipe_read_handle.fd = filedes [0];
3542 pipe_read_handle.fileaccess = GENERIC_READ;
3543 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3545 if (read_handle == _WAPI_HANDLE_INVALID) {
3546 g_warning ("%s: error creating pipe read handle", __func__);
3549 SetLastError (ERROR_GEN_FAILURE);
3554 pipe_write_handle.fd = filedes [1];
3555 pipe_write_handle.fileaccess = GENERIC_WRITE;
3556 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3557 &pipe_write_handle);
3558 if (write_handle == _WAPI_HANDLE_INVALID) {
3559 g_warning ("%s: error creating pipe write handle", __func__);
3560 _wapi_handle_unref (read_handle);
3564 SetLastError (ERROR_GEN_FAILURE);
3569 *readpipe = read_handle;
3570 *writepipe = write_handle;
3572 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning pipe: read handle %p, write handle %p",
3573 __func__, read_handle, write_handle);
3578 #ifdef HAVE_GETFSSTAT
3579 /* Darwin has getfsstat */
3580 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3582 struct statfs *stats;
3585 glong length, total = 0;
3587 n = getfsstat (NULL, 0, MNT_NOWAIT);
3590 size = n * sizeof (struct statfs);
3591 stats = (struct statfs *) g_malloc (size);
3594 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3598 for (i = 0; i < n; i++){
3599 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3600 if (total + length < len){
3601 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3602 buf [total+length] = 0;
3605 total += length + 1;
3614 /* In-place octal sequence replacement */
3616 unescape_octal (gchar *str)
3625 while (*rptr != '\0') {
3626 if (*rptr == '\\') {
3629 c = (*(rptr++) - '0') << 6;
3630 c += (*(rptr++) - '0') << 3;
3631 c += *(rptr++) - '0';
3633 } else if (wptr != rptr) {
3641 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3644 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3645 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3646 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3651 guint32 buffer_index;
3652 guint32 mountpoint_index;
3653 guint32 field_number;
3654 guint32 allocated_size;
3655 guint32 fsname_index;
3656 guint32 fstype_index;
3657 gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3658 gchar *mountpoint_allocated;
3659 gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3660 gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3661 gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3664 gboolean check_mount_source;
3665 } LinuxMountInfoParseState;
3667 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3668 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3669 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3670 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3672 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3676 LinuxMountInfoParseState state;
3677 gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3679 memset (buf, 0, len * sizeof (gunichar2));
3680 fd = open ("/proc/self/mountinfo", O_RDONLY);
3682 parser = GetLogicalDriveStrings_MountInfo;
3684 fd = open ("/proc/mounts", O_RDONLY);
3686 parser = GetLogicalDriveStrings_Mounts;
3690 ret = GetLogicalDriveStrings_Mtab (len, buf);
3694 memset (&state, 0, sizeof (LinuxMountInfoParseState));
3695 state.field_number = 1;
3696 state.delimiter = ' ';
3698 while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3699 state.buffer_index = 0;
3701 while ((*parser)(len, buf, &state)) {
3702 if (state.buffer [state.buffer_index] == '\n') {
3703 gboolean quit = add_drive_string (len, buf, &state);
3704 state.field_number = 1;
3705 state.buffer_index++;
3706 if (state.mountpoint_allocated) {
3707 g_free (state.mountpoint_allocated);
3708 state.mountpoint_allocated = NULL;
3725 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3729 if (state->field_number == 1)
3730 state->check_mount_source = TRUE;
3732 while (state->buffer_index < (guint32)state->nbytes) {
3733 if (state->buffer [state->buffer_index] == state->delimiter) {
3734 state->field_number++;
3735 switch (state->field_number) {
3737 state->mountpoint_index = 0;
3741 if (state->mountpoint_allocated)
3742 state->mountpoint_allocated [state->mountpoint_index] = 0;
3744 state->mountpoint [state->mountpoint_index] = 0;
3748 ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3750 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3752 state->buffer_index = state->nbytes;
3755 state->buffer_index++;
3757 } else if (state->buffer [state->buffer_index] == '\n')
3760 switch (state->field_number) {
3762 if (state->check_mount_source) {
3763 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3764 /* We can ignore the rest, it's a device
3766 state->check_mount_source = FALSE;
3767 state->fsname [state->fsname_index++] = '/';
3770 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3771 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3776 append_to_mountpoint (state);
3780 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3781 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3785 state->buffer_index++;
3791 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3793 while (state->buffer_index < (guint32)state->nbytes) {
3794 if (state->buffer [state->buffer_index] == state->delimiter) {
3795 state->field_number++;
3796 switch (state->field_number) {
3798 state->mountpoint_index = 0;
3802 if (state->mountpoint_allocated)
3803 state->mountpoint_allocated [state->mountpoint_index] = 0;
3805 state->mountpoint [state->mountpoint_index] = 0;
3809 state->delimiter = '-';
3813 state->delimiter = ' ';
3817 state->check_mount_source = TRUE;
3820 state->buffer_index++;
3822 } else if (state->buffer [state->buffer_index] == '\n')
3825 switch (state->field_number) {
3827 append_to_mountpoint (state);
3831 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3832 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3836 if (state->check_mount_source) {
3837 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3838 /* We can ignore the rest, it's a device
3840 state->check_mount_source = FALSE;
3841 state->fsname [state->fsname_index++] = '/';
3844 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3845 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3850 state->buffer_index++;
3857 append_to_mountpoint (LinuxMountInfoParseState *state)
3859 gchar ch = state->buffer [state->buffer_index];
3860 if (state->mountpoint_allocated) {
3861 if (state->mountpoint_index >= state->allocated_size) {
3862 guint32 newsize = (state->allocated_size << 1) + 1;
3863 gchar *newbuf = (gchar *)g_malloc0 (newsize * sizeof (gchar));
3865 memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3866 g_free (state->mountpoint_allocated);
3867 state->mountpoint_allocated = newbuf;
3868 state->allocated_size = newsize;
3870 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3872 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3873 state->allocated_size = (state->mountpoint_index << 1) + 1;
3874 state->mountpoint_allocated = (gchar *)g_malloc0 (state->allocated_size * sizeof (gchar));
3875 memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3876 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3878 state->mountpoint [state->mountpoint_index++] = ch;
3883 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3885 gboolean quit = FALSE;
3886 gboolean ignore_entry;
3888 if (state->fsname_index == 1 && state->fsname [0] == '/')
3889 ignore_entry = FALSE;
3890 else if (memcmp ("overlay", state->fsname, state->fsname_index) == 0 ||
3891 memcmp ("aufs", state->fstype, state->fstype_index) == 0) {
3892 /* Don't ignore overlayfs and aufs - these might be used on Docker
3893 * (https://bugzilla.xamarin.com/show_bug.cgi?id=31021) */
3894 ignore_entry = FALSE;
3895 } else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0) {
3896 ignore_entry = TRUE;
3897 } else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3898 /* Ignore GNOME's gvfs */
3899 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3900 ignore_entry = TRUE;
3902 ignore_entry = FALSE;
3903 } else if (state->fstype_index == 3 && memcmp ("nfs", state->fstype, state->fstype_index) == 0)
3904 ignore_entry = FALSE;
3906 ignore_entry = TRUE;
3908 if (!ignore_entry) {
3911 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3913 unescape_octal (mountpoint);
3914 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3915 if (state->total + length + 1 > len) {
3917 state->total = len * 2;
3920 memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3921 state->total += length;
3925 state->fsname_index = 0;
3926 state->fstype_index = 0;
3932 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3934 return GetLogicalDriveStrings_Mtab (len, buf);
3938 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3941 gunichar2 *ptr, *dir;
3942 glong length, total = 0;
3946 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3951 /* Sigh, mntent and friends don't work well.
3952 * It stops on the first line that doesn't begin with a '/'.
3953 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3954 fp = fopen ("/etc/mtab", "rt");
3956 fp = fopen ("/etc/mnttab", "rt");
3962 while (fgets (buffer, 512, fp) != NULL) {
3966 splitted = g_strsplit (buffer, " ", 0);
3967 if (!*splitted || !*(splitted + 1)) {
3968 g_strfreev (splitted);
3972 unescape_octal (*(splitted + 1));
3973 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3974 g_strfreev (splitted);
3975 if (total + length + 1 > len) {
3978 return len * 2; /* guess */
3981 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3983 total += length + 1;
3988 /* Commented out, does not work with my mtab!!! - Gonz */
3989 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3993 gunichar2 *ptr, *dir;
3994 glong len, total = 0;
3997 fp = setmntent ("/etc/mtab", "rt");
3999 fp = setmntent ("/etc/mnttab", "rt");
4005 while ((mnt = getmntent (fp)) != NULL) {
4006 g_print ("GOT %s\n", mnt->mnt_dir);
4007 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
4008 if (total + len + 1 > len) {
4009 return len * 2; /* guess */
4012 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
4024 #if defined(HAVE_STATVFS) || defined(HAVE_STATFS)
4025 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4026 WapiULargeInteger *total_number_of_bytes,
4027 WapiULargeInteger *total_number_of_free_bytes)
4030 struct statvfs fsstat;
4031 #elif defined(HAVE_STATFS)
4032 struct statfs fsstat;
4034 gboolean isreadonly;
4035 gchar *utf8_path_name;
4037 unsigned long block_size;
4039 if (path_name == NULL) {
4040 utf8_path_name = g_strdup (g_get_current_dir());
4041 if (utf8_path_name == NULL) {
4042 SetLastError (ERROR_DIRECTORY);
4047 utf8_path_name = mono_unicode_to_external (path_name);
4048 if (utf8_path_name == NULL) {
4049 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4051 SetLastError (ERROR_INVALID_NAME);
4058 ret = statvfs (utf8_path_name, &fsstat);
4059 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
4060 block_size = fsstat.f_frsize;
4061 #elif defined(HAVE_STATFS)
4062 ret = statfs (utf8_path_name, &fsstat);
4063 #if defined (MNT_RDONLY)
4064 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
4065 #elif defined (MS_RDONLY)
4066 isreadonly = ((fsstat.f_flags & MS_RDONLY) == MS_RDONLY);
4068 block_size = fsstat.f_bsize;
4070 } while(ret == -1 && errno == EINTR);
4072 g_free(utf8_path_name);
4075 _wapi_set_last_error_from_errno ();
4076 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: statvfs failed: %s", __func__, strerror (errno));
4080 /* total number of free bytes for non-root */
4081 if (free_bytes_avail != NULL) {
4083 free_bytes_avail->QuadPart = 0;
4086 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
4090 /* total number of bytes available for non-root */
4091 if (total_number_of_bytes != NULL) {
4092 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
4095 /* total number of bytes available for root */
4096 if (total_number_of_free_bytes != NULL) {
4098 total_number_of_free_bytes->QuadPart = 0;
4101 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
4108 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4109 WapiULargeInteger *total_number_of_bytes,
4110 WapiULargeInteger *total_number_of_free_bytes)
4112 if (free_bytes_avail != NULL) {
4113 free_bytes_avail->QuadPart = (guint64) -1;
4116 if (total_number_of_bytes != NULL) {
4117 total_number_of_bytes->QuadPart = (guint64) -1;
4120 if (total_number_of_free_bytes != NULL) {
4121 total_number_of_free_bytes->QuadPart = (guint64) -1;
4129 * General Unix support
4134 const long fstypeid;
4136 const gchar* fstype;
4139 static _wapi_drive_type _wapi_drive_types[] = {
4141 { DRIVE_REMOTE, "afp" },
4142 { DRIVE_REMOTE, "autofs" },
4143 { DRIVE_CDROM, "cddafs" },
4144 { DRIVE_CDROM, "cd9660" },
4145 { DRIVE_RAMDISK, "devfs" },
4146 { DRIVE_FIXED, "exfat" },
4147 { DRIVE_RAMDISK, "fdesc" },
4148 { DRIVE_REMOTE, "ftp" },
4149 { DRIVE_FIXED, "hfs" },
4150 { DRIVE_FIXED, "msdos" },
4151 { DRIVE_REMOTE, "nfs" },
4152 { DRIVE_FIXED, "ntfs" },
4153 { DRIVE_REMOTE, "smbfs" },
4154 { DRIVE_FIXED, "udf" },
4155 { DRIVE_REMOTE, "webdav" },
4156 { DRIVE_UNKNOWN, NULL }
4158 { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
4159 { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
4160 { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
4161 { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
4162 { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
4163 { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
4164 { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
4165 { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
4166 { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
4167 { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
4168 { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
4169 { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
4170 { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
4171 { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
4172 { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
4173 { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
4174 { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
4175 { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4176 { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4177 { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4178 { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4179 { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4180 { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4181 { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4182 { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4183 { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4184 { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4185 { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4186 { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4187 { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4188 { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4189 { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4190 { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4191 { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4192 { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4193 { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4194 { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4195 { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4196 { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4197 { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4198 { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4199 { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4200 { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4201 { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4202 { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4203 { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4204 { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4205 { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4206 { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4207 { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4208 { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4209 { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4210 { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4211 { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4212 { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4213 { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4214 { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4215 { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4216 { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4217 { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4218 { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4219 { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4220 { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4221 { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4222 { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4223 { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4224 { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4225 { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4226 { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4227 { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4228 { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4229 { DRIVE_UNKNOWN, 0, NULL}
4231 { DRIVE_RAMDISK, "ramfs" },
4232 { DRIVE_RAMDISK, "tmpfs" },
4233 { DRIVE_RAMDISK, "proc" },
4234 { DRIVE_RAMDISK, "sysfs" },
4235 { DRIVE_RAMDISK, "debugfs" },
4236 { DRIVE_RAMDISK, "devpts" },
4237 { DRIVE_RAMDISK, "securityfs" },
4238 { DRIVE_CDROM, "iso9660" },
4239 { DRIVE_FIXED, "ext2" },
4240 { DRIVE_FIXED, "ext3" },
4241 { DRIVE_FIXED, "ext4" },
4242 { DRIVE_FIXED, "sysv" },
4243 { DRIVE_FIXED, "reiserfs" },
4244 { DRIVE_FIXED, "ufs" },
4245 { DRIVE_FIXED, "vfat" },
4246 { DRIVE_FIXED, "msdos" },
4247 { DRIVE_FIXED, "udf" },
4248 { DRIVE_FIXED, "hfs" },
4249 { DRIVE_FIXED, "hpfs" },
4250 { DRIVE_FIXED, "qnx4" },
4251 { DRIVE_FIXED, "ntfs" },
4252 { DRIVE_FIXED, "ntfs-3g" },
4253 { DRIVE_REMOTE, "smbfs" },
4254 { DRIVE_REMOTE, "fuse" },
4255 { DRIVE_REMOTE, "nfs" },
4256 { DRIVE_REMOTE, "nfs4" },
4257 { DRIVE_REMOTE, "cifs" },
4258 { DRIVE_REMOTE, "ncpfs" },
4259 { DRIVE_REMOTE, "coda" },
4260 { DRIVE_REMOTE, "afs" },
4261 { DRIVE_UNKNOWN, NULL }
4266 static guint32 _wapi_get_drive_type(long f_type)
4268 _wapi_drive_type *current;
4270 current = &_wapi_drive_types[0];
4271 while (current->drive_type != DRIVE_UNKNOWN) {
4272 if (current->fstypeid == f_type)
4273 return current->drive_type;
4277 return DRIVE_UNKNOWN;
4280 static guint32 _wapi_get_drive_type(const gchar* fstype)
4282 _wapi_drive_type *current;
4284 current = &_wapi_drive_types[0];
4285 while (current->drive_type != DRIVE_UNKNOWN) {
4286 if (strcmp (current->fstype, fstype) == 0)
4292 return current->drive_type;
4296 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4298 GetDriveTypeFromPath (const char *utf8_root_path_name)
4302 if (statfs (utf8_root_path_name, &buf) == -1)
4303 return DRIVE_UNKNOWN;
4305 return _wapi_get_drive_type (buf.f_fstypename);
4307 return _wapi_get_drive_type (buf.f_type);
4312 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4319 fp = fopen ("/etc/mtab", "rt");
4321 fp = fopen ("/etc/mnttab", "rt");
4323 return(DRIVE_UNKNOWN);
4326 drive_type = DRIVE_NO_ROOT_DIR;
4327 while (fgets (buffer, 512, fp) != NULL) {
4328 splitted = g_strsplit (buffer, " ", 0);
4329 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4330 g_strfreev (splitted);
4334 /* compare given root_path_name with the one from mtab,
4335 if length of utf8_root_path_name is zero it must be the root dir */
4336 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4337 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4338 drive_type = _wapi_get_drive_type (*(splitted + 2));
4339 /* it is possible this path might be mounted again with
4340 a known type...keep looking */
4341 if (drive_type != DRIVE_UNKNOWN) {
4342 g_strfreev (splitted);
4347 g_strfreev (splitted);
4355 guint32 GetDriveType(const gunichar2 *root_path_name)
4357 gchar *utf8_root_path_name;
4360 if (root_path_name == NULL) {
4361 utf8_root_path_name = g_strdup (g_get_current_dir());
4362 if (utf8_root_path_name == NULL) {
4363 return(DRIVE_NO_ROOT_DIR);
4367 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4368 if (utf8_root_path_name == NULL) {
4369 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4370 return(DRIVE_NO_ROOT_DIR);
4373 /* strip trailing slash for compare below */
4374 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4375 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4378 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4379 g_free (utf8_root_path_name);
4381 return (drive_type);
4384 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__) || defined(__FreeBSD_kernel__)
4386 get_fstypename (gchar *utfpath)
4388 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4391 _wapi_drive_type *current;
4393 if (statfs (utfpath, &stat) == -1)
4396 return g_strdup (stat.f_fstypename);
4398 current = &_wapi_drive_types[0];
4399 while (current->drive_type != DRIVE_UNKNOWN) {
4400 if (stat.f_type == current->fstypeid)
4401 return g_strdup (current->fstype);
4411 /* Linux has struct statfs which has a different layout */
4413 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4417 gboolean status = FALSE;
4420 // We only support getting the file system type
4421 if (fsbuffer == NULL)
4424 utfpath = mono_unicode_to_external (path);
4425 if ((fstypename = get_fstypename (utfpath)) != NULL){
4426 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4427 if (ret != NULL && len < fsbuffersize){
4428 memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4434 g_free (fstypename);
4443 _wapi_io_init (void)
4445 mono_os_mutex_init (&stdhandle_mutex);
4449 _wapi_io_cleanup (void)
4451 if (file_share_hash) {
4452 g_hash_table_destroy (file_share_hash);
4453 mono_os_mutex_destroy (&file_share_hash_mutex);