2 * io.c: File, console and find handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002 Ximian, Inc.
8 * Copyright (c) 2002-2006 Novell, Inc.
9 * Copyright 2011 Xamarin Inc (http://www.xamarin.com).
10 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
20 #ifdef HAVE_SYS_STATVFS_H
21 #include <sys/statvfs.h>
23 #if defined(HAVE_SYS_STATFS_H)
24 #include <sys/statfs.h>
26 #if defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H)
27 #include <sys/param.h>
28 #include <sys/mount.h>
30 #include <sys/types.h>
34 #include <sys/ioctl.h>
36 #include <mono/utils/linux_magic.h>
39 #include <mono/io-layer/wapi.h>
40 #include <mono/io-layer/wapi-private.h>
41 #include <mono/io-layer/io-private.h>
42 #include <mono/io-layer/timefuncs.h>
43 #include <mono/io-layer/io-portability.h>
44 #include <mono/io-layer/io-trace.h>
45 #include <mono/utils/strenc.h>
46 #include <mono/utils/mono-once.h>
47 #include <mono/utils/mono-logger-internals.h>
48 #include <mono/metadata/w32handle.h>
51 * If SHM is disabled, this will point to a hash of _WapiFileShare structures, otherwise
52 * it will be NULL. We use this instead of _wapi_fileshare_layout to avoid allocating a
55 static GHashTable *file_share_hash;
56 static mono_mutex_t file_share_mutex;
59 _wapi_handle_share_release (_WapiFileShare *share_info)
61 /* Prevent new entries racing with us */
62 mono_os_mutex_lock (&file_share_mutex);
64 g_assert (share_info->handle_refs > 0);
65 share_info->handle_refs -= 1;
67 if (share_info->handle_refs == 0)
68 g_hash_table_remove (file_share_hash, share_info);
70 mono_os_mutex_unlock (&file_share_mutex);
74 wapi_share_info_equal (gconstpointer ka, gconstpointer kb)
76 const _WapiFileShare *s1 = (const _WapiFileShare *)ka;
77 const _WapiFileShare *s2 = (const _WapiFileShare *)kb;
79 return (s1->device == s2->device && s1->inode == s2->inode) ? 1 : 0;
83 wapi_share_info_hash (gconstpointer data)
85 const _WapiFileShare *s = (const _WapiFileShare *)data;
91 _wapi_handle_get_or_set_share (guint64 device, guint64 inode, guint32 new_sharemode, guint32 new_access,
92 guint32 *old_sharemode, guint32 *old_access, struct _WapiFileShare **share_info)
94 struct _WapiFileShare *file_share;
95 gboolean exists = FALSE;
97 /* Prevent new entries racing with us */
98 mono_os_mutex_lock (&file_share_mutex);
103 * Instead of allocating a 4MB array, we use a hash table to keep track of this
104 * info. This is needed even if SHM is disabled, to track sharing inside
105 * the current process.
107 if (!file_share_hash)
108 file_share_hash = g_hash_table_new_full (wapi_share_info_hash, wapi_share_info_equal, NULL, g_free);
113 file_share = (_WapiFileShare *)g_hash_table_lookup (file_share_hash, &tmp);
115 *old_sharemode = file_share->sharemode;
116 *old_access = file_share->access;
117 *share_info = file_share;
119 g_assert (file_share->handle_refs > 0);
120 file_share->handle_refs += 1;
124 file_share = g_new0 (_WapiFileShare, 1);
126 file_share->device = device;
127 file_share->inode = inode;
128 file_share->opened_by_pid = wapi_getpid ();
129 file_share->sharemode = new_sharemode;
130 file_share->access = new_access;
131 file_share->handle_refs = 1;
132 *share_info = file_share;
134 g_hash_table_insert (file_share_hash, file_share, file_share);
137 mono_os_mutex_unlock (&file_share_mutex);
142 static void file_close (gpointer handle, gpointer data);
143 static void file_details (gpointer data);
144 static const gchar* file_typename (void);
145 static gsize file_typesize (void);
146 static WapiFileType file_getfiletype(void);
147 static gboolean file_read(gpointer handle, gpointer buffer,
148 guint32 numbytes, guint32 *bytesread,
149 WapiOverlapped *overlapped);
150 static gboolean file_write(gpointer handle, gconstpointer buffer,
151 guint32 numbytes, guint32 *byteswritten,
152 WapiOverlapped *overlapped);
153 static gboolean file_flush(gpointer handle);
154 static guint32 file_seek(gpointer handle, gint32 movedistance,
155 gint32 *highmovedistance, WapiSeekMethod method);
156 static gboolean file_setendoffile(gpointer handle);
157 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
158 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
159 WapiFileTime *last_access,
160 WapiFileTime *last_write);
161 static gboolean file_setfiletime(gpointer handle,
162 const WapiFileTime *create_time,
163 const WapiFileTime *last_access,
164 const WapiFileTime *last_write);
165 static guint32 GetDriveTypeFromPath (const gchar *utf8_root_path_name);
167 /* File handle is only signalled for overlapped IO */
168 static MonoW32HandleOps _wapi_file_ops = {
169 file_close, /* close */
173 NULL, /* special_wait */
175 file_details, /* details */
176 file_typename, /* typename */
177 file_typesize, /* typesize */
180 static void console_close (gpointer handle, gpointer data);
181 static void console_details (gpointer data);
182 static const gchar* console_typename (void);
183 static gsize console_typesize (void);
184 static WapiFileType console_getfiletype(void);
185 static gboolean console_read(gpointer handle, gpointer buffer,
186 guint32 numbytes, guint32 *bytesread,
187 WapiOverlapped *overlapped);
188 static gboolean console_write(gpointer handle, gconstpointer buffer,
189 guint32 numbytes, guint32 *byteswritten,
190 WapiOverlapped *overlapped);
192 /* Console is mostly the same as file, except it can block waiting for
195 static MonoW32HandleOps _wapi_console_ops = {
196 console_close, /* close */
200 NULL, /* special_wait */
202 console_details, /* details */
203 console_typename, /* typename */
204 console_typesize, /* typesize */
207 static const gchar* find_typename (void);
208 static gsize find_typesize (void);
210 static MonoW32HandleOps _wapi_find_ops = {
215 NULL, /* special_wait */
218 find_typename, /* typename */
219 find_typesize, /* typesize */
222 static void pipe_close (gpointer handle, gpointer data);
223 static void pipe_details (gpointer data);
224 static const gchar* pipe_typename (void);
225 static gsize pipe_typesize (void);
226 static WapiFileType pipe_getfiletype (void);
227 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
228 guint32 *bytesread, WapiOverlapped *overlapped);
229 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
230 guint32 numbytes, guint32 *byteswritten,
231 WapiOverlapped *overlapped);
235 static MonoW32HandleOps _wapi_pipe_ops = {
236 pipe_close, /* close */
240 NULL, /* special_wait */
242 pipe_details, /* details */
243 pipe_typename, /* typename */
244 pipe_typesize, /* typesize */
247 static const struct {
248 /* File, console and pipe handles */
249 WapiFileType (*getfiletype)(void);
251 /* File, console and pipe handles */
252 gboolean (*readfile)(gpointer handle, gpointer buffer,
253 guint32 numbytes, guint32 *bytesread,
254 WapiOverlapped *overlapped);
255 gboolean (*writefile)(gpointer handle, gconstpointer buffer,
256 guint32 numbytes, guint32 *byteswritten,
257 WapiOverlapped *overlapped);
258 gboolean (*flushfile)(gpointer handle);
261 guint32 (*seek)(gpointer handle, gint32 movedistance,
262 gint32 *highmovedistance, WapiSeekMethod method);
263 gboolean (*setendoffile)(gpointer handle);
264 guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
265 gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
266 WapiFileTime *last_access,
267 WapiFileTime *last_write);
268 gboolean (*setfiletime)(gpointer handle,
269 const WapiFileTime *create_time,
270 const WapiFileTime *last_access,
271 const WapiFileTime *last_write);
272 } io_ops[MONO_W32HANDLE_COUNT]={
273 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
276 file_read, file_write,
277 file_flush, file_seek,
283 {console_getfiletype,
286 NULL, NULL, NULL, NULL, NULL, NULL},
288 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
290 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
292 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
294 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
295 /* socket (will need at least read and write) */
296 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
298 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
300 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
305 NULL, NULL, NULL, NULL, NULL, NULL},
308 static gboolean lock_while_writing = FALSE;
310 /* Some utility functions.
314 * Check if a file is writable by the current user.
316 * This is is a best effort kind of thing. It assumes a reasonable sane set
317 * of permissions by the underlying OS.
319 * We generally assume that basic unix permission bits are authoritative. Which might not
320 * be the case under systems with extended permissions systems (posix ACLs, SELinux, OSX/iOS sandboxing, etc)
322 * The choice of access as the fallback is due to the expected lower overhead compared to trying to open the file.
324 * The only expected problem with using access are for root, setuid or setgid programs as access is not consistent
325 * under those situations. It's to be expected that this should not happen in practice as those bits are very dangerous
326 * and should not be used with a dynamic runtime.
329 is_file_writable (struct stat *st, const char *path)
332 // OS X Finder "locked" or `ls -lO` "uchg".
333 // This only covers one of several cases where an OS X file could be unwritable through special flags.
334 if (st->st_flags & (UF_IMMUTABLE|SF_IMMUTABLE))
338 /* Is it globally writable? */
339 if (st->st_mode & S_IWOTH)
342 /* Am I the owner? */
343 if ((st->st_uid == geteuid ()) && (st->st_mode & S_IWUSR))
346 /* Am I in the same group? */
347 if ((st->st_gid == getegid ()) && (st->st_mode & S_IWGRP))
350 /* Fallback to using access(2). It's not ideal as it might not take into consideration euid/egid
351 * but it's the only sane option we have on unix.
353 return access (path, W_OK) == 0;
357 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
364 /* FIXME: this could definitely be better, but there seems to
365 * be no pattern to the attributes that are set
368 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
369 if (S_ISSOCK (buf->st_mode))
370 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
372 filename = _wapi_basename (pathname);
374 if (S_ISDIR (buf->st_mode)) {
375 attrs = FILE_ATTRIBUTE_DIRECTORY;
376 if (!is_file_writable (buf, pathname)) {
377 attrs |= FILE_ATTRIBUTE_READONLY;
379 if (filename[0] == '.') {
380 attrs |= FILE_ATTRIBUTE_HIDDEN;
383 if (!is_file_writable (buf, pathname)) {
384 attrs = FILE_ATTRIBUTE_READONLY;
386 if (filename[0] == '.') {
387 attrs |= FILE_ATTRIBUTE_HIDDEN;
389 } else if (filename[0] == '.') {
390 attrs = FILE_ATTRIBUTE_HIDDEN;
392 attrs = FILE_ATTRIBUTE_NORMAL;
397 if (S_ISLNK (lbuf->st_mode)) {
398 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
408 _wapi_set_last_error_from_errno (void)
410 SetLastError (_wapi_get_win32_file_error (errno));
413 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
416 if (errno == ENOENT) {
417 /* Check the path - if it's a missing directory then
418 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
424 dirname = _wapi_dirname (path);
426 dirname = g_strdup (dir);
429 if (_wapi_access (dirname, F_OK) == 0) {
430 SetLastError (ERROR_FILE_NOT_FOUND);
432 SetLastError (ERROR_PATH_NOT_FOUND);
437 _wapi_set_last_error_from_errno ();
443 static void file_close (gpointer handle, gpointer data)
445 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
446 int fd = file_handle->fd;
448 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing file handle %p [%s]", __func__, handle,
449 file_handle->filename);
451 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
452 _wapi_unlink (file_handle->filename);
454 g_free (file_handle->filename);
456 if (file_handle->share_info)
457 _wapi_handle_share_release (file_handle->share_info);
462 static void file_details (gpointer data)
464 struct _WapiHandle_file *file = (struct _WapiHandle_file *)data;
466 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
468 file->fileaccess&GENERIC_READ?'R':'.',
469 file->fileaccess&GENERIC_WRITE?'W':'.',
470 file->fileaccess&GENERIC_EXECUTE?'X':'.',
471 file->sharemode&FILE_SHARE_READ?'R':'.',
472 file->sharemode&FILE_SHARE_WRITE?'W':'.',
473 file->sharemode&FILE_SHARE_DELETE?'D':'.',
477 static const gchar* file_typename (void)
482 static gsize file_typesize (void)
484 return sizeof (struct _WapiHandle_file);
487 static WapiFileType file_getfiletype(void)
489 return(FILE_TYPE_DISK);
492 static gboolean file_read(gpointer handle, gpointer buffer,
493 guint32 numbytes, guint32 *bytesread,
494 WapiOverlapped *overlapped)
496 struct _WapiHandle_file *file_handle;
499 MonoThreadInfo *info = mono_thread_info_current ();
501 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
502 (gpointer *)&file_handle);
504 g_warning ("%s: error looking up file handle %p", __func__,
506 SetLastError (ERROR_INVALID_HANDLE);
510 fd = file_handle->fd;
511 if(bytesread!=NULL) {
515 if(!(file_handle->fileaccess & GENERIC_READ) &&
516 !(file_handle->fileaccess & GENERIC_ALL)) {
517 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
518 __func__, handle, file_handle->fileaccess);
520 SetLastError (ERROR_ACCESS_DENIED);
525 ret = read (fd, buffer, numbytes);
526 } while (ret == -1 && errno == EINTR &&
527 !mono_thread_info_is_interrupt_state (info));
532 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
533 handle, strerror(err));
534 SetLastError (_wapi_get_win32_file_error (err));
538 if (bytesread != NULL) {
545 static gboolean file_write(gpointer handle, gconstpointer buffer,
546 guint32 numbytes, guint32 *byteswritten,
547 WapiOverlapped *overlapped G_GNUC_UNUSED)
549 struct _WapiHandle_file *file_handle;
552 off_t current_pos = 0;
553 MonoThreadInfo *info = mono_thread_info_current ();
555 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
556 (gpointer *)&file_handle);
558 g_warning ("%s: error looking up file handle %p", __func__,
560 SetLastError (ERROR_INVALID_HANDLE);
564 fd = file_handle->fd;
566 if(byteswritten!=NULL) {
570 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
571 !(file_handle->fileaccess & GENERIC_ALL)) {
572 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);
574 SetLastError (ERROR_ACCESS_DENIED);
578 if (lock_while_writing) {
579 /* Need to lock the region we're about to write to,
580 * because we only do advisory locking on POSIX
583 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
584 if (current_pos == -1) {
585 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
586 handle, strerror (errno));
587 _wapi_set_last_error_from_errno ();
591 if (_wapi_lock_file_region (fd, current_pos,
592 numbytes) == FALSE) {
593 /* The error has already been set */
599 ret = write (fd, buffer, numbytes);
600 } while (ret == -1 && errno == EINTR &&
601 !mono_thread_info_is_interrupt_state (info));
603 if (lock_while_writing) {
604 _wapi_unlock_file_region (fd, current_pos, numbytes);
608 if (errno == EINTR) {
611 _wapi_set_last_error_from_errno ();
613 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
614 __func__, handle, strerror(errno));
619 if (byteswritten != NULL) {
625 static gboolean file_flush(gpointer handle)
627 struct _WapiHandle_file *file_handle;
631 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
632 (gpointer *)&file_handle);
634 g_warning ("%s: error looking up file handle %p", __func__,
636 SetLastError (ERROR_INVALID_HANDLE);
640 fd = file_handle->fd;
642 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
643 !(file_handle->fileaccess & GENERIC_ALL)) {
644 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);
646 SetLastError (ERROR_ACCESS_DENIED);
652 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fsync of handle %p error: %s", __func__, handle,
655 _wapi_set_last_error_from_errno ();
662 static guint32 file_seek(gpointer handle, gint32 movedistance,
663 gint32 *highmovedistance, WapiSeekMethod method)
665 struct _WapiHandle_file *file_handle;
667 gint64 offset, newpos;
671 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
672 (gpointer *)&file_handle);
674 g_warning ("%s: error looking up file handle %p", __func__,
676 SetLastError (ERROR_INVALID_HANDLE);
677 return(INVALID_SET_FILE_POINTER);
680 fd = file_handle->fd;
682 if(!(file_handle->fileaccess & GENERIC_READ) &&
683 !(file_handle->fileaccess & GENERIC_WRITE) &&
684 !(file_handle->fileaccess & GENERIC_ALL)) {
685 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);
687 SetLastError (ERROR_ACCESS_DENIED);
688 return(INVALID_SET_FILE_POINTER);
702 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: invalid seek type %d", __func__, method);
704 SetLastError (ERROR_INVALID_PARAMETER);
705 return(INVALID_SET_FILE_POINTER);
708 #ifdef HAVE_LARGE_FILE_SUPPORT
709 if(highmovedistance==NULL) {
711 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting offset to %lld (low %d)", __func__,
712 offset, movedistance);
714 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
716 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);
722 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: moving handle %p by %lld bytes from %d", __func__,
723 handle, (long long)offset, whence);
725 #ifdef PLATFORM_ANDROID
726 /* bionic doesn't support -D_FILE_OFFSET_BITS=64 */
727 newpos=lseek64(fd, offset, whence);
729 newpos=lseek(fd, offset, whence);
732 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek on handle %p returned error %s",
733 __func__, handle, strerror(errno));
735 _wapi_set_last_error_from_errno ();
736 return(INVALID_SET_FILE_POINTER);
739 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek returns %lld", __func__, newpos);
741 #ifdef HAVE_LARGE_FILE_SUPPORT
742 ret=newpos & 0xFFFFFFFF;
743 if(highmovedistance!=NULL) {
744 *highmovedistance=newpos>>32;
748 if(highmovedistance!=NULL) {
749 /* Accurate, but potentially dodgy :-) */
754 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: move of handle %p returning %d/%d", __func__,
755 handle, ret, highmovedistance==NULL?0:*highmovedistance);
760 static gboolean file_setendoffile(gpointer handle)
762 struct _WapiHandle_file *file_handle;
767 MonoThreadInfo *info = mono_thread_info_current ();
769 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
770 (gpointer *)&file_handle);
772 g_warning ("%s: error looking up file handle %p", __func__,
774 SetLastError (ERROR_INVALID_HANDLE);
777 fd = file_handle->fd;
779 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
780 !(file_handle->fileaccess & GENERIC_ALL)) {
781 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);
783 SetLastError (ERROR_ACCESS_DENIED);
787 /* Find the current file position, and the file length. If
788 * the file position is greater than the length, write to
789 * extend the file with a hole. If the file position is less
790 * than the length, truncate the file.
793 ret=fstat(fd, &statbuf);
795 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
796 handle, strerror(errno));
798 _wapi_set_last_error_from_errno ();
802 pos=lseek(fd, (off_t)0, SEEK_CUR);
804 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
805 handle, strerror(errno));
807 _wapi_set_last_error_from_errno ();
811 #ifdef FTRUNCATE_DOESNT_EXTEND
812 off_t size = statbuf.st_size;
813 /* I haven't bothered to write the configure.ac stuff for this
814 * because I don't know if any platform needs it. I'm leaving
815 * this code just in case though
818 /* Extend the file. Use write() here, because some
819 * manuals say that ftruncate() behaviour is undefined
820 * when the file needs extending. The POSIX spec says
821 * that on XSI-conformant systems it extends, so if
822 * every system we care about conforms, then we can
826 ret = write (fd, "", 1);
827 } while (ret == -1 && errno == EINTR &&
828 !mono_thread_info_is_interrupt_state (info));
831 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
833 _wapi_set_last_error_from_errno ();
837 /* And put the file position back after the write */
838 ret = lseek (fd, pos, SEEK_SET);
840 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p second lseek failed: %s",
841 __func__, handle, strerror(errno));
843 _wapi_set_last_error_from_errno ();
849 /* Native Client has no ftruncate function, even in standalone sel_ldr. */
850 #ifndef __native_client__
851 /* always truncate, because the extend write() adds an extra
852 * byte to the end of the file
855 ret=ftruncate(fd, pos);
857 while (ret==-1 && errno==EINTR && !mono_thread_info_is_interrupt_state (info));
859 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ftruncate failed: %s", __func__,
860 handle, strerror(errno));
862 _wapi_set_last_error_from_errno ();
870 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
872 struct _WapiHandle_file *file_handle;
879 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
880 (gpointer *)&file_handle);
882 g_warning ("%s: error looking up file handle %p", __func__,
884 SetLastError (ERROR_INVALID_HANDLE);
885 return(INVALID_FILE_SIZE);
887 fd = file_handle->fd;
889 if(!(file_handle->fileaccess & GENERIC_READ) &&
890 !(file_handle->fileaccess & GENERIC_WRITE) &&
891 !(file_handle->fileaccess & GENERIC_ALL)) {
892 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);
894 SetLastError (ERROR_ACCESS_DENIED);
895 return(INVALID_FILE_SIZE);
898 /* If the file has a size with the low bits 0xFFFFFFFF the
899 * caller can't tell if this is an error, so clear the error
902 SetLastError (ERROR_SUCCESS);
904 ret = fstat(fd, &statbuf);
906 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
907 handle, strerror(errno));
909 _wapi_set_last_error_from_errno ();
910 return(INVALID_FILE_SIZE);
913 /* fstat indicates block devices as zero-length, so go a different path */
915 if (S_ISBLK(statbuf.st_mode)) {
917 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
918 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ioctl BLKGETSIZE64 failed: %s",
919 __func__, handle, strerror(errno));
921 _wapi_set_last_error_from_errno ();
922 return(INVALID_FILE_SIZE);
925 size = bigsize & 0xFFFFFFFF;
926 if (highsize != NULL) {
927 *highsize = bigsize>>32;
930 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning block device size %d/%d",
931 __func__, size, *highsize);
937 #ifdef HAVE_LARGE_FILE_SUPPORT
938 size = statbuf.st_size & 0xFFFFFFFF;
939 if (highsize != NULL) {
940 *highsize = statbuf.st_size>>32;
943 if (highsize != NULL) {
944 /* Accurate, but potentially dodgy :-) */
947 size = statbuf.st_size;
950 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning size %d/%d", __func__, size, *highsize);
955 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
956 WapiFileTime *last_access,
957 WapiFileTime *last_write)
959 struct _WapiHandle_file *file_handle;
962 guint64 create_ticks, access_ticks, write_ticks;
965 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
966 (gpointer *)&file_handle);
968 g_warning ("%s: error looking up file handle %p", __func__,
970 SetLastError (ERROR_INVALID_HANDLE);
973 fd = file_handle->fd;
975 if(!(file_handle->fileaccess & GENERIC_READ) &&
976 !(file_handle->fileaccess & GENERIC_ALL)) {
977 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
978 __func__, handle, file_handle->fileaccess);
980 SetLastError (ERROR_ACCESS_DENIED);
984 ret=fstat(fd, &statbuf);
986 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
989 _wapi_set_last_error_from_errno ();
993 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: atime: %ld ctime: %ld mtime: %ld", __func__,
994 statbuf.st_atime, statbuf.st_ctime,
997 /* Try and guess a meaningful create time by using the older
1000 /* The magic constant comes from msdn documentation
1001 * "Converting a time_t Value to a File Time"
1003 if(statbuf.st_atime < statbuf.st_ctime) {
1004 create_ticks=((guint64)statbuf.st_atime*10000000)
1005 + 116444736000000000ULL;
1007 create_ticks=((guint64)statbuf.st_ctime*10000000)
1008 + 116444736000000000ULL;
1011 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
1012 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
1014 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
1015 access_ticks, create_ticks, write_ticks);
1017 if(create_time!=NULL) {
1018 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
1019 create_time->dwHighDateTime = create_ticks >> 32;
1022 if(last_access!=NULL) {
1023 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
1024 last_access->dwHighDateTime = access_ticks >> 32;
1027 if(last_write!=NULL) {
1028 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
1029 last_write->dwHighDateTime = write_ticks >> 32;
1035 static gboolean file_setfiletime(gpointer handle,
1036 const WapiFileTime *create_time G_GNUC_UNUSED,
1037 const WapiFileTime *last_access,
1038 const WapiFileTime *last_write)
1040 struct _WapiHandle_file *file_handle;
1042 struct utimbuf utbuf;
1043 struct stat statbuf;
1044 guint64 access_ticks, write_ticks;
1047 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1048 (gpointer *)&file_handle);
1050 g_warning ("%s: error looking up file handle %p", __func__,
1052 SetLastError (ERROR_INVALID_HANDLE);
1055 fd = file_handle->fd;
1057 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
1058 !(file_handle->fileaccess & GENERIC_ALL)) {
1059 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);
1061 SetLastError (ERROR_ACCESS_DENIED);
1065 if(file_handle->filename == NULL) {
1066 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p unknown filename", __func__, handle);
1068 SetLastError (ERROR_INVALID_HANDLE);
1072 /* Get the current times, so we can put the same times back in
1073 * the event that one of the FileTime structs is NULL
1075 ret=fstat (fd, &statbuf);
1077 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
1080 SetLastError (ERROR_INVALID_PARAMETER);
1084 if(last_access!=NULL) {
1085 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
1086 last_access->dwLowDateTime;
1087 /* This is (time_t)0. We can actually go to INT_MIN,
1088 * but this will do for now.
1090 if (access_ticks < 116444736000000000ULL) {
1091 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set access time too early",
1093 SetLastError (ERROR_INVALID_PARAMETER);
1097 if (sizeof (utbuf.actime) == 4 && ((access_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
1098 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",
1100 SetLastError (ERROR_INVALID_PARAMETER);
1104 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
1106 utbuf.actime=statbuf.st_atime;
1109 if(last_write!=NULL) {
1110 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
1111 last_write->dwLowDateTime;
1112 /* This is (time_t)0. We can actually go to INT_MIN,
1113 * but this will do for now.
1115 if (write_ticks < 116444736000000000ULL) {
1116 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set write time too early",
1118 SetLastError (ERROR_INVALID_PARAMETER);
1121 if (sizeof (utbuf.modtime) == 4 && ((write_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
1122 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",
1124 SetLastError (ERROR_INVALID_PARAMETER);
1128 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1130 utbuf.modtime=statbuf.st_mtime;
1133 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting handle %p access %ld write %ld", __func__,
1134 handle, utbuf.actime, utbuf.modtime);
1136 ret = _wapi_utime (file_handle->filename, &utbuf);
1138 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p [%s] utime failed: %s", __func__,
1139 handle, file_handle->filename, strerror(errno));
1141 SetLastError (ERROR_INVALID_PARAMETER);
1148 static void console_close (gpointer handle, gpointer data)
1150 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1151 int fd = console_handle->fd;
1153 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing console handle %p", __func__, handle);
1155 g_free (console_handle->filename);
1158 if (console_handle->share_info)
1159 _wapi_handle_share_release (console_handle->share_info);
1164 static void console_details (gpointer data)
1166 file_details (data);
1169 static const gchar* console_typename (void)
1174 static gsize console_typesize (void)
1176 return sizeof (struct _WapiHandle_file);
1179 static WapiFileType console_getfiletype(void)
1181 return(FILE_TYPE_CHAR);
1184 static gboolean console_read(gpointer handle, gpointer buffer,
1185 guint32 numbytes, guint32 *bytesread,
1186 WapiOverlapped *overlapped G_GNUC_UNUSED)
1188 struct _WapiHandle_file *console_handle;
1191 MonoThreadInfo *info = mono_thread_info_current ();
1193 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_CONSOLE,
1194 (gpointer *)&console_handle);
1196 g_warning ("%s: error looking up console handle %p", __func__,
1198 SetLastError (ERROR_INVALID_HANDLE);
1201 fd = console_handle->fd;
1203 if(bytesread!=NULL) {
1207 if(!(console_handle->fileaccess & GENERIC_READ) &&
1208 !(console_handle->fileaccess & GENERIC_ALL)) {
1209 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1210 __func__, handle, console_handle->fileaccess);
1212 SetLastError (ERROR_ACCESS_DENIED);
1217 ret=read(fd, buffer, numbytes);
1218 } while (ret==-1 && errno==EINTR && !mono_thread_info_is_interrupt_state (info));
1221 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__, handle,
1224 _wapi_set_last_error_from_errno ();
1228 if(bytesread!=NULL) {
1235 static gboolean console_write(gpointer handle, gconstpointer buffer,
1236 guint32 numbytes, guint32 *byteswritten,
1237 WapiOverlapped *overlapped G_GNUC_UNUSED)
1239 struct _WapiHandle_file *console_handle;
1242 MonoThreadInfo *info = mono_thread_info_current ();
1244 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_CONSOLE,
1245 (gpointer *)&console_handle);
1247 g_warning ("%s: error looking up console handle %p", __func__,
1249 SetLastError (ERROR_INVALID_HANDLE);
1252 fd = console_handle->fd;
1254 if(byteswritten!=NULL) {
1258 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1259 !(console_handle->fileaccess & GENERIC_ALL)) {
1260 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, console_handle->fileaccess);
1262 SetLastError (ERROR_ACCESS_DENIED);
1267 ret = write(fd, buffer, numbytes);
1268 } while (ret == -1 && errno == EINTR &&
1269 !mono_thread_info_is_interrupt_state (info));
1272 if (errno == EINTR) {
1275 _wapi_set_last_error_from_errno ();
1277 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
1278 __func__, handle, strerror(errno));
1283 if(byteswritten!=NULL) {
1290 static const gchar* find_typename (void)
1295 static gsize find_typesize (void)
1297 return sizeof (struct _WapiHandle_find);
1300 static void pipe_close (gpointer handle, gpointer data)
1302 struct _WapiHandle_file *pipe_handle = (struct _WapiHandle_file*)data;
1303 int fd = pipe_handle->fd;
1305 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing pipe handle %p fd %d", __func__, handle, fd);
1307 /* No filename with pipe handles */
1309 if (pipe_handle->share_info)
1310 _wapi_handle_share_release (pipe_handle->share_info);
1315 static void pipe_details (gpointer data)
1317 file_details (data);
1320 static const gchar* pipe_typename (void)
1325 static gsize pipe_typesize (void)
1327 return sizeof (struct _WapiHandle_file);
1330 static WapiFileType pipe_getfiletype(void)
1332 return(FILE_TYPE_PIPE);
1335 static gboolean pipe_read (gpointer handle, gpointer buffer,
1336 guint32 numbytes, guint32 *bytesread,
1337 WapiOverlapped *overlapped G_GNUC_UNUSED)
1339 struct _WapiHandle_file *pipe_handle;
1342 MonoThreadInfo *info = mono_thread_info_current ();
1344 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_PIPE,
1345 (gpointer *)&pipe_handle);
1347 g_warning ("%s: error looking up pipe handle %p", __func__,
1349 SetLastError (ERROR_INVALID_HANDLE);
1352 fd = pipe_handle->fd;
1354 if(bytesread!=NULL) {
1358 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1359 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1360 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1361 __func__, handle, pipe_handle->fileaccess);
1363 SetLastError (ERROR_ACCESS_DENIED);
1367 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: reading up to %d bytes from pipe %p", __func__,
1371 ret=read(fd, buffer, numbytes);
1372 } while (ret==-1 && errno==EINTR && !mono_thread_info_is_interrupt_state (info));
1375 if (errno == EINTR) {
1378 _wapi_set_last_error_from_errno ();
1380 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
1381 handle, strerror(errno));
1387 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read %d bytes from pipe %p", __func__, ret, handle);
1389 if(bytesread!=NULL) {
1396 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1397 guint32 numbytes, guint32 *byteswritten,
1398 WapiOverlapped *overlapped G_GNUC_UNUSED)
1400 struct _WapiHandle_file *pipe_handle;
1403 MonoThreadInfo *info = mono_thread_info_current ();
1405 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_PIPE,
1406 (gpointer *)&pipe_handle);
1408 g_warning ("%s: error looking up pipe handle %p", __func__,
1410 SetLastError (ERROR_INVALID_HANDLE);
1413 fd = pipe_handle->fd;
1415 if(byteswritten!=NULL) {
1419 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1420 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1421 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);
1423 SetLastError (ERROR_ACCESS_DENIED);
1427 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1431 ret = write (fd, buffer, numbytes);
1432 } while (ret == -1 && errno == EINTR &&
1433 !mono_thread_info_is_interrupt_state (info));
1436 if (errno == EINTR) {
1439 _wapi_set_last_error_from_errno ();
1441 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s", __func__,
1442 handle, strerror(errno));
1447 if(byteswritten!=NULL) {
1454 static int convert_flags(guint32 fileaccess, guint32 createmode)
1458 switch(fileaccess) {
1465 case GENERIC_READ|GENERIC_WRITE:
1469 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown access type 0x%x", __func__,
1474 switch(createmode) {
1476 flags|=O_CREAT|O_EXCL;
1479 flags|=O_CREAT|O_TRUNC;
1486 case TRUNCATE_EXISTING:
1490 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown create mode 0x%x", __func__,
1499 static mode_t convert_perms(guint32 sharemode)
1503 if(sharemode&FILE_SHARE_READ) {
1506 if(sharemode&FILE_SHARE_WRITE) {
1514 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1516 struct _WapiFileShare **share_info)
1518 gboolean file_already_shared;
1519 guint32 file_existing_share, file_existing_access;
1521 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);
1523 if (file_already_shared) {
1524 /* The reference to this share info was incremented
1525 * when we looked it up, so be careful to put it back
1526 * if we conclude we can't use this file.
1528 if (file_existing_share == 0) {
1529 /* Quick and easy, no possibility to share */
1530 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);
1532 _wapi_handle_share_release (*share_info);
1537 if (((file_existing_share == FILE_SHARE_READ) &&
1538 (fileaccess != GENERIC_READ)) ||
1539 ((file_existing_share == FILE_SHARE_WRITE) &&
1540 (fileaccess != GENERIC_WRITE))) {
1541 /* New access mode doesn't match up */
1542 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);
1544 _wapi_handle_share_release (*share_info);
1549 if (((file_existing_access & GENERIC_READ) &&
1550 !(sharemode & FILE_SHARE_READ)) ||
1551 ((file_existing_access & GENERIC_WRITE) &&
1552 !(sharemode & FILE_SHARE_WRITE))) {
1553 /* New share mode doesn't match up */
1554 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);
1556 _wapi_handle_share_release (*share_info);
1561 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
1569 share_allows_delete (struct stat *statbuf, struct _WapiFileShare **share_info)
1571 gboolean file_already_shared;
1572 guint32 file_existing_share, file_existing_access;
1574 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);
1576 if (file_already_shared) {
1577 /* The reference to this share info was incremented
1578 * when we looked it up, so be careful to put it back
1579 * if we conclude we can't use this file.
1581 if (file_existing_share == 0) {
1582 /* Quick and easy, no possibility to share */
1583 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);
1585 _wapi_handle_share_release (*share_info);
1590 if (!(file_existing_share & FILE_SHARE_DELETE)) {
1591 /* New access mode doesn't match up */
1592 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);
1594 _wapi_handle_share_release (*share_info);
1599 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
1607 * @name: a pointer to a NULL-terminated unicode string, that names
1608 * the file or other object to create.
1609 * @fileaccess: specifies the file access mode
1610 * @sharemode: whether the file should be shared. This parameter is
1611 * currently ignored.
1612 * @security: Ignored for now.
1613 * @createmode: specifies whether to create a new file, whether to
1614 * overwrite an existing file, whether to truncate the file, etc.
1615 * @attrs: specifies file attributes and flags. On win32 attributes
1616 * are characteristics of the file, not the handle, and are ignored
1617 * when an existing file is opened. Flags give the library hints on
1618 * how to process a file to optimise performance.
1619 * @template: the handle of an open %GENERIC_READ file that specifies
1620 * attributes to apply to a newly created file, ignoring @attrs.
1621 * Normally this parameter is NULL. This parameter is ignored when an
1622 * existing file is opened.
1624 * Creates a new file handle. This only applies to normal files:
1625 * pipes are handled by CreatePipe(), and console handles are created
1626 * with GetStdHandle().
1628 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1630 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1631 guint32 sharemode, WapiSecurityAttributes *security,
1632 guint32 createmode, guint32 attrs,
1633 gpointer template_ G_GNUC_UNUSED)
1635 struct _WapiHandle_file file_handle = {0};
1637 int flags=convert_flags(fileaccess, createmode);
1638 /*mode_t perms=convert_perms(sharemode);*/
1639 /* we don't use sharemode, because that relates to sharing of
1640 * the file when the file is open and is already handled by
1641 * other code, perms instead are the on-disk permissions and
1642 * this is a sane default.
1647 MonoW32HandleType handle_type;
1648 struct stat statbuf;
1650 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1653 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1654 SetLastError (ERROR_ENCRYPTION_FAILED);
1655 return INVALID_HANDLE_VALUE;
1659 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1661 SetLastError (ERROR_INVALID_NAME);
1662 return(INVALID_HANDLE_VALUE);
1665 filename = mono_unicode_to_external (name);
1666 if (filename == NULL) {
1667 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1669 SetLastError (ERROR_INVALID_NAME);
1670 return(INVALID_HANDLE_VALUE);
1673 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Opening %s with share 0x%x and access 0x%x", __func__,
1674 filename, sharemode, fileaccess);
1676 fd = _wapi_open (filename, flags, perms);
1678 /* If we were trying to open a directory with write permissions
1679 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1680 * EISDIR. However, this is a bit bogus because calls to
1681 * manipulate the directory (e.g. SetFileTime) will still work on
1682 * the directory because they use other API calls
1683 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1684 * to open the directory again without write permission.
1686 if (fd == -1 && errno == EISDIR)
1688 /* Try again but don't try to make it writable */
1689 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1693 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s: %s", __func__, filename,
1695 _wapi_set_last_path_error_from_errno (NULL, filename);
1698 return(INVALID_HANDLE_VALUE);
1701 if (fd >= mono_w32handle_fd_reserve) {
1702 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
1704 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1709 return(INVALID_HANDLE_VALUE);
1712 ret = fstat (fd, &statbuf);
1714 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fstat error of file %s: %s", __func__,
1715 filename, strerror (errno));
1716 _wapi_set_last_error_from_errno ();
1720 return(INVALID_HANDLE_VALUE);
1722 #ifdef __native_client__
1723 /* Workaround: Native Client currently returns the same fake inode
1724 * for all files, so do a simple hash on the filename so we don't
1725 * use the same share info for each file.
1727 statbuf.st_ino = g_str_hash(filename);
1730 if (share_allows_open (&statbuf, sharemode, fileaccess,
1731 &file_handle.share_info) == FALSE) {
1732 SetLastError (ERROR_SHARING_VIOLATION);
1736 return (INVALID_HANDLE_VALUE);
1738 if (file_handle.share_info == NULL) {
1739 /* No space, so no more files can be opened */
1740 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No space in the share table", __func__);
1742 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1746 return(INVALID_HANDLE_VALUE);
1749 file_handle.filename = filename;
1751 if(security!=NULL) {
1752 //file_handle->security_attributes=_wapi_handle_scratch_store (
1753 //security, sizeof(WapiSecurityAttributes));
1756 file_handle.fd = fd;
1757 file_handle.fileaccess=fileaccess;
1758 file_handle.sharemode=sharemode;
1759 file_handle.attrs=attrs;
1761 #ifdef HAVE_POSIX_FADVISE
1762 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1763 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1764 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1765 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1769 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1770 fcntl(fd, F_RDAHEAD, 1);
1774 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1776 if (S_ISFIFO (statbuf.st_mode)) {
1777 handle_type = MONO_W32HANDLE_PIPE;
1778 /* maintain invariant that pipes have no filename */
1779 file_handle.filename = NULL;
1782 } else if (S_ISCHR (statbuf.st_mode)) {
1783 handle_type = MONO_W32HANDLE_CONSOLE;
1785 handle_type = MONO_W32HANDLE_FILE;
1788 handle = mono_w32handle_new_fd (handle_type, fd, &file_handle);
1789 if (handle == INVALID_HANDLE_VALUE) {
1790 g_warning ("%s: error creating file handle", __func__);
1794 SetLastError (ERROR_GEN_FAILURE);
1795 return(INVALID_HANDLE_VALUE);
1798 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p", __func__, handle);
1805 * @name: a pointer to a NULL-terminated unicode string, that names
1806 * the file to be deleted.
1808 * Deletes file @name.
1810 * Return value: %TRUE on success, %FALSE otherwise.
1812 gboolean DeleteFile(const gunichar2 *name)
1816 gboolean ret = FALSE;
1819 struct stat statbuf;
1820 struct _WapiFileShare *shareinfo;
1824 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1826 SetLastError (ERROR_INVALID_NAME);
1830 filename=mono_unicode_to_external(name);
1831 if(filename==NULL) {
1832 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1834 SetLastError (ERROR_INVALID_NAME);
1838 attrs = GetFileAttributes (name);
1839 if (attrs == INVALID_FILE_ATTRIBUTES) {
1840 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file attributes error", __func__);
1841 /* Error set by GetFileAttributes() */
1847 /* Check to make sure sharing allows us to open the file for
1848 * writing. See bug 323389.
1850 * Do the checks that don't need an open file descriptor, for
1851 * simplicity's sake. If we really have to do the full checks
1852 * then we can implement that later.
1854 if (_wapi_stat (filename, &statbuf) < 0) {
1855 _wapi_set_last_path_error_from_errno (NULL, filename);
1860 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1861 &shareinfo) == FALSE) {
1862 SetLastError (ERROR_SHARING_VIOLATION);
1867 _wapi_handle_share_release (shareinfo);
1870 retval = _wapi_unlink (filename);
1873 _wapi_set_last_path_error_from_errno (NULL, filename);
1885 * @name: a pointer to a NULL-terminated unicode string, that names
1886 * the file to be moved.
1887 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1888 * new name for the file.
1890 * Renames file @name to @dest_name.
1891 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1892 * when it is the same file as the source. In that case it silently succeeds.
1894 * Return value: %TRUE on success, %FALSE otherwise.
1896 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1898 gchar *utf8_name, *utf8_dest_name;
1899 int result, errno_copy;
1900 struct stat stat_src, stat_dest;
1901 gboolean ret = FALSE;
1902 struct _WapiFileShare *shareinfo;
1905 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1907 SetLastError (ERROR_INVALID_NAME);
1911 utf8_name = mono_unicode_to_external (name);
1912 if (utf8_name == NULL) {
1913 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1915 SetLastError (ERROR_INVALID_NAME);
1919 if(dest_name==NULL) {
1920 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1923 SetLastError (ERROR_INVALID_NAME);
1927 utf8_dest_name = mono_unicode_to_external (dest_name);
1928 if (utf8_dest_name == NULL) {
1929 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1932 SetLastError (ERROR_INVALID_NAME);
1937 * In C# land we check for the existence of src, but not for dest.
1938 * We check it here and return the failure if dest exists and is not
1939 * the same file as src.
1941 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1942 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1943 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1945 g_free (utf8_dest_name);
1950 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1951 if (stat_dest.st_dev != stat_src.st_dev ||
1952 stat_dest.st_ino != stat_src.st_ino) {
1954 g_free (utf8_dest_name);
1955 SetLastError (ERROR_ALREADY_EXISTS);
1960 /* Check to make that we have delete sharing permission.
1961 * See https://bugzilla.xamarin.com/show_bug.cgi?id=17009
1963 * Do the checks that don't need an open file descriptor, for
1964 * simplicity's sake. If we really have to do the full checks
1965 * then we can implement that later.
1967 if (share_allows_delete (&stat_src, &shareinfo) == FALSE) {
1968 SetLastError (ERROR_SHARING_VIOLATION);
1972 _wapi_handle_share_release (shareinfo);
1974 result = _wapi_rename (utf8_name, utf8_dest_name);
1978 switch(errno_copy) {
1980 SetLastError (ERROR_ALREADY_EXISTS);
1984 /* Ignore here, it is dealt with below */
1988 /* We already know src exists. Must be dest that doesn't exist. */
1989 _wapi_set_last_path_error_from_errno (NULL, utf8_dest_name);
1993 _wapi_set_last_error_from_errno ();
1998 g_free (utf8_dest_name);
2000 if (result != 0 && errno_copy == EXDEV) {
2001 if (S_ISDIR (stat_src.st_mode)) {
2002 SetLastError (ERROR_NOT_SAME_DEVICE);
2005 /* Try a copy to the new location, and delete the source */
2006 if (CopyFile (name, dest_name, TRUE)==FALSE) {
2007 /* CopyFile will set the error */
2011 return(DeleteFile (name));
2022 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
2026 int buf_size = st_src->st_blksize;
2027 MonoThreadInfo *info = mono_thread_info_current ();
2029 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
2030 buf = (char *) g_malloc (buf_size);
2033 remain = read (src_fd, buf, buf_size);
2035 if (errno == EINTR && !mono_thread_info_is_interrupt_state (info))
2039 _wapi_set_last_error_from_errno ();
2049 while (remain > 0) {
2050 if ((n = write (dest_fd, wbuf, remain)) < 0) {
2051 if (errno == EINTR && !mono_thread_info_is_interrupt_state (info))
2055 _wapi_set_last_error_from_errno ();
2056 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write failed.", __func__);
2072 * @name: a pointer to a NULL-terminated unicode string, that names
2073 * the file to be copied.
2074 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
2075 * new name for the file.
2076 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
2078 * Copies file @name to @dest_name
2080 * Return value: %TRUE on success, %FALSE otherwise.
2082 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
2083 gboolean fail_if_exists)
2085 gchar *utf8_src, *utf8_dest;
2086 int src_fd, dest_fd;
2087 struct stat st, dest_st;
2088 struct utimbuf dest_time;
2089 gboolean ret = TRUE;
2093 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2095 SetLastError (ERROR_INVALID_NAME);
2099 utf8_src = mono_unicode_to_external (name);
2100 if (utf8_src == NULL) {
2101 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of source returned NULL",
2104 SetLastError (ERROR_INVALID_PARAMETER);
2108 if(dest_name==NULL) {
2109 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: dest is NULL", __func__);
2112 SetLastError (ERROR_INVALID_NAME);
2116 utf8_dest = mono_unicode_to_external (dest_name);
2117 if (utf8_dest == NULL) {
2118 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of dest returned NULL",
2121 SetLastError (ERROR_INVALID_PARAMETER);
2128 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2130 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2138 if (fstat (src_fd, &st) < 0) {
2139 _wapi_set_last_error_from_errno ();
2148 /* Before trying to open/create the dest, we need to report a 'file busy'
2149 * error if src and dest are actually the same file. We do the check here to take
2150 * advantage of the IOMAP capability */
2151 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
2152 st.st_ino == dest_st.st_ino) {
2158 SetLastError (ERROR_SHARING_VIOLATION);
2162 if (fail_if_exists) {
2163 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2165 /* FIXME: it kinda sucks that this code path potentially scans
2166 * the directory twice due to the weird SetLastError()
2168 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2170 /* The file does not exist, try creating it */
2171 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2173 /* Apparently this error is set if we
2174 * overwrite the dest file
2176 SetLastError (ERROR_ALREADY_EXISTS);
2180 _wapi_set_last_error_from_errno ();
2189 if (!write_file (src_fd, dest_fd, &st, TRUE))
2195 dest_time.modtime = st.st_mtime;
2196 dest_time.actime = st.st_atime;
2197 ret_utime = utime (utf8_dest, &dest_time);
2198 if (ret_utime == -1)
2199 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file [%s] utime failed: %s", __func__, utf8_dest, strerror(errno));
2208 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2213 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: %s is NULL", __func__, arg_name);
2214 SetLastError (ERROR_INVALID_NAME);
2218 utf8_ret = mono_unicode_to_external (arg);
2219 if (utf8_ret == NULL) {
2220 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of %s returned NULL",
2221 __func__, arg_name);
2222 SetLastError (ERROR_INVALID_PARAMETER);
2230 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2231 const gunichar2 *backupFileName, guint32 replaceFlags,
2232 gpointer exclude, gpointer reserved)
2234 int result, backup_fd = -1,replaced_fd = -1;
2235 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2236 struct stat stBackup;
2237 gboolean ret = FALSE;
2239 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2241 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2242 goto replace_cleanup;
2243 if (backupFileName != NULL) {
2244 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2245 goto replace_cleanup;
2248 if (utf8_backupFileName) {
2249 // Open the backup file for read so we can restore the file if an error occurs.
2250 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2251 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2253 goto replace_cleanup;
2256 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2258 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2259 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2260 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2261 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2264 if (replaced_fd == -1)
2265 goto replace_cleanup;
2267 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2270 goto replace_cleanup;
2276 g_free (utf8_replacedFileName);
2277 g_free (utf8_replacementFileName);
2278 g_free (utf8_backupFileName);
2279 if (backup_fd != -1)
2281 if (replaced_fd != -1)
2282 close (replaced_fd);
2288 * @stdhandle: specifies the file descriptor
2290 * Returns a handle for stdin, stdout, or stderr. Always returns the
2291 * same handle for the same @stdhandle.
2293 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2296 static mono_mutex_t stdhandle_mutex;
2298 gpointer GetStdHandle(WapiStdHandle stdhandle)
2300 struct _WapiHandle_file *file_handle;
2307 case STD_INPUT_HANDLE:
2312 case STD_OUTPUT_HANDLE:
2317 case STD_ERROR_HANDLE:
2323 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unknown standard handle type", __func__);
2325 SetLastError (ERROR_INVALID_PARAMETER);
2326 return(INVALID_HANDLE_VALUE);
2329 handle = GINT_TO_POINTER (fd);
2331 mono_os_mutex_lock (&stdhandle_mutex);
2333 ok = mono_w32handle_lookup (handle, MONO_W32HANDLE_CONSOLE,
2334 (gpointer *)&file_handle);
2336 /* Need to create this console handle */
2337 handle = _wapi_stdhandle_create (fd, name);
2339 if (handle == INVALID_HANDLE_VALUE) {
2340 SetLastError (ERROR_NO_MORE_FILES);
2344 /* Add a reference to this handle */
2345 mono_w32handle_ref (handle);
2349 mono_os_mutex_unlock (&stdhandle_mutex);
2356 * @handle: The file handle to read from. The handle must have
2357 * %GENERIC_READ access.
2358 * @buffer: The buffer to store read data in
2359 * @numbytes: The maximum number of bytes to read
2360 * @bytesread: The actual number of bytes read is stored here. This
2361 * value can be zero if the handle is positioned at the end of the
2363 * @overlapped: points to a required %WapiOverlapped structure if
2364 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2367 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2368 * function reads up to @numbytes bytes from the file from the current
2369 * file position, and stores them in @buffer. If there are not enough
2370 * bytes left in the file, just the amount available will be read.
2371 * The actual number of bytes read is stored in @bytesread.
2373 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2374 * file position is ignored and the read position is taken from data
2375 * in the @overlapped structure.
2377 * Return value: %TRUE if the read succeeds (even if no bytes were
2378 * read due to an attempt to read past the end of the file), %FALSE on
2381 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2382 guint32 *bytesread, WapiOverlapped *overlapped)
2384 MonoW32HandleType type;
2386 type = mono_w32handle_get_type (handle);
2388 if(io_ops[type].readfile==NULL) {
2389 SetLastError (ERROR_INVALID_HANDLE);
2393 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2399 * @handle: The file handle to write to. The handle must have
2400 * %GENERIC_WRITE access.
2401 * @buffer: The buffer to read data from.
2402 * @numbytes: The maximum number of bytes to write.
2403 * @byteswritten: The actual number of bytes written is stored here.
2404 * If the handle is positioned at the file end, the length of the file
2405 * is extended. This parameter may be %NULL.
2406 * @overlapped: points to a required %WapiOverlapped structure if
2407 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2410 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2411 * function writes up to @numbytes bytes from @buffer to the file at
2412 * the current file position. If @handle is positioned at the end of
2413 * the file, the file is extended. The actual number of bytes written
2414 * is stored in @byteswritten.
2416 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2417 * file position is ignored and the write position is taken from data
2418 * in the @overlapped structure.
2420 * Return value: %TRUE if the write succeeds, %FALSE on error.
2422 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2423 guint32 *byteswritten, WapiOverlapped *overlapped)
2425 MonoW32HandleType type;
2427 type = mono_w32handle_get_type (handle);
2429 if(io_ops[type].writefile==NULL) {
2430 SetLastError (ERROR_INVALID_HANDLE);
2434 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2440 * @handle: Handle to open file. The handle must have
2441 * %GENERIC_WRITE access.
2443 * Flushes buffers of the file and causes all unwritten data to
2446 * Return value: %TRUE on success, %FALSE otherwise.
2448 gboolean FlushFileBuffers(gpointer handle)
2450 MonoW32HandleType type;
2452 type = mono_w32handle_get_type (handle);
2454 if(io_ops[type].flushfile==NULL) {
2455 SetLastError (ERROR_INVALID_HANDLE);
2459 return(io_ops[type].flushfile (handle));
2464 * @handle: The file handle to set. The handle must have
2465 * %GENERIC_WRITE access.
2467 * Moves the end-of-file position to the current position of the file
2468 * pointer. This function is used to truncate or extend a file.
2470 * Return value: %TRUE on success, %FALSE otherwise.
2472 gboolean SetEndOfFile(gpointer handle)
2474 MonoW32HandleType type;
2476 type = mono_w32handle_get_type (handle);
2478 if (io_ops[type].setendoffile == NULL) {
2479 SetLastError (ERROR_INVALID_HANDLE);
2483 return(io_ops[type].setendoffile (handle));
2488 * @handle: The file handle to set. The handle must have
2489 * %GENERIC_READ or %GENERIC_WRITE access.
2490 * @movedistance: Low 32 bits of a signed value that specifies the
2491 * number of bytes to move the file pointer.
2492 * @highmovedistance: Pointer to the high 32 bits of a signed value
2493 * that specifies the number of bytes to move the file pointer, or
2495 * @method: The starting point for the file pointer move.
2497 * Sets the file pointer of an open file.
2499 * The distance to move the file pointer is calculated from
2500 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2501 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2502 * is the low 32 bits and @highmovedistance a pointer to the high 32
2503 * bits of a 64 bit signed value. A positive distance moves the file
2504 * pointer forward from the position specified by @method; a negative
2505 * distance moves the file pointer backward.
2507 * If the library is compiled without large file support,
2508 * @highmovedistance is ignored and its value is set to zero on a
2509 * successful return.
2511 * Return value: On success, the low 32 bits of the new file pointer.
2512 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2513 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2515 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2516 gint32 *highmovedistance, WapiSeekMethod method)
2518 MonoW32HandleType type;
2520 type = mono_w32handle_get_type (handle);
2522 if (io_ops[type].seek == NULL) {
2523 SetLastError (ERROR_INVALID_HANDLE);
2524 return(INVALID_SET_FILE_POINTER);
2527 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2533 * @handle: The file handle to test.
2535 * Finds the type of file @handle.
2537 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2538 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2539 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2540 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2542 WapiFileType GetFileType(gpointer handle)
2544 MonoW32HandleType type;
2546 type = mono_w32handle_get_type (handle);
2548 if (io_ops[type].getfiletype == NULL) {
2549 SetLastError (ERROR_INVALID_HANDLE);
2550 return(FILE_TYPE_UNKNOWN);
2553 return(io_ops[type].getfiletype ());
2558 * @handle: The file handle to query. The handle must have
2559 * %GENERIC_READ or %GENERIC_WRITE access.
2560 * @highsize: If non-%NULL, the high 32 bits of the file size are
2563 * Retrieves the size of the file @handle.
2565 * If the library is compiled without large file support, @highsize
2566 * has its value set to zero on a successful return.
2568 * Return value: On success, the low 32 bits of the file size. If
2569 * @highsize is non-%NULL then the high 32 bits of the file size are
2570 * stored here. On failure %INVALID_FILE_SIZE is returned.
2572 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2574 MonoW32HandleType type;
2576 type = mono_w32handle_get_type (handle);
2578 if (io_ops[type].getfilesize == NULL) {
2579 SetLastError (ERROR_INVALID_HANDLE);
2580 return(INVALID_FILE_SIZE);
2583 return(io_ops[type].getfilesize (handle, highsize));
2588 * @handle: The file handle to query. The handle must have
2589 * %GENERIC_READ access.
2590 * @create_time: Points to a %WapiFileTime structure to receive the
2591 * number of ticks since the epoch that file was created. May be
2593 * @last_access: Points to a %WapiFileTime structure to receive the
2594 * number of ticks since the epoch when file was last accessed. May be
2596 * @last_write: Points to a %WapiFileTime structure to receive the
2597 * number of ticks since the epoch when file was last written to. May
2600 * Finds the number of ticks since the epoch that the file referenced
2601 * by @handle was created, last accessed and last modified. A tick is
2602 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2605 * Create time isn't recorded on POSIX file systems or reported by
2606 * stat(2), so that time is guessed by returning the oldest of the
2609 * Return value: %TRUE on success, %FALSE otherwise.
2611 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2612 WapiFileTime *last_access, WapiFileTime *last_write)
2614 MonoW32HandleType type;
2616 type = mono_w32handle_get_type (handle);
2618 if (io_ops[type].getfiletime == NULL) {
2619 SetLastError (ERROR_INVALID_HANDLE);
2623 return(io_ops[type].getfiletime (handle, create_time, last_access,
2629 * @handle: The file handle to set. The handle must have
2630 * %GENERIC_WRITE access.
2631 * @create_time: Points to a %WapiFileTime structure that contains the
2632 * number of ticks since the epoch that the file was created. May be
2634 * @last_access: Points to a %WapiFileTime structure that contains the
2635 * number of ticks since the epoch when the file was last accessed.
2637 * @last_write: Points to a %WapiFileTime structure that contains the
2638 * number of ticks since the epoch when the file was last written to.
2641 * Sets the number of ticks since the epoch that the file referenced
2642 * by @handle was created, last accessed or last modified. A tick is
2643 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2646 * Create time isn't recorded on POSIX file systems, and is ignored.
2648 * Return value: %TRUE on success, %FALSE otherwise.
2650 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2651 const WapiFileTime *last_access,
2652 const WapiFileTime *last_write)
2654 MonoW32HandleType type;
2656 type = mono_w32handle_get_type (handle);
2658 if (io_ops[type].setfiletime == NULL) {
2659 SetLastError (ERROR_INVALID_HANDLE);
2663 return(io_ops[type].setfiletime (handle, create_time, last_access,
2667 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2668 * January 1 1601 GMT
2671 #define TICKS_PER_MILLISECOND 10000L
2672 #define TICKS_PER_SECOND 10000000L
2673 #define TICKS_PER_MINUTE 600000000L
2674 #define TICKS_PER_HOUR 36000000000LL
2675 #define TICKS_PER_DAY 864000000000LL
2677 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2679 static const guint16 mon_yday[2][13]={
2680 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2681 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2685 * FileTimeToSystemTime:
2686 * @file_time: Points to a %WapiFileTime structure that contains the
2687 * number of ticks to convert.
2688 * @system_time: Points to a %WapiSystemTime structure to receive the
2691 * Converts a tick count into broken-out time values.
2693 * Return value: %TRUE on success, %FALSE otherwise.
2695 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2696 WapiSystemTime *system_time)
2698 gint64 file_ticks, totaldays, rem, y;
2701 if(system_time==NULL) {
2702 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: system_time NULL", __func__);
2704 SetLastError (ERROR_INVALID_PARAMETER);
2708 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2709 file_time->dwLowDateTime;
2711 /* Really compares if file_ticks>=0x8000000000000000
2712 * (LLONG_MAX+1) but we're working with a signed value for the
2713 * year and day calculation to work later
2716 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file_time too big", __func__);
2718 SetLastError (ERROR_INVALID_PARAMETER);
2722 totaldays=(file_ticks / TICKS_PER_DAY);
2723 rem = file_ticks % TICKS_PER_DAY;
2724 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2726 system_time->wHour=rem/TICKS_PER_HOUR;
2727 rem %= TICKS_PER_HOUR;
2728 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2730 system_time->wMinute = rem / TICKS_PER_MINUTE;
2731 rem %= TICKS_PER_MINUTE;
2732 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2735 system_time->wSecond = rem / TICKS_PER_SECOND;
2736 rem %= TICKS_PER_SECOND;
2737 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2740 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2741 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Milliseconds: %d", __func__,
2742 system_time->wMilliseconds);
2744 /* January 1, 1601 was a Monday, according to Emacs calendar */
2745 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2746 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2748 /* This algorithm to find year and month given days from epoch
2753 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2754 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2756 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2757 /* Guess a corrected year, assuming 365 days per year */
2758 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2759 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld yg: %lld y: %lld", __func__,
2762 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2763 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2765 /* Adjust days and y to match the guessed year. */
2766 totaldays -= ((yg - y) * 365
2767 + LEAPS_THRU_END_OF (yg - 1)
2768 - LEAPS_THRU_END_OF (y - 1));
2769 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2771 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: y: %lld", __func__, y);
2774 system_time->wYear = y;
2775 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Year: %d", __func__, system_time->wYear);
2777 ip = mon_yday[isleap(y)];
2779 for(y=11; totaldays < ip[y]; --y) {
2783 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2785 system_time->wMonth = y + 1;
2786 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Month: %d", __func__, system_time->wMonth);
2788 system_time->wDay = totaldays + 1;
2789 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day: %d", __func__, system_time->wDay);
2794 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2796 struct _WapiHandle_find find_handle = {0};
2798 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2801 if (pattern == NULL) {
2802 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: pattern is NULL", __func__);
2804 SetLastError (ERROR_PATH_NOT_FOUND);
2805 return(INVALID_HANDLE_VALUE);
2808 utf8_pattern = mono_unicode_to_external (pattern);
2809 if (utf8_pattern == NULL) {
2810 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2812 SetLastError (ERROR_INVALID_NAME);
2813 return(INVALID_HANDLE_VALUE);
2816 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for [%s]", __func__, utf8_pattern);
2818 /* Figure out which bit of the pattern is the directory */
2819 dir_part = _wapi_dirname (utf8_pattern);
2820 entry_part = _wapi_basename (utf8_pattern);
2823 /* Don't do this check for now, it breaks if directories
2824 * really do have metachars in their names (see bug 58116).
2825 * FIXME: Figure out a better solution to keep some checks...
2827 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2828 SetLastError (ERROR_INVALID_NAME);
2830 g_free (entry_part);
2831 g_free (utf8_pattern);
2832 return(INVALID_HANDLE_VALUE);
2836 /* The pattern can specify a directory or a set of files.
2838 * The pattern can have wildcard characters ? and *, but only
2839 * in the section after the last directory delimiter. (Return
2840 * ERROR_INVALID_NAME if there are wildcards in earlier path
2841 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2842 * means "match one character", "??" seems to mean "match one
2843 * or two characters", "???" seems to mean "match one, two or
2844 * three characters", etc. Windows will also try and match
2845 * the mangled "short name" of files, so 8 character patterns
2846 * with wildcards will show some surprising results.
2848 * All the written documentation I can find says that '?'
2849 * should only match one character, and doesn't mention '??',
2850 * '???' etc. I'm going to assume that the strict behaviour
2851 * (ie '???' means three and only three characters) is the
2852 * correct one, because that lets me use fnmatch(3) rather
2853 * than mess around with regexes.
2856 find_handle.namelist = NULL;
2857 result = _wapi_io_scandir (dir_part, entry_part,
2858 &find_handle.namelist);
2861 /* No files, which windows seems to call
2864 SetLastError (ERROR_FILE_NOT_FOUND);
2865 g_free (utf8_pattern);
2866 g_free (entry_part);
2868 return (INVALID_HANDLE_VALUE);
2872 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2873 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: scandir error: %s", __func__, g_strerror (errno));
2874 g_free (utf8_pattern);
2875 g_free (entry_part);
2877 return (INVALID_HANDLE_VALUE);
2880 g_free (utf8_pattern);
2881 g_free (entry_part);
2883 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Got %d matches", __func__, result);
2885 find_handle.dir_part = dir_part;
2886 find_handle.num = result;
2887 find_handle.count = 0;
2889 handle = mono_w32handle_new (MONO_W32HANDLE_FIND, &find_handle);
2890 if (handle == INVALID_HANDLE_VALUE) {
2891 g_warning ("%s: error creating find handle", __func__);
2893 g_free (entry_part);
2894 g_free (utf8_pattern);
2895 SetLastError (ERROR_GEN_FAILURE);
2897 return(INVALID_HANDLE_VALUE);
2900 if (handle != INVALID_HANDLE_VALUE &&
2901 !FindNextFile (handle, find_data)) {
2903 SetLastError (ERROR_NO_MORE_FILES);
2904 handle = INVALID_HANDLE_VALUE;
2910 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2912 struct _WapiHandle_find *find_handle;
2914 struct stat buf, linkbuf;
2917 gchar *utf8_filename, *utf8_basename;
2918 gunichar2 *utf16_basename;
2921 gboolean ret = FALSE;
2923 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FIND,
2924 (gpointer *)&find_handle);
2926 g_warning ("%s: error looking up find handle %p", __func__,
2928 SetLastError (ERROR_INVALID_HANDLE);
2932 mono_w32handle_lock_handle (handle);
2935 if (find_handle->count >= find_handle->num) {
2936 SetLastError (ERROR_NO_MORE_FILES);
2940 /* stat next match */
2942 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2944 result = _wapi_stat (filename, &buf);
2945 if (result == -1 && errno == ENOENT) {
2946 /* Might be a dangling symlink */
2947 result = _wapi_lstat (filename, &buf);
2951 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: stat failed: %s", __func__, filename);
2957 #ifndef __native_client__
2958 result = _wapi_lstat (filename, &linkbuf);
2960 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lstat failed: %s", __func__, filename);
2967 utf8_filename = mono_utf8_from_external (filename);
2968 if (utf8_filename == NULL) {
2969 /* We couldn't turn this filename into utf8 (eg the
2970 * encoding of the name wasn't convertible), so just
2973 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2980 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Found [%s]", __func__, utf8_filename);
2982 /* fill data block */
2984 if (buf.st_mtime < buf.st_ctime)
2985 create_time = buf.st_mtime;
2987 create_time = buf.st_ctime;
2989 #ifdef __native_client__
2990 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, NULL);
2992 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2995 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2996 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2997 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2999 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3000 find_data->nFileSizeHigh = 0;
3001 find_data->nFileSizeLow = 0;
3003 find_data->nFileSizeHigh = buf.st_size >> 32;
3004 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3007 find_data->dwReserved0 = 0;
3008 find_data->dwReserved1 = 0;
3010 utf8_basename = _wapi_basename (utf8_filename);
3011 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
3013 if(utf16_basename==NULL) {
3014 g_free (utf8_basename);
3015 g_free (utf8_filename);
3020 /* utf16 is 2 * utf8 */
3023 memset (find_data->cFileName, '\0', (MAX_PATH*2));
3025 /* Truncating a utf16 string like this might leave the last
3028 memcpy (find_data->cFileName, utf16_basename,
3029 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3031 find_data->cAlternateFileName [0] = 0; /* not used */
3033 g_free (utf8_basename);
3034 g_free (utf8_filename);
3035 g_free (utf16_basename);
3038 mono_w32handle_unlock_handle (handle);
3045 * @wapi_handle: the find handle to close.
3047 * Closes find handle @wapi_handle
3049 * Return value: %TRUE on success, %FALSE otherwise.
3051 gboolean FindClose (gpointer handle)
3053 struct _WapiHandle_find *find_handle;
3056 if (handle == NULL) {
3057 SetLastError (ERROR_INVALID_HANDLE);
3061 ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FIND,
3062 (gpointer *)&find_handle);
3064 g_warning ("%s: error looking up find handle %p", __func__,
3066 SetLastError (ERROR_INVALID_HANDLE);
3070 mono_w32handle_lock_handle (handle);
3072 g_strfreev (find_handle->namelist);
3073 g_free (find_handle->dir_part);
3075 mono_w32handle_unlock_handle (handle);
3077 mono_w32handle_unref (handle);
3084 * @name: a pointer to a NULL-terminated unicode string, that names
3085 * the directory to be created.
3086 * @security: ignored for now
3088 * Creates directory @name
3090 * Return value: %TRUE on success, %FALSE otherwise.
3092 gboolean CreateDirectory (const gunichar2 *name,
3093 WapiSecurityAttributes *security)
3099 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3101 SetLastError (ERROR_INVALID_NAME);
3105 utf8_name = mono_unicode_to_external (name);
3106 if (utf8_name == NULL) {
3107 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3109 SetLastError (ERROR_INVALID_NAME);
3113 result = _wapi_mkdir (utf8_name, 0777);
3120 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3127 * @name: a pointer to a NULL-terminated unicode string, that names
3128 * the directory to be removed.
3130 * Removes directory @name
3132 * Return value: %TRUE on success, %FALSE otherwise.
3134 gboolean RemoveDirectory (const gunichar2 *name)
3140 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3142 SetLastError (ERROR_INVALID_NAME);
3146 utf8_name = mono_unicode_to_external (name);
3147 if (utf8_name == NULL) {
3148 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3150 SetLastError (ERROR_INVALID_NAME);
3154 result = _wapi_rmdir (utf8_name);
3156 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3167 * GetFileAttributes:
3168 * @name: a pointer to a NULL-terminated unicode filename.
3170 * Gets the attributes for @name;
3172 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3174 guint32 GetFileAttributes (const gunichar2 *name)
3177 struct stat buf, linkbuf;
3182 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3184 SetLastError (ERROR_INVALID_NAME);
3188 utf8_name = mono_unicode_to_external (name);
3189 if (utf8_name == NULL) {
3190 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3192 SetLastError (ERROR_INVALID_PARAMETER);
3193 return (INVALID_FILE_ATTRIBUTES);
3196 result = _wapi_stat (utf8_name, &buf);
3197 if (result == -1 && errno == ENOENT) {
3198 /* Might be a dangling symlink... */
3199 result = _wapi_lstat (utf8_name, &buf);
3203 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3205 return (INVALID_FILE_ATTRIBUTES);
3208 #ifndef __native_client__
3209 result = _wapi_lstat (utf8_name, &linkbuf);
3211 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3213 return (INVALID_FILE_ATTRIBUTES);
3217 #ifdef __native_client__
3218 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, NULL);
3220 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3229 * GetFileAttributesEx:
3230 * @name: a pointer to a NULL-terminated unicode filename.
3231 * @level: must be GetFileExInfoStandard
3232 * @info: pointer to a WapiFileAttributesData structure
3234 * Gets attributes, size and filetimes for @name;
3236 * Return value: %TRUE on success, %FALSE on failure
3238 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3241 WapiFileAttributesData *data;
3243 struct stat buf, linkbuf;
3247 if (level != GetFileExInfoStandard) {
3248 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: info level %d not supported.", __func__,
3251 SetLastError (ERROR_INVALID_PARAMETER);
3256 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3258 SetLastError (ERROR_INVALID_NAME);
3262 utf8_name = mono_unicode_to_external (name);
3263 if (utf8_name == NULL) {
3264 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3266 SetLastError (ERROR_INVALID_PARAMETER);
3270 result = _wapi_stat (utf8_name, &buf);
3271 if (result == -1 && errno == ENOENT) {
3272 /* Might be a dangling symlink... */
3273 result = _wapi_lstat (utf8_name, &buf);
3277 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3282 result = _wapi_lstat (utf8_name, &linkbuf);
3284 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3289 /* fill data block */
3291 data = (WapiFileAttributesData *)info;
3293 if (buf.st_mtime < buf.st_ctime)
3294 create_time = buf.st_mtime;
3296 create_time = buf.st_ctime;
3298 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3304 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3305 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3306 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3308 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3309 data->nFileSizeHigh = 0;
3310 data->nFileSizeLow = 0;
3313 data->nFileSizeHigh = buf.st_size >> 32;
3314 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3322 * @name: name of file
3323 * @attrs: attributes to set
3325 * Changes the attributes on a named file.
3327 * Return value: %TRUE on success, %FALSE on failure.
3329 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3331 /* FIXME: think of something clever to do on unix */
3337 * Currently we only handle one *internal* case, with a value that is
3338 * not standard: 0x80000000, which means `set executable bit'
3342 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3344 SetLastError (ERROR_INVALID_NAME);
3348 utf8_name = mono_unicode_to_external (name);
3349 if (utf8_name == NULL) {
3350 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3352 SetLastError (ERROR_INVALID_NAME);
3356 result = _wapi_stat (utf8_name, &buf);
3357 if (result == -1 && errno == ENOENT) {
3358 /* Might be a dangling symlink... */
3359 result = _wapi_lstat (utf8_name, &buf);
3363 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3368 /* Contrary to the documentation, ms allows NORMAL to be
3369 * specified along with other attributes, so dont bother to
3370 * catch that case here.
3372 if (attrs & FILE_ATTRIBUTE_READONLY) {
3373 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWUSR | S_IWOTH | S_IWGRP));
3375 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWUSR);
3378 /* Ignore the other attributes for now */
3380 if (attrs & 0x80000000){
3381 mode_t exec_mask = 0;
3383 if ((buf.st_mode & S_IRUSR) != 0)
3384 exec_mask |= S_IXUSR;
3386 if ((buf.st_mode & S_IRGRP) != 0)
3387 exec_mask |= S_IXGRP;
3389 if ((buf.st_mode & S_IROTH) != 0)
3390 exec_mask |= S_IXOTH;
3392 result = chmod (utf8_name, buf.st_mode | exec_mask);
3394 /* Don't bother to reset executable (might need to change this
3404 * GetCurrentDirectory
3405 * @length: size of the buffer
3406 * @buffer: pointer to buffer that recieves path
3408 * Retrieves the current directory for the current process.
3410 * Return value: number of characters in buffer on success, zero on failure
3412 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3414 gunichar2 *utf16_path;
3418 #ifdef __native_client__
3419 gchar *path = g_get_current_dir ();
3420 if (length < strlen(path) + 1 || path == NULL)
3422 memcpy (buffer, path, strlen(path) + 1);
3424 if (getcwd ((char*)buffer, length) == NULL) {
3425 if (errno == ERANGE) { /*buffer length is not big enough */
3426 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*/
3429 utf16_path = mono_unicode_from_external (path, &bytes);
3430 g_free (utf16_path);
3434 _wapi_set_last_error_from_errno ();
3439 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3440 count = (bytes/2)+1;
3441 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3443 /* Add the terminator */
3444 memset (buffer, '\0', bytes+2);
3445 memcpy (buffer, utf16_path, bytes);
3447 g_free (utf16_path);
3453 * SetCurrentDirectory
3454 * @path: path to new directory
3456 * Changes the directory path for the current process.
3458 * Return value: %TRUE on success, %FALSE on failure.
3460 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3466 SetLastError (ERROR_INVALID_PARAMETER);
3470 utf8_path = mono_unicode_to_external (path);
3471 if (_wapi_chdir (utf8_path) != 0) {
3472 _wapi_set_last_error_from_errno ();
3482 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3483 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3485 struct _WapiHandle_file pipe_read_handle = {0};
3486 struct _WapiHandle_file pipe_write_handle = {0};
3487 gpointer read_handle;
3488 gpointer write_handle;
3492 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Creating pipe", __func__);
3496 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error creating pipe: %s", __func__,
3499 _wapi_set_last_error_from_errno ();
3503 if (filedes[0] >= mono_w32handle_fd_reserve ||
3504 filedes[1] >= mono_w32handle_fd_reserve) {
3505 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
3507 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3515 /* filedes[0] is open for reading, filedes[1] for writing */
3517 pipe_read_handle.fd = filedes [0];
3518 pipe_read_handle.fileaccess = GENERIC_READ;
3519 read_handle = mono_w32handle_new_fd (MONO_W32HANDLE_PIPE, filedes[0],
3521 if (read_handle == INVALID_HANDLE_VALUE) {
3522 g_warning ("%s: error creating pipe read handle", __func__);
3525 SetLastError (ERROR_GEN_FAILURE);
3530 pipe_write_handle.fd = filedes [1];
3531 pipe_write_handle.fileaccess = GENERIC_WRITE;
3532 write_handle = mono_w32handle_new_fd (MONO_W32HANDLE_PIPE, filedes[1],
3533 &pipe_write_handle);
3534 if (write_handle == INVALID_HANDLE_VALUE) {
3535 g_warning ("%s: error creating pipe write handle", __func__);
3536 mono_w32handle_unref (read_handle);
3540 SetLastError (ERROR_GEN_FAILURE);
3545 *readpipe = read_handle;
3546 *writepipe = write_handle;
3548 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning pipe: read handle %p, write handle %p",
3549 __func__, read_handle, write_handle);
3554 #ifdef HAVE_GETFSSTAT
3555 /* Darwin has getfsstat */
3556 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3558 struct statfs *stats;
3561 glong length, total = 0;
3563 n = getfsstat (NULL, 0, MNT_NOWAIT);
3566 size = n * sizeof (struct statfs);
3567 stats = (struct statfs *) g_malloc (size);
3570 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3574 for (i = 0; i < n; i++){
3575 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3576 if (total + length < len){
3577 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3578 buf [total+length] = 0;
3581 total += length + 1;
3590 /* In-place octal sequence replacement */
3592 unescape_octal (gchar *str)
3601 while (*rptr != '\0') {
3602 if (*rptr == '\\') {
3605 c = (*(rptr++) - '0') << 6;
3606 c += (*(rptr++) - '0') << 3;
3607 c += *(rptr++) - '0';
3609 } else if (wptr != rptr) {
3617 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3620 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3621 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3622 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3627 guint32 buffer_index;
3628 guint32 mountpoint_index;
3629 guint32 field_number;
3630 guint32 allocated_size;
3631 guint32 fsname_index;
3632 guint32 fstype_index;
3633 gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3634 gchar *mountpoint_allocated;
3635 gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3636 gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3637 gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3640 gboolean check_mount_source;
3641 } LinuxMountInfoParseState;
3643 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3644 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3645 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3646 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3648 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3652 LinuxMountInfoParseState state;
3653 gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3655 memset (buf, 0, len * sizeof (gunichar2));
3656 fd = open ("/proc/self/mountinfo", O_RDONLY);
3658 parser = GetLogicalDriveStrings_MountInfo;
3660 fd = open ("/proc/mounts", O_RDONLY);
3662 parser = GetLogicalDriveStrings_Mounts;
3666 ret = GetLogicalDriveStrings_Mtab (len, buf);
3670 memset (&state, 0, sizeof (LinuxMountInfoParseState));
3671 state.field_number = 1;
3672 state.delimiter = ' ';
3674 while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3675 state.buffer_index = 0;
3677 while ((*parser)(len, buf, &state)) {
3678 if (state.buffer [state.buffer_index] == '\n') {
3679 gboolean quit = add_drive_string (len, buf, &state);
3680 state.field_number = 1;
3681 state.buffer_index++;
3682 if (state.mountpoint_allocated) {
3683 g_free (state.mountpoint_allocated);
3684 state.mountpoint_allocated = NULL;
3701 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3705 if (state->field_number == 1)
3706 state->check_mount_source = TRUE;
3708 while (state->buffer_index < (guint32)state->nbytes) {
3709 if (state->buffer [state->buffer_index] == state->delimiter) {
3710 state->field_number++;
3711 switch (state->field_number) {
3713 state->mountpoint_index = 0;
3717 if (state->mountpoint_allocated)
3718 state->mountpoint_allocated [state->mountpoint_index] = 0;
3720 state->mountpoint [state->mountpoint_index] = 0;
3724 ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3726 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3728 state->buffer_index = state->nbytes;
3731 state->buffer_index++;
3733 } else if (state->buffer [state->buffer_index] == '\n')
3736 switch (state->field_number) {
3738 if (state->check_mount_source) {
3739 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3740 /* We can ignore the rest, it's a device
3742 state->check_mount_source = FALSE;
3743 state->fsname [state->fsname_index++] = '/';
3746 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3747 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3752 append_to_mountpoint (state);
3756 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3757 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3761 state->buffer_index++;
3767 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3769 while (state->buffer_index < (guint32)state->nbytes) {
3770 if (state->buffer [state->buffer_index] == state->delimiter) {
3771 state->field_number++;
3772 switch (state->field_number) {
3774 state->mountpoint_index = 0;
3778 if (state->mountpoint_allocated)
3779 state->mountpoint_allocated [state->mountpoint_index] = 0;
3781 state->mountpoint [state->mountpoint_index] = 0;
3785 state->delimiter = '-';
3789 state->delimiter = ' ';
3793 state->check_mount_source = TRUE;
3796 state->buffer_index++;
3798 } else if (state->buffer [state->buffer_index] == '\n')
3801 switch (state->field_number) {
3803 append_to_mountpoint (state);
3807 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3808 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3812 if (state->check_mount_source) {
3813 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3814 /* We can ignore the rest, it's a device
3816 state->check_mount_source = FALSE;
3817 state->fsname [state->fsname_index++] = '/';
3820 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3821 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3826 state->buffer_index++;
3833 append_to_mountpoint (LinuxMountInfoParseState *state)
3835 gchar ch = state->buffer [state->buffer_index];
3836 if (state->mountpoint_allocated) {
3837 if (state->mountpoint_index >= state->allocated_size) {
3838 guint32 newsize = (state->allocated_size << 1) + 1;
3839 gchar *newbuf = (gchar *)g_malloc0 (newsize * sizeof (gchar));
3841 memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3842 g_free (state->mountpoint_allocated);
3843 state->mountpoint_allocated = newbuf;
3844 state->allocated_size = newsize;
3846 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3848 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3849 state->allocated_size = (state->mountpoint_index << 1) + 1;
3850 state->mountpoint_allocated = (gchar *)g_malloc0 (state->allocated_size * sizeof (gchar));
3851 memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3852 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3854 state->mountpoint [state->mountpoint_index++] = ch;
3859 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3861 gboolean quit = FALSE;
3862 gboolean ignore_entry;
3864 if (state->fsname_index == 1 && state->fsname [0] == '/')
3865 ignore_entry = FALSE;
3866 else if (memcmp ("overlay", state->fsname, state->fsname_index) == 0 ||
3867 memcmp ("aufs", state->fstype, state->fstype_index) == 0) {
3868 /* Don't ignore overlayfs and aufs - these might be used on Docker
3869 * (https://bugzilla.xamarin.com/show_bug.cgi?id=31021) */
3870 ignore_entry = FALSE;
3871 } else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0) {
3872 ignore_entry = TRUE;
3873 } else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3874 /* Ignore GNOME's gvfs */
3875 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3876 ignore_entry = TRUE;
3878 ignore_entry = FALSE;
3879 } else if (state->fstype_index == 3 && memcmp ("nfs", state->fstype, state->fstype_index) == 0)
3880 ignore_entry = FALSE;
3882 ignore_entry = TRUE;
3884 if (!ignore_entry) {
3887 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3889 unescape_octal (mountpoint);
3890 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3891 if (state->total + length + 1 > len) {
3893 state->total = len * 2;
3896 memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3897 state->total += length;
3901 state->fsname_index = 0;
3902 state->fstype_index = 0;
3908 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3910 return GetLogicalDriveStrings_Mtab (len, buf);
3914 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3917 gunichar2 *ptr, *dir;
3918 glong length, total = 0;
3922 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3927 /* Sigh, mntent and friends don't work well.
3928 * It stops on the first line that doesn't begin with a '/'.
3929 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3930 fp = fopen ("/etc/mtab", "rt");
3932 fp = fopen ("/etc/mnttab", "rt");
3938 while (fgets (buffer, 512, fp) != NULL) {
3942 splitted = g_strsplit (buffer, " ", 0);
3943 if (!*splitted || !*(splitted + 1)) {
3944 g_strfreev (splitted);
3948 unescape_octal (*(splitted + 1));
3949 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3950 g_strfreev (splitted);
3951 if (total + length + 1 > len) {
3954 return len * 2; /* guess */
3957 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3959 total += length + 1;
3964 /* Commented out, does not work with my mtab!!! - Gonz */
3965 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3969 gunichar2 *ptr, *dir;
3970 glong len, total = 0;
3973 fp = setmntent ("/etc/mtab", "rt");
3975 fp = setmntent ("/etc/mnttab", "rt");
3981 while ((mnt = getmntent (fp)) != NULL) {
3982 g_print ("GOT %s\n", mnt->mnt_dir);
3983 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3984 if (total + len + 1 > len) {
3985 return len * 2; /* guess */
3988 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
4000 #if defined(HAVE_STATVFS) || defined(HAVE_STATFS)
4001 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4002 WapiULargeInteger *total_number_of_bytes,
4003 WapiULargeInteger *total_number_of_free_bytes)
4006 struct statvfs fsstat;
4007 #elif defined(HAVE_STATFS)
4008 struct statfs fsstat;
4010 gboolean isreadonly;
4011 gchar *utf8_path_name;
4013 unsigned long block_size;
4015 if (path_name == NULL) {
4016 utf8_path_name = g_strdup (g_get_current_dir());
4017 if (utf8_path_name == NULL) {
4018 SetLastError (ERROR_DIRECTORY);
4023 utf8_path_name = mono_unicode_to_external (path_name);
4024 if (utf8_path_name == NULL) {
4025 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4027 SetLastError (ERROR_INVALID_NAME);
4034 ret = statvfs (utf8_path_name, &fsstat);
4035 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
4036 block_size = fsstat.f_frsize;
4037 #elif defined(HAVE_STATFS)
4038 ret = statfs (utf8_path_name, &fsstat);
4039 #if defined (MNT_RDONLY)
4040 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
4041 #elif defined (MS_RDONLY)
4042 isreadonly = ((fsstat.f_flags & MS_RDONLY) == MS_RDONLY);
4044 block_size = fsstat.f_bsize;
4046 } while(ret == -1 && errno == EINTR);
4048 g_free(utf8_path_name);
4051 _wapi_set_last_error_from_errno ();
4052 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: statvfs failed: %s", __func__, strerror (errno));
4056 /* total number of free bytes for non-root */
4057 if (free_bytes_avail != NULL) {
4059 free_bytes_avail->QuadPart = 0;
4062 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
4066 /* total number of bytes available for non-root */
4067 if (total_number_of_bytes != NULL) {
4068 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
4071 /* total number of bytes available for root */
4072 if (total_number_of_free_bytes != NULL) {
4074 total_number_of_free_bytes->QuadPart = 0;
4077 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
4084 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4085 WapiULargeInteger *total_number_of_bytes,
4086 WapiULargeInteger *total_number_of_free_bytes)
4088 if (free_bytes_avail != NULL) {
4089 free_bytes_avail->QuadPart = (guint64) -1;
4092 if (total_number_of_bytes != NULL) {
4093 total_number_of_bytes->QuadPart = (guint64) -1;
4096 if (total_number_of_free_bytes != NULL) {
4097 total_number_of_free_bytes->QuadPart = (guint64) -1;
4105 * General Unix support
4110 const long fstypeid;
4112 const gchar* fstype;
4115 static _wapi_drive_type _wapi_drive_types[] = {
4117 { DRIVE_REMOTE, "afp" },
4118 { DRIVE_REMOTE, "autofs" },
4119 { DRIVE_CDROM, "cddafs" },
4120 { DRIVE_CDROM, "cd9660" },
4121 { DRIVE_RAMDISK, "devfs" },
4122 { DRIVE_FIXED, "exfat" },
4123 { DRIVE_RAMDISK, "fdesc" },
4124 { DRIVE_REMOTE, "ftp" },
4125 { DRIVE_FIXED, "hfs" },
4126 { DRIVE_FIXED, "msdos" },
4127 { DRIVE_REMOTE, "nfs" },
4128 { DRIVE_FIXED, "ntfs" },
4129 { DRIVE_REMOTE, "smbfs" },
4130 { DRIVE_FIXED, "udf" },
4131 { DRIVE_REMOTE, "webdav" },
4132 { DRIVE_UNKNOWN, NULL }
4134 { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
4135 { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
4136 { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
4137 { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
4138 { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
4139 { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
4140 { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
4141 { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
4142 { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
4143 { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
4144 { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
4145 { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
4146 { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
4147 { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
4148 { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
4149 { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
4150 { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
4151 { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4152 { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4153 { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4154 { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4155 { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4156 { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4157 { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4158 { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4159 { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4160 { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4161 { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4162 { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4163 { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4164 { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4165 { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4166 { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4167 { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4168 { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4169 { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4170 { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4171 { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4172 { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4173 { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4174 { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4175 { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4176 { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4177 { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4178 { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4179 { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4180 { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4181 { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4182 { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4183 { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4184 { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4185 { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4186 { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4187 { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4188 { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4189 { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4190 { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4191 { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4192 { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4193 { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4194 { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4195 { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4196 { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4197 { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4198 { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4199 { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4200 { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4201 { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4202 { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4203 { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4204 { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4205 { DRIVE_UNKNOWN, 0, NULL}
4207 { DRIVE_RAMDISK, "ramfs" },
4208 { DRIVE_RAMDISK, "tmpfs" },
4209 { DRIVE_RAMDISK, "proc" },
4210 { DRIVE_RAMDISK, "sysfs" },
4211 { DRIVE_RAMDISK, "debugfs" },
4212 { DRIVE_RAMDISK, "devpts" },
4213 { DRIVE_RAMDISK, "securityfs" },
4214 { DRIVE_CDROM, "iso9660" },
4215 { DRIVE_FIXED, "ext2" },
4216 { DRIVE_FIXED, "ext3" },
4217 { DRIVE_FIXED, "ext4" },
4218 { DRIVE_FIXED, "sysv" },
4219 { DRIVE_FIXED, "reiserfs" },
4220 { DRIVE_FIXED, "ufs" },
4221 { DRIVE_FIXED, "vfat" },
4222 { DRIVE_FIXED, "msdos" },
4223 { DRIVE_FIXED, "udf" },
4224 { DRIVE_FIXED, "hfs" },
4225 { DRIVE_FIXED, "hpfs" },
4226 { DRIVE_FIXED, "qnx4" },
4227 { DRIVE_FIXED, "ntfs" },
4228 { DRIVE_FIXED, "ntfs-3g" },
4229 { DRIVE_REMOTE, "smbfs" },
4230 { DRIVE_REMOTE, "fuse" },
4231 { DRIVE_REMOTE, "nfs" },
4232 { DRIVE_REMOTE, "nfs4" },
4233 { DRIVE_REMOTE, "cifs" },
4234 { DRIVE_REMOTE, "ncpfs" },
4235 { DRIVE_REMOTE, "coda" },
4236 { DRIVE_REMOTE, "afs" },
4237 { DRIVE_UNKNOWN, NULL }
4242 static guint32 _wapi_get_drive_type(long f_type)
4244 _wapi_drive_type *current;
4246 current = &_wapi_drive_types[0];
4247 while (current->drive_type != DRIVE_UNKNOWN) {
4248 if (current->fstypeid == f_type)
4249 return current->drive_type;
4253 return DRIVE_UNKNOWN;
4256 static guint32 _wapi_get_drive_type(const gchar* fstype)
4258 _wapi_drive_type *current;
4260 current = &_wapi_drive_types[0];
4261 while (current->drive_type != DRIVE_UNKNOWN) {
4262 if (strcmp (current->fstype, fstype) == 0)
4268 return current->drive_type;
4272 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4274 GetDriveTypeFromPath (const char *utf8_root_path_name)
4278 if (statfs (utf8_root_path_name, &buf) == -1)
4279 return DRIVE_UNKNOWN;
4281 return _wapi_get_drive_type (buf.f_fstypename);
4283 return _wapi_get_drive_type (buf.f_type);
4288 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4295 fp = fopen ("/etc/mtab", "rt");
4297 fp = fopen ("/etc/mnttab", "rt");
4299 return(DRIVE_UNKNOWN);
4302 drive_type = DRIVE_NO_ROOT_DIR;
4303 while (fgets (buffer, 512, fp) != NULL) {
4304 splitted = g_strsplit (buffer, " ", 0);
4305 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4306 g_strfreev (splitted);
4310 /* compare given root_path_name with the one from mtab,
4311 if length of utf8_root_path_name is zero it must be the root dir */
4312 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4313 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4314 drive_type = _wapi_get_drive_type (*(splitted + 2));
4315 /* it is possible this path might be mounted again with
4316 a known type...keep looking */
4317 if (drive_type != DRIVE_UNKNOWN) {
4318 g_strfreev (splitted);
4323 g_strfreev (splitted);
4331 guint32 GetDriveType(const gunichar2 *root_path_name)
4333 gchar *utf8_root_path_name;
4336 if (root_path_name == NULL) {
4337 utf8_root_path_name = g_strdup (g_get_current_dir());
4338 if (utf8_root_path_name == NULL) {
4339 return(DRIVE_NO_ROOT_DIR);
4343 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4344 if (utf8_root_path_name == NULL) {
4345 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4346 return(DRIVE_NO_ROOT_DIR);
4349 /* strip trailing slash for compare below */
4350 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4351 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4354 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4355 g_free (utf8_root_path_name);
4357 return (drive_type);
4360 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__) || defined(__FreeBSD_kernel__)
4362 get_fstypename (gchar *utfpath)
4364 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4367 _wapi_drive_type *current;
4369 if (statfs (utfpath, &stat) == -1)
4372 return g_strdup (stat.f_fstypename);
4374 current = &_wapi_drive_types[0];
4375 while (current->drive_type != DRIVE_UNKNOWN) {
4376 if (stat.f_type == current->fstypeid)
4377 return g_strdup (current->fstype);
4387 /* Linux has struct statfs which has a different layout */
4389 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4393 gboolean status = FALSE;
4396 // We only support getting the file system type
4397 if (fsbuffer == NULL)
4400 utfpath = mono_unicode_to_external (path);
4401 if ((fstypename = get_fstypename (utfpath)) != NULL){
4402 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4403 if (ret != NULL && len < fsbuffersize){
4404 memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4410 g_free (fstypename);
4418 _wapi_io_init (void)
4420 mono_os_mutex_init (&stdhandle_mutex);
4421 mono_os_mutex_init (&file_share_mutex);
4423 mono_w32handle_register_ops (MONO_W32HANDLE_FILE, &_wapi_file_ops);
4424 mono_w32handle_register_ops (MONO_W32HANDLE_CONSOLE, &_wapi_console_ops);
4425 mono_w32handle_register_ops (MONO_W32HANDLE_FIND, &_wapi_find_ops);
4426 mono_w32handle_register_ops (MONO_W32HANDLE_PIPE, &_wapi_pipe_ops);
4428 /* mono_w32handle_register_capabilities (MONO_W32HANDLE_FILE, */
4429 /* MONO_W32HANDLE_CAP_WAIT); */
4430 /* mono_w32handle_register_capabilities (MONO_W32HANDLE_CONSOLE, */
4431 /* MONO_W32HANDLE_CAP_WAIT); */
4433 if (g_getenv ("MONO_STRICT_IO_EMULATION"))
4434 lock_while_writing = TRUE;
4438 _wapi_io_cleanup (void)
4440 mono_os_mutex_destroy (&file_share_mutex);
4442 if (file_share_hash)
4443 g_hash_table_destroy (file_share_hash);