[io-layer] Move file_share_hash to io.c
[mono-project.git] / mono / io-layer / io.c
blob13dd00f9220906e60bfa4f60ce20522f4d5d9637
1 /*
2 * io.c: File, console and find handles
4 * Author:
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.
13 #include <config.h>
14 #include <glib.h>
15 #include <fcntl.h>
16 #include <unistd.h>
17 #include <errno.h>
18 #include <string.h>
19 #include <sys/stat.h>
20 #ifdef HAVE_SYS_STATVFS_H
21 #include <sys/statvfs.h>
22 #endif
23 #if defined(HAVE_SYS_STATFS_H)
24 #include <sys/statfs.h>
25 #endif
26 #if defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H)
27 #include <sys/param.h>
28 #include <sys/mount.h>
29 #endif
30 #include <sys/types.h>
31 #include <stdio.h>
32 #include <utime.h>
33 #ifdef __linux__
34 #include <sys/ioctl.h>
35 #include <linux/fs.h>
36 #include <mono/utils/linux_magic.h>
37 #endif
39 #include <mono/io-layer/wapi.h>
40 #include <mono/io-layer/wapi-private.h>
41 #include <mono/io-layer/handles-private.h>
42 #include <mono/io-layer/io-private.h>
43 #include <mono/io-layer/timefuncs-private.h>
44 #include <mono/io-layer/thread-private.h>
45 #include <mono/io-layer/io-portability.h>
46 #include <mono/io-layer/io-trace.h>
47 #include <mono/utils/strenc.h>
48 #include <mono/utils/mono-once.h>
49 #include <mono/utils/mono-logger-internals.h>
52 * If SHM is disabled, this will point to a hash of _WapiFileShare structures, otherwise
53 * it will be NULL. We use this instead of _wapi_fileshare_layout to avoid allocating a
54 * 4MB array.
56 static GHashTable *file_share_hash;
57 static mono_mutex_t file_share_hash_mutex;
59 #define file_share_hash_lock() mono_os_mutex_lock (&file_share_hash_mutex)
60 #define file_share_hash_unlock() mono_os_mutex_unlock (&file_share_hash_mutex)
62 static void
63 _wapi_handle_share_release (_WapiFileShare *share_info)
65 int thr_ret;
67 g_assert (share_info->handle_refs > 0);
69 /* Prevent new entries racing with us */
70 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_FILESHARE);
71 g_assert(thr_ret == 0);
73 if (InterlockedDecrement ((gint32 *)&share_info->handle_refs) == 0) {
74 file_share_hash_lock ();
75 g_hash_table_remove (file_share_hash, share_info);
76 file_share_hash_unlock ();
79 thr_ret = _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_FILESHARE);
80 g_assert (thr_ret == 0);
83 static gint
84 wapi_share_info_equal (gconstpointer ka, gconstpointer kb)
86 const _WapiFileShare *s1 = (const _WapiFileShare *)ka;
87 const _WapiFileShare *s2 = (const _WapiFileShare *)kb;
89 return (s1->device == s2->device && s1->inode == s2->inode) ? 1 : 0;
92 static guint
93 wapi_share_info_hash (gconstpointer data)
95 const _WapiFileShare *s = (const _WapiFileShare *)data;
97 return s->inode;
100 static gboolean
101 _wapi_handle_get_or_set_share (guint64 device, guint64 inode, guint32 new_sharemode, guint32 new_access,
102 guint32 *old_sharemode, guint32 *old_access, struct _WapiFileShare **share_info)
104 struct _WapiFileShare *file_share;
105 int thr_ret;
106 gboolean exists = FALSE;
108 /* Prevent new entries racing with us */
109 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_FILESHARE);
110 g_assert (thr_ret == 0);
112 _WapiFileShare tmp;
115 * Instead of allocating a 4MB array, we use a hash table to keep track of this
116 * info. This is needed even if SHM is disabled, to track sharing inside
117 * the current process.
119 if (!file_share_hash) {
120 file_share_hash = g_hash_table_new_full (wapi_share_info_hash, wapi_share_info_equal, NULL, g_free);
121 mono_os_mutex_init_recursive (&file_share_hash_mutex);
124 tmp.device = device;
125 tmp.inode = inode;
127 file_share_hash_lock ();
129 file_share = (_WapiFileShare *)g_hash_table_lookup (file_share_hash, &tmp);
130 if (file_share) {
131 *old_sharemode = file_share->sharemode;
132 *old_access = file_share->access;
133 *share_info = file_share;
135 InterlockedIncrement ((gint32 *)&file_share->handle_refs);
136 exists = TRUE;
137 } else {
138 file_share = g_new0 (_WapiFileShare, 1);
140 file_share->device = device;
141 file_share->inode = inode;
142 file_share->opened_by_pid = _wapi_getpid ();
143 file_share->sharemode = new_sharemode;
144 file_share->access = new_access;
145 file_share->handle_refs = 1;
146 *share_info = file_share;
148 g_hash_table_insert (file_share_hash, file_share, file_share);
151 file_share_hash_unlock ();
153 thr_ret = _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_FILESHARE);
154 g_assert (thr_ret == 0);
156 return(exists);
159 static void file_close (gpointer handle, gpointer data);
160 static WapiFileType file_getfiletype(void);
161 static gboolean file_read(gpointer handle, gpointer buffer,
162 guint32 numbytes, guint32 *bytesread,
163 WapiOverlapped *overlapped);
164 static gboolean file_write(gpointer handle, gconstpointer buffer,
165 guint32 numbytes, guint32 *byteswritten,
166 WapiOverlapped *overlapped);
167 static gboolean file_flush(gpointer handle);
168 static guint32 file_seek(gpointer handle, gint32 movedistance,
169 gint32 *highmovedistance, WapiSeekMethod method);
170 static gboolean file_setendoffile(gpointer handle);
171 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
172 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
173 WapiFileTime *last_access,
174 WapiFileTime *last_write);
175 static gboolean file_setfiletime(gpointer handle,
176 const WapiFileTime *create_time,
177 const WapiFileTime *last_access,
178 const WapiFileTime *last_write);
179 static guint32 GetDriveTypeFromPath (const gchar *utf8_root_path_name);
181 /* File handle is only signalled for overlapped IO */
182 struct _WapiHandleOps _wapi_file_ops = {
183 file_close, /* close */
184 NULL, /* signal */
185 NULL, /* own */
186 NULL, /* is_owned */
187 NULL, /* special_wait */
188 NULL /* prewait */
191 void _wapi_file_details (gpointer handle_info)
193 struct _WapiHandle_file *file = (struct _WapiHandle_file *)handle_info;
195 g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
196 file->filename,
197 file->fileaccess&GENERIC_READ?'R':'.',
198 file->fileaccess&GENERIC_WRITE?'W':'.',
199 file->fileaccess&GENERIC_EXECUTE?'X':'.',
200 file->sharemode&FILE_SHARE_READ?'R':'.',
201 file->sharemode&FILE_SHARE_WRITE?'W':'.',
202 file->sharemode&FILE_SHARE_DELETE?'D':'.',
203 file->attrs);
206 static void console_close (gpointer handle, gpointer data);
207 static WapiFileType console_getfiletype(void);
208 static gboolean console_read(gpointer handle, gpointer buffer,
209 guint32 numbytes, guint32 *bytesread,
210 WapiOverlapped *overlapped);
211 static gboolean console_write(gpointer handle, gconstpointer buffer,
212 guint32 numbytes, guint32 *byteswritten,
213 WapiOverlapped *overlapped);
215 /* Console is mostly the same as file, except it can block waiting for
216 * input or output
218 struct _WapiHandleOps _wapi_console_ops = {
219 console_close, /* close */
220 NULL, /* signal */
221 NULL, /* own */
222 NULL, /* is_owned */
223 NULL, /* special_wait */
224 NULL /* prewait */
227 void _wapi_console_details (gpointer handle_info)
229 _wapi_file_details (handle_info);
232 /* Find handle has no ops.
234 struct _WapiHandleOps _wapi_find_ops = {
235 NULL, /* close */
236 NULL, /* signal */
237 NULL, /* own */
238 NULL, /* is_owned */
239 NULL, /* special_wait */
240 NULL /* prewait */
243 static void pipe_close (gpointer handle, gpointer data);
244 static WapiFileType pipe_getfiletype (void);
245 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
246 guint32 *bytesread, WapiOverlapped *overlapped);
247 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
248 guint32 numbytes, guint32 *byteswritten,
249 WapiOverlapped *overlapped);
251 /* Pipe handles
253 struct _WapiHandleOps _wapi_pipe_ops = {
254 pipe_close, /* close */
255 NULL, /* signal */
256 NULL, /* own */
257 NULL, /* is_owned */
258 NULL, /* special_wait */
259 NULL /* prewait */
262 void _wapi_pipe_details (gpointer handle_info)
264 _wapi_file_details (handle_info);
267 static const struct {
268 /* File, console and pipe handles */
269 WapiFileType (*getfiletype)(void);
271 /* File, console and pipe handles */
272 gboolean (*readfile)(gpointer handle, gpointer buffer,
273 guint32 numbytes, guint32 *bytesread,
274 WapiOverlapped *overlapped);
275 gboolean (*writefile)(gpointer handle, gconstpointer buffer,
276 guint32 numbytes, guint32 *byteswritten,
277 WapiOverlapped *overlapped);
278 gboolean (*flushfile)(gpointer handle);
280 /* File handles */
281 guint32 (*seek)(gpointer handle, gint32 movedistance,
282 gint32 *highmovedistance, WapiSeekMethod method);
283 gboolean (*setendoffile)(gpointer handle);
284 guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
285 gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
286 WapiFileTime *last_access,
287 WapiFileTime *last_write);
288 gboolean (*setfiletime)(gpointer handle,
289 const WapiFileTime *create_time,
290 const WapiFileTime *last_access,
291 const WapiFileTime *last_write);
292 } io_ops[WAPI_HANDLE_COUNT]={
293 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
294 /* file */
295 {file_getfiletype,
296 file_read, file_write,
297 file_flush, file_seek,
298 file_setendoffile,
299 file_getfilesize,
300 file_getfiletime,
301 file_setfiletime},
302 /* console */
303 {console_getfiletype,
304 console_read,
305 console_write,
306 NULL, NULL, NULL, NULL, NULL, NULL},
307 /* thread */
308 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
309 /* sem */
310 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
311 /* mutex */
312 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
313 /* event */
314 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
315 /* socket (will need at least read and write) */
316 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
317 /* find */
318 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
319 /* process */
320 {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
321 /* pipe */
322 {pipe_getfiletype,
323 pipe_read,
324 pipe_write,
325 NULL, NULL, NULL, NULL, NULL, NULL},
328 static mono_once_t io_ops_once=MONO_ONCE_INIT;
329 static gboolean lock_while_writing = FALSE;
331 static void io_ops_init (void)
333 /* _wapi_handle_register_capabilities (WAPI_HANDLE_FILE, */
334 /* WAPI_HANDLE_CAP_WAIT); */
335 /* _wapi_handle_register_capabilities (WAPI_HANDLE_CONSOLE, */
336 /* WAPI_HANDLE_CAP_WAIT); */
338 if (g_getenv ("MONO_STRICT_IO_EMULATION") != NULL) {
339 lock_while_writing = TRUE;
343 /* Some utility functions.
347 * Check if a file is writable by the current user.
349 * This is is a best effort kind of thing. It assumes a reasonable sane set
350 * of permissions by the underlying OS.
352 * We generally assume that basic unix permission bits are authoritative. Which might not
353 * be the case under systems with extended permissions systems (posix ACLs, SELinux, OSX/iOS sandboxing, etc)
355 * The choice of access as the fallback is due to the expected lower overhead compared to trying to open the file.
357 * The only expected problem with using access are for root, setuid or setgid programs as access is not consistent
358 * under those situations. It's to be expected that this should not happen in practice as those bits are very dangerous
359 * and should not be used with a dynamic runtime.
361 static gboolean
362 is_file_writable (struct stat *st, const char *path)
364 #if __APPLE__
365 // OS X Finder "locked" or `ls -lO` "uchg".
366 // This only covers one of several cases where an OS X file could be unwritable through special flags.
367 if (st->st_flags & (UF_IMMUTABLE|SF_IMMUTABLE))
368 return 0;
369 #endif
371 /* Is it globally writable? */
372 if (st->st_mode & S_IWOTH)
373 return 1;
375 /* Am I the owner? */
376 if ((st->st_uid == geteuid ()) && (st->st_mode & S_IWUSR))
377 return 1;
379 /* Am I in the same group? */
380 if ((st->st_gid == getegid ()) && (st->st_mode & S_IWGRP))
381 return 1;
383 /* Fallback to using access(2). It's not ideal as it might not take into consideration euid/egid
384 * but it's the only sane option we have on unix.
386 return access (path, W_OK) == 0;
390 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
391 struct stat *buf,
392 struct stat *lbuf)
394 guint32 attrs = 0;
395 gchar *filename;
397 /* FIXME: this could definitely be better, but there seems to
398 * be no pattern to the attributes that are set
401 /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
402 if (S_ISSOCK (buf->st_mode))
403 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
405 filename = _wapi_basename (pathname);
407 if (S_ISDIR (buf->st_mode)) {
408 attrs = FILE_ATTRIBUTE_DIRECTORY;
409 if (!is_file_writable (buf, pathname)) {
410 attrs |= FILE_ATTRIBUTE_READONLY;
412 if (filename[0] == '.') {
413 attrs |= FILE_ATTRIBUTE_HIDDEN;
415 } else {
416 if (!is_file_writable (buf, pathname)) {
417 attrs = FILE_ATTRIBUTE_READONLY;
419 if (filename[0] == '.') {
420 attrs |= FILE_ATTRIBUTE_HIDDEN;
422 } else if (filename[0] == '.') {
423 attrs = FILE_ATTRIBUTE_HIDDEN;
424 } else {
425 attrs = FILE_ATTRIBUTE_NORMAL;
429 if (lbuf != NULL) {
430 if (S_ISLNK (lbuf->st_mode)) {
431 attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
435 g_free (filename);
437 return attrs;
440 static void
441 _wapi_set_last_error_from_errno (void)
443 SetLastError (_wapi_get_win32_file_error (errno));
446 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
447 const gchar *path)
449 if (errno == ENOENT) {
450 /* Check the path - if it's a missing directory then
451 * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
453 gchar *dirname;
456 if (dir == NULL) {
457 dirname = _wapi_dirname (path);
458 } else {
459 dirname = g_strdup (dir);
462 if (_wapi_access (dirname, F_OK) == 0) {
463 SetLastError (ERROR_FILE_NOT_FOUND);
464 } else {
465 SetLastError (ERROR_PATH_NOT_FOUND);
468 g_free (dirname);
469 } else {
470 _wapi_set_last_error_from_errno ();
474 /* Handle ops.
476 static void file_close (gpointer handle, gpointer data)
478 struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
479 int fd = file_handle->fd;
481 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing file handle %p [%s]", __func__, handle,
482 file_handle->filename);
484 if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
485 _wapi_unlink (file_handle->filename);
487 g_free (file_handle->filename);
489 if (file_handle->share_info)
490 _wapi_handle_share_release (file_handle->share_info);
492 close (fd);
495 static WapiFileType file_getfiletype(void)
497 return(FILE_TYPE_DISK);
500 static gboolean file_read(gpointer handle, gpointer buffer,
501 guint32 numbytes, guint32 *bytesread,
502 WapiOverlapped *overlapped)
504 struct _WapiHandle_file *file_handle;
505 gboolean ok;
506 int fd, ret;
508 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
509 (gpointer *)&file_handle);
510 if(ok==FALSE) {
511 g_warning ("%s: error looking up file handle %p", __func__,
512 handle);
513 SetLastError (ERROR_INVALID_HANDLE);
514 return(FALSE);
517 fd = file_handle->fd;
518 if(bytesread!=NULL) {
519 *bytesread=0;
522 if(!(file_handle->fileaccess & GENERIC_READ) &&
523 !(file_handle->fileaccess & GENERIC_ALL)) {
524 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
525 __func__, handle, file_handle->fileaccess);
527 SetLastError (ERROR_ACCESS_DENIED);
528 return(FALSE);
531 do {
532 ret = read (fd, buffer, numbytes);
533 } while (ret == -1 && errno == EINTR &&
534 !_wapi_thread_cur_apc_pending());
536 if(ret==-1) {
537 gint err = errno;
539 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
540 handle, strerror(err));
541 SetLastError (_wapi_get_win32_file_error (err));
542 return(FALSE);
545 if (bytesread != NULL) {
546 *bytesread = ret;
549 return(TRUE);
552 static gboolean file_write(gpointer handle, gconstpointer buffer,
553 guint32 numbytes, guint32 *byteswritten,
554 WapiOverlapped *overlapped G_GNUC_UNUSED)
556 struct _WapiHandle_file *file_handle;
557 gboolean ok;
558 int ret, fd;
559 off_t current_pos = 0;
561 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
562 (gpointer *)&file_handle);
563 if(ok==FALSE) {
564 g_warning ("%s: error looking up file handle %p", __func__,
565 handle);
566 SetLastError (ERROR_INVALID_HANDLE);
567 return(FALSE);
570 fd = file_handle->fd;
572 if(byteswritten!=NULL) {
573 *byteswritten=0;
576 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
577 !(file_handle->fileaccess & GENERIC_ALL)) {
578 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);
580 SetLastError (ERROR_ACCESS_DENIED);
581 return(FALSE);
584 if (lock_while_writing) {
585 /* Need to lock the region we're about to write to,
586 * because we only do advisory locking on POSIX
587 * systems
589 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
590 if (current_pos == -1) {
591 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
592 handle, strerror (errno));
593 _wapi_set_last_error_from_errno ();
594 return(FALSE);
597 if (_wapi_lock_file_region (fd, current_pos,
598 numbytes) == FALSE) {
599 /* The error has already been set */
600 return(FALSE);
604 do {
605 ret = write (fd, buffer, numbytes);
606 } while (ret == -1 && errno == EINTR &&
607 !_wapi_thread_cur_apc_pending());
609 if (lock_while_writing) {
610 _wapi_unlock_file_region (fd, current_pos, numbytes);
613 if (ret == -1) {
614 if (errno == EINTR) {
615 ret = 0;
616 } else {
617 _wapi_set_last_error_from_errno ();
619 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
620 __func__, handle, strerror(errno));
622 return(FALSE);
625 if (byteswritten != NULL) {
626 *byteswritten = ret;
628 return(TRUE);
631 static gboolean file_flush(gpointer handle)
633 struct _WapiHandle_file *file_handle;
634 gboolean ok;
635 int ret, fd;
637 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
638 (gpointer *)&file_handle);
639 if(ok==FALSE) {
640 g_warning ("%s: error looking up file handle %p", __func__,
641 handle);
642 SetLastError (ERROR_INVALID_HANDLE);
643 return(FALSE);
646 fd = file_handle->fd;
648 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
649 !(file_handle->fileaccess & GENERIC_ALL)) {
650 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);
652 SetLastError (ERROR_ACCESS_DENIED);
653 return(FALSE);
656 ret=fsync(fd);
657 if (ret==-1) {
658 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fsync of handle %p error: %s", __func__, handle,
659 strerror(errno));
661 _wapi_set_last_error_from_errno ();
662 return(FALSE);
665 return(TRUE);
668 static guint32 file_seek(gpointer handle, gint32 movedistance,
669 gint32 *highmovedistance, WapiSeekMethod method)
671 struct _WapiHandle_file *file_handle;
672 gboolean ok;
673 gint64 offset, newpos;
674 int whence, fd;
675 guint32 ret;
677 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
678 (gpointer *)&file_handle);
679 if(ok==FALSE) {
680 g_warning ("%s: error looking up file handle %p", __func__,
681 handle);
682 SetLastError (ERROR_INVALID_HANDLE);
683 return(INVALID_SET_FILE_POINTER);
686 fd = file_handle->fd;
688 if(!(file_handle->fileaccess & GENERIC_READ) &&
689 !(file_handle->fileaccess & GENERIC_WRITE) &&
690 !(file_handle->fileaccess & GENERIC_ALL)) {
691 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);
693 SetLastError (ERROR_ACCESS_DENIED);
694 return(INVALID_SET_FILE_POINTER);
697 switch(method) {
698 case FILE_BEGIN:
699 whence=SEEK_SET;
700 break;
701 case FILE_CURRENT:
702 whence=SEEK_CUR;
703 break;
704 case FILE_END:
705 whence=SEEK_END;
706 break;
707 default:
708 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: invalid seek type %d", __func__, method);
710 SetLastError (ERROR_INVALID_PARAMETER);
711 return(INVALID_SET_FILE_POINTER);
714 #ifdef HAVE_LARGE_FILE_SUPPORT
715 if(highmovedistance==NULL) {
716 offset=movedistance;
717 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting offset to %lld (low %d)", __func__,
718 offset, movedistance);
719 } else {
720 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
722 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);
724 #else
725 offset=movedistance;
726 #endif
728 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: moving handle %p by %lld bytes from %d", __func__,
729 handle, (long long)offset, whence);
731 #ifdef PLATFORM_ANDROID
732 /* bionic doesn't support -D_FILE_OFFSET_BITS=64 */
733 newpos=lseek64(fd, offset, whence);
734 #else
735 newpos=lseek(fd, offset, whence);
736 #endif
737 if(newpos==-1) {
738 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek on handle %p returned error %s",
739 __func__, handle, strerror(errno));
741 _wapi_set_last_error_from_errno ();
742 return(INVALID_SET_FILE_POINTER);
745 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek returns %lld", __func__, newpos);
747 #ifdef HAVE_LARGE_FILE_SUPPORT
748 ret=newpos & 0xFFFFFFFF;
749 if(highmovedistance!=NULL) {
750 *highmovedistance=newpos>>32;
752 #else
753 ret=newpos;
754 if(highmovedistance!=NULL) {
755 /* Accurate, but potentially dodgy :-) */
756 *highmovedistance=0;
758 #endif
760 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: move of handle %p returning %d/%d", __func__,
761 handle, ret, highmovedistance==NULL?0:*highmovedistance);
763 return(ret);
766 static gboolean file_setendoffile(gpointer handle)
768 struct _WapiHandle_file *file_handle;
769 gboolean ok;
770 struct stat statbuf;
771 off_t pos;
772 int ret, fd;
774 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
775 (gpointer *)&file_handle);
776 if(ok==FALSE) {
777 g_warning ("%s: error looking up file handle %p", __func__,
778 handle);
779 SetLastError (ERROR_INVALID_HANDLE);
780 return(FALSE);
782 fd = file_handle->fd;
784 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
785 !(file_handle->fileaccess & GENERIC_ALL)) {
786 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);
788 SetLastError (ERROR_ACCESS_DENIED);
789 return(FALSE);
792 /* Find the current file position, and the file length. If
793 * the file position is greater than the length, write to
794 * extend the file with a hole. If the file position is less
795 * than the length, truncate the file.
798 ret=fstat(fd, &statbuf);
799 if(ret==-1) {
800 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
801 handle, strerror(errno));
803 _wapi_set_last_error_from_errno ();
804 return(FALSE);
807 pos=lseek(fd, (off_t)0, SEEK_CUR);
808 if(pos==-1) {
809 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
810 handle, strerror(errno));
812 _wapi_set_last_error_from_errno ();
813 return(FALSE);
816 #ifdef FTRUNCATE_DOESNT_EXTEND
817 off_t size = statbuf.st_size;
818 /* I haven't bothered to write the configure.ac stuff for this
819 * because I don't know if any platform needs it. I'm leaving
820 * this code just in case though
822 if(pos>size) {
823 /* Extend the file. Use write() here, because some
824 * manuals say that ftruncate() behaviour is undefined
825 * when the file needs extending. The POSIX spec says
826 * that on XSI-conformant systems it extends, so if
827 * every system we care about conforms, then we can
828 * drop this write.
830 do {
831 ret = write (fd, "", 1);
832 } while (ret == -1 && errno == EINTR &&
833 !_wapi_thread_cur_apc_pending());
835 if(ret==-1) {
836 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
838 _wapi_set_last_error_from_errno ();
839 return(FALSE);
842 /* And put the file position back after the write */
843 ret = lseek (fd, pos, SEEK_SET);
844 if (ret == -1) {
845 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p second lseek failed: %s",
846 __func__, handle, strerror(errno));
848 _wapi_set_last_error_from_errno ();
849 return(FALSE);
852 #endif
854 /* Native Client has no ftruncate function, even in standalone sel_ldr. */
855 #ifndef __native_client__
856 /* always truncate, because the extend write() adds an extra
857 * byte to the end of the file
859 do {
860 ret=ftruncate(fd, pos);
862 while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
863 if(ret==-1) {
864 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ftruncate failed: %s", __func__,
865 handle, strerror(errno));
867 _wapi_set_last_error_from_errno ();
868 return(FALSE);
870 #endif
872 return(TRUE);
875 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
877 struct _WapiHandle_file *file_handle;
878 gboolean ok;
879 struct stat statbuf;
880 guint32 size;
881 int ret;
882 int fd;
884 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
885 (gpointer *)&file_handle);
886 if(ok==FALSE) {
887 g_warning ("%s: error looking up file handle %p", __func__,
888 handle);
889 SetLastError (ERROR_INVALID_HANDLE);
890 return(INVALID_FILE_SIZE);
892 fd = file_handle->fd;
894 if(!(file_handle->fileaccess & GENERIC_READ) &&
895 !(file_handle->fileaccess & GENERIC_WRITE) &&
896 !(file_handle->fileaccess & GENERIC_ALL)) {
897 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);
899 SetLastError (ERROR_ACCESS_DENIED);
900 return(INVALID_FILE_SIZE);
903 /* If the file has a size with the low bits 0xFFFFFFFF the
904 * caller can't tell if this is an error, so clear the error
905 * value
907 SetLastError (ERROR_SUCCESS);
909 ret = fstat(fd, &statbuf);
910 if (ret == -1) {
911 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
912 handle, strerror(errno));
914 _wapi_set_last_error_from_errno ();
915 return(INVALID_FILE_SIZE);
918 /* fstat indicates block devices as zero-length, so go a different path */
919 #ifdef BLKGETSIZE64
920 if (S_ISBLK(statbuf.st_mode)) {
921 guint64 bigsize;
922 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
923 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ioctl BLKGETSIZE64 failed: %s",
924 __func__, handle, strerror(errno));
926 _wapi_set_last_error_from_errno ();
927 return(INVALID_FILE_SIZE);
930 size = bigsize & 0xFFFFFFFF;
931 if (highsize != NULL) {
932 *highsize = bigsize>>32;
935 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning block device size %d/%d",
936 __func__, size, *highsize);
938 return(size);
940 #endif
942 #ifdef HAVE_LARGE_FILE_SUPPORT
943 size = statbuf.st_size & 0xFFFFFFFF;
944 if (highsize != NULL) {
945 *highsize = statbuf.st_size>>32;
947 #else
948 if (highsize != NULL) {
949 /* Accurate, but potentially dodgy :-) */
950 *highsize = 0;
952 size = statbuf.st_size;
953 #endif
955 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning size %d/%d", __func__, size, *highsize);
957 return(size);
960 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
961 WapiFileTime *last_access,
962 WapiFileTime *last_write)
964 struct _WapiHandle_file *file_handle;
965 gboolean ok;
966 struct stat statbuf;
967 guint64 create_ticks, access_ticks, write_ticks;
968 int ret, fd;
970 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
971 (gpointer *)&file_handle);
972 if(ok==FALSE) {
973 g_warning ("%s: error looking up file handle %p", __func__,
974 handle);
975 SetLastError (ERROR_INVALID_HANDLE);
976 return(FALSE);
978 fd = file_handle->fd;
980 if(!(file_handle->fileaccess & GENERIC_READ) &&
981 !(file_handle->fileaccess & GENERIC_ALL)) {
982 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
983 __func__, handle, file_handle->fileaccess);
985 SetLastError (ERROR_ACCESS_DENIED);
986 return(FALSE);
989 ret=fstat(fd, &statbuf);
990 if(ret==-1) {
991 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
992 strerror(errno));
994 _wapi_set_last_error_from_errno ();
995 return(FALSE);
998 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: atime: %ld ctime: %ld mtime: %ld", __func__,
999 statbuf.st_atime, statbuf.st_ctime,
1000 statbuf.st_mtime);
1002 /* Try and guess a meaningful create time by using the older
1003 * of atime or ctime
1005 /* The magic constant comes from msdn documentation
1006 * "Converting a time_t Value to a File Time"
1008 if(statbuf.st_atime < statbuf.st_ctime) {
1009 create_ticks=((guint64)statbuf.st_atime*10000000)
1010 + 116444736000000000ULL;
1011 } else {
1012 create_ticks=((guint64)statbuf.st_ctime*10000000)
1013 + 116444736000000000ULL;
1016 access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
1017 write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
1019 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
1020 access_ticks, create_ticks, write_ticks);
1022 if(create_time!=NULL) {
1023 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
1024 create_time->dwHighDateTime = create_ticks >> 32;
1027 if(last_access!=NULL) {
1028 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
1029 last_access->dwHighDateTime = access_ticks >> 32;
1032 if(last_write!=NULL) {
1033 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
1034 last_write->dwHighDateTime = write_ticks >> 32;
1037 return(TRUE);
1040 static gboolean file_setfiletime(gpointer handle,
1041 const WapiFileTime *create_time G_GNUC_UNUSED,
1042 const WapiFileTime *last_access,
1043 const WapiFileTime *last_write)
1045 struct _WapiHandle_file *file_handle;
1046 gboolean ok;
1047 struct utimbuf utbuf;
1048 struct stat statbuf;
1049 guint64 access_ticks, write_ticks;
1050 int ret, fd;
1052 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
1053 (gpointer *)&file_handle);
1054 if(ok==FALSE) {
1055 g_warning ("%s: error looking up file handle %p", __func__,
1056 handle);
1057 SetLastError (ERROR_INVALID_HANDLE);
1058 return(FALSE);
1060 fd = file_handle->fd;
1062 if(!(file_handle->fileaccess & GENERIC_WRITE) &&
1063 !(file_handle->fileaccess & GENERIC_ALL)) {
1064 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);
1066 SetLastError (ERROR_ACCESS_DENIED);
1067 return(FALSE);
1070 if(file_handle->filename == NULL) {
1071 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p unknown filename", __func__, handle);
1073 SetLastError (ERROR_INVALID_HANDLE);
1074 return(FALSE);
1077 /* Get the current times, so we can put the same times back in
1078 * the event that one of the FileTime structs is NULL
1080 ret=fstat (fd, &statbuf);
1081 if(ret==-1) {
1082 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
1083 strerror(errno));
1085 SetLastError (ERROR_INVALID_PARAMETER);
1086 return(FALSE);
1089 if(last_access!=NULL) {
1090 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
1091 last_access->dwLowDateTime;
1092 /* This is (time_t)0. We can actually go to INT_MIN,
1093 * but this will do for now.
1095 if (access_ticks < 116444736000000000ULL) {
1096 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set access time too early",
1097 __func__);
1098 SetLastError (ERROR_INVALID_PARAMETER);
1099 return(FALSE);
1102 if (sizeof (utbuf.actime) == 4 && ((access_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
1103 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",
1104 __func__);
1105 SetLastError (ERROR_INVALID_PARAMETER);
1106 return(FALSE);
1109 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
1110 } else {
1111 utbuf.actime=statbuf.st_atime;
1114 if(last_write!=NULL) {
1115 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
1116 last_write->dwLowDateTime;
1117 /* This is (time_t)0. We can actually go to INT_MIN,
1118 * but this will do for now.
1120 if (write_ticks < 116444736000000000ULL) {
1121 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set write time too early",
1122 __func__);
1123 SetLastError (ERROR_INVALID_PARAMETER);
1124 return(FALSE);
1126 if (sizeof (utbuf.modtime) == 4 && ((write_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
1127 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",
1128 __func__);
1129 SetLastError (ERROR_INVALID_PARAMETER);
1130 return(FALSE);
1133 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1134 } else {
1135 utbuf.modtime=statbuf.st_mtime;
1138 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting handle %p access %ld write %ld", __func__,
1139 handle, utbuf.actime, utbuf.modtime);
1141 ret = _wapi_utime (file_handle->filename, &utbuf);
1142 if (ret == -1) {
1143 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p [%s] utime failed: %s", __func__,
1144 handle, file_handle->filename, strerror(errno));
1146 SetLastError (ERROR_INVALID_PARAMETER);
1147 return(FALSE);
1150 return(TRUE);
1153 static void console_close (gpointer handle, gpointer data)
1155 struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1156 int fd = console_handle->fd;
1158 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing console handle %p", __func__, handle);
1160 g_free (console_handle->filename);
1162 if (fd > 2) {
1163 if (console_handle->share_info)
1164 _wapi_handle_share_release (console_handle->share_info);
1165 close (fd);
1169 static WapiFileType console_getfiletype(void)
1171 return(FILE_TYPE_CHAR);
1174 static gboolean console_read(gpointer handle, gpointer buffer,
1175 guint32 numbytes, guint32 *bytesread,
1176 WapiOverlapped *overlapped G_GNUC_UNUSED)
1178 struct _WapiHandle_file *console_handle;
1179 gboolean ok;
1180 int ret, fd;
1182 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1183 (gpointer *)&console_handle);
1184 if(ok==FALSE) {
1185 g_warning ("%s: error looking up console handle %p", __func__,
1186 handle);
1187 SetLastError (ERROR_INVALID_HANDLE);
1188 return(FALSE);
1190 fd = console_handle->fd;
1192 if(bytesread!=NULL) {
1193 *bytesread=0;
1196 if(!(console_handle->fileaccess & GENERIC_READ) &&
1197 !(console_handle->fileaccess & GENERIC_ALL)) {
1198 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1199 __func__, handle, console_handle->fileaccess);
1201 SetLastError (ERROR_ACCESS_DENIED);
1202 return(FALSE);
1205 do {
1206 ret=read(fd, buffer, numbytes);
1207 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1209 if(ret==-1) {
1210 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__, handle,
1211 strerror(errno));
1213 _wapi_set_last_error_from_errno ();
1214 return(FALSE);
1217 if(bytesread!=NULL) {
1218 *bytesread=ret;
1221 return(TRUE);
1224 static gboolean console_write(gpointer handle, gconstpointer buffer,
1225 guint32 numbytes, guint32 *byteswritten,
1226 WapiOverlapped *overlapped G_GNUC_UNUSED)
1228 struct _WapiHandle_file *console_handle;
1229 gboolean ok;
1230 int ret, fd;
1232 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1233 (gpointer *)&console_handle);
1234 if(ok==FALSE) {
1235 g_warning ("%s: error looking up console handle %p", __func__,
1236 handle);
1237 SetLastError (ERROR_INVALID_HANDLE);
1238 return(FALSE);
1240 fd = console_handle->fd;
1242 if(byteswritten!=NULL) {
1243 *byteswritten=0;
1246 if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1247 !(console_handle->fileaccess & GENERIC_ALL)) {
1248 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);
1250 SetLastError (ERROR_ACCESS_DENIED);
1251 return(FALSE);
1254 do {
1255 ret = write(fd, buffer, numbytes);
1256 } while (ret == -1 && errno == EINTR &&
1257 !_wapi_thread_cur_apc_pending());
1259 if (ret == -1) {
1260 if (errno == EINTR) {
1261 ret = 0;
1262 } else {
1263 _wapi_set_last_error_from_errno ();
1265 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
1266 __func__, handle, strerror(errno));
1268 return(FALSE);
1271 if(byteswritten!=NULL) {
1272 *byteswritten=ret;
1275 return(TRUE);
1278 static void pipe_close (gpointer handle, gpointer data)
1280 struct _WapiHandle_file *pipe_handle = (struct _WapiHandle_file*)data;
1281 int fd = pipe_handle->fd;
1283 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing pipe handle %p fd %d", __func__, handle, fd);
1285 /* No filename with pipe handles */
1287 if (pipe_handle->share_info)
1288 _wapi_handle_share_release (pipe_handle->share_info);
1290 close (fd);
1293 static WapiFileType pipe_getfiletype(void)
1295 return(FILE_TYPE_PIPE);
1298 static gboolean pipe_read (gpointer handle, gpointer buffer,
1299 guint32 numbytes, guint32 *bytesread,
1300 WapiOverlapped *overlapped G_GNUC_UNUSED)
1302 struct _WapiHandle_file *pipe_handle;
1303 gboolean ok;
1304 int ret, fd;
1306 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1307 (gpointer *)&pipe_handle);
1308 if(ok==FALSE) {
1309 g_warning ("%s: error looking up pipe handle %p", __func__,
1310 handle);
1311 SetLastError (ERROR_INVALID_HANDLE);
1312 return(FALSE);
1314 fd = pipe_handle->fd;
1316 if(bytesread!=NULL) {
1317 *bytesread=0;
1320 if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1321 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1322 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1323 __func__, handle, pipe_handle->fileaccess);
1325 SetLastError (ERROR_ACCESS_DENIED);
1326 return(FALSE);
1329 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: reading up to %d bytes from pipe %p", __func__,
1330 numbytes, handle);
1332 do {
1333 ret=read(fd, buffer, numbytes);
1334 } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1336 if (ret == -1) {
1337 if (errno == EINTR) {
1338 ret = 0;
1339 } else {
1340 _wapi_set_last_error_from_errno ();
1342 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
1343 handle, strerror(errno));
1345 return(FALSE);
1349 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read %d bytes from pipe %p", __func__, ret, handle);
1351 if(bytesread!=NULL) {
1352 *bytesread=ret;
1355 return(TRUE);
1358 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1359 guint32 numbytes, guint32 *byteswritten,
1360 WapiOverlapped *overlapped G_GNUC_UNUSED)
1362 struct _WapiHandle_file *pipe_handle;
1363 gboolean ok;
1364 int ret, fd;
1366 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1367 (gpointer *)&pipe_handle);
1368 if(ok==FALSE) {
1369 g_warning ("%s: error looking up pipe handle %p", __func__,
1370 handle);
1371 SetLastError (ERROR_INVALID_HANDLE);
1372 return(FALSE);
1374 fd = pipe_handle->fd;
1376 if(byteswritten!=NULL) {
1377 *byteswritten=0;
1380 if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1381 !(pipe_handle->fileaccess & GENERIC_ALL)) {
1382 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);
1384 SetLastError (ERROR_ACCESS_DENIED);
1385 return(FALSE);
1388 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1389 handle);
1391 do {
1392 ret = write (fd, buffer, numbytes);
1393 } while (ret == -1 && errno == EINTR &&
1394 !_wapi_thread_cur_apc_pending());
1396 if (ret == -1) {
1397 if (errno == EINTR) {
1398 ret = 0;
1399 } else {
1400 _wapi_set_last_error_from_errno ();
1402 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s", __func__,
1403 handle, strerror(errno));
1405 return(FALSE);
1408 if(byteswritten!=NULL) {
1409 *byteswritten=ret;
1412 return(TRUE);
1415 static int convert_flags(guint32 fileaccess, guint32 createmode)
1417 int flags=0;
1419 switch(fileaccess) {
1420 case GENERIC_READ:
1421 flags=O_RDONLY;
1422 break;
1423 case GENERIC_WRITE:
1424 flags=O_WRONLY;
1425 break;
1426 case GENERIC_READ|GENERIC_WRITE:
1427 flags=O_RDWR;
1428 break;
1429 default:
1430 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown access type 0x%x", __func__,
1431 fileaccess);
1432 break;
1435 switch(createmode) {
1436 case CREATE_NEW:
1437 flags|=O_CREAT|O_EXCL;
1438 break;
1439 case CREATE_ALWAYS:
1440 flags|=O_CREAT|O_TRUNC;
1441 break;
1442 case OPEN_EXISTING:
1443 break;
1444 case OPEN_ALWAYS:
1445 flags|=O_CREAT;
1446 break;
1447 case TRUNCATE_EXISTING:
1448 flags|=O_TRUNC;
1449 break;
1450 default:
1451 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown create mode 0x%x", __func__,
1452 createmode);
1453 break;
1456 return(flags);
1459 #if 0 /* unused */
1460 static mode_t convert_perms(guint32 sharemode)
1462 mode_t perms=0600;
1464 if(sharemode&FILE_SHARE_READ) {
1465 perms|=044;
1467 if(sharemode&FILE_SHARE_WRITE) {
1468 perms|=022;
1471 return(perms);
1473 #endif
1475 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1476 guint32 fileaccess,
1477 struct _WapiFileShare **share_info)
1479 gboolean file_already_shared;
1480 guint32 file_existing_share, file_existing_access;
1482 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);
1484 if (file_already_shared) {
1485 /* The reference to this share info was incremented
1486 * when we looked it up, so be careful to put it back
1487 * if we conclude we can't use this file.
1489 if (file_existing_share == 0) {
1490 /* Quick and easy, no possibility to share */
1491 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);
1493 _wapi_handle_share_release (*share_info);
1495 return(FALSE);
1498 if (((file_existing_share == FILE_SHARE_READ) &&
1499 (fileaccess != GENERIC_READ)) ||
1500 ((file_existing_share == FILE_SHARE_WRITE) &&
1501 (fileaccess != GENERIC_WRITE))) {
1502 /* New access mode doesn't match up */
1503 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);
1505 _wapi_handle_share_release (*share_info);
1507 return(FALSE);
1510 if (((file_existing_access & GENERIC_READ) &&
1511 !(sharemode & FILE_SHARE_READ)) ||
1512 ((file_existing_access & GENERIC_WRITE) &&
1513 !(sharemode & FILE_SHARE_WRITE))) {
1514 /* New share mode doesn't match up */
1515 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);
1517 _wapi_handle_share_release (*share_info);
1519 return(FALSE);
1521 } else {
1522 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
1525 return(TRUE);
1529 static gboolean
1530 share_allows_delete (struct stat *statbuf, struct _WapiFileShare **share_info)
1532 gboolean file_already_shared;
1533 guint32 file_existing_share, file_existing_access;
1535 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);
1537 if (file_already_shared) {
1538 /* The reference to this share info was incremented
1539 * when we looked it up, so be careful to put it back
1540 * if we conclude we can't use this file.
1542 if (file_existing_share == 0) {
1543 /* Quick and easy, no possibility to share */
1544 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);
1546 _wapi_handle_share_release (*share_info);
1548 return(FALSE);
1551 if (!(file_existing_share & FILE_SHARE_DELETE)) {
1552 /* New access mode doesn't match up */
1553 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);
1555 _wapi_handle_share_release (*share_info);
1557 return(FALSE);
1559 } else {
1560 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
1563 return(TRUE);
1567 * CreateFile:
1568 * @name: a pointer to a NULL-terminated unicode string, that names
1569 * the file or other object to create.
1570 * @fileaccess: specifies the file access mode
1571 * @sharemode: whether the file should be shared. This parameter is
1572 * currently ignored.
1573 * @security: Ignored for now.
1574 * @createmode: specifies whether to create a new file, whether to
1575 * overwrite an existing file, whether to truncate the file, etc.
1576 * @attrs: specifies file attributes and flags. On win32 attributes
1577 * are characteristics of the file, not the handle, and are ignored
1578 * when an existing file is opened. Flags give the library hints on
1579 * how to process a file to optimise performance.
1580 * @template: the handle of an open %GENERIC_READ file that specifies
1581 * attributes to apply to a newly created file, ignoring @attrs.
1582 * Normally this parameter is NULL. This parameter is ignored when an
1583 * existing file is opened.
1585 * Creates a new file handle. This only applies to normal files:
1586 * pipes are handled by CreatePipe(), and console handles are created
1587 * with GetStdHandle().
1589 * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1591 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1592 guint32 sharemode, WapiSecurityAttributes *security,
1593 guint32 createmode, guint32 attrs,
1594 gpointer template_ G_GNUC_UNUSED)
1596 struct _WapiHandle_file file_handle = {0};
1597 gpointer handle;
1598 int flags=convert_flags(fileaccess, createmode);
1599 /*mode_t perms=convert_perms(sharemode);*/
1600 /* we don't use sharemode, because that relates to sharing of
1601 * the file when the file is open and is already handled by
1602 * other code, perms instead are the on-disk permissions and
1603 * this is a sane default.
1605 mode_t perms=0666;
1606 gchar *filename;
1607 int fd, ret;
1608 WapiHandleType handle_type;
1609 struct stat statbuf;
1611 mono_once (&io_ops_once, io_ops_init);
1613 if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1614 perms = 0600;
1616 if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1617 SetLastError (ERROR_ENCRYPTION_FAILED);
1618 return INVALID_HANDLE_VALUE;
1621 if (name == NULL) {
1622 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1624 SetLastError (ERROR_INVALID_NAME);
1625 return(INVALID_HANDLE_VALUE);
1628 filename = mono_unicode_to_external (name);
1629 if (filename == NULL) {
1630 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1632 SetLastError (ERROR_INVALID_NAME);
1633 return(INVALID_HANDLE_VALUE);
1636 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Opening %s with share 0x%x and access 0x%x", __func__,
1637 filename, sharemode, fileaccess);
1639 fd = _wapi_open (filename, flags, perms);
1641 /* If we were trying to open a directory with write permissions
1642 * (e.g. O_WRONLY or O_RDWR), this call will fail with
1643 * EISDIR. However, this is a bit bogus because calls to
1644 * manipulate the directory (e.g. SetFileTime) will still work on
1645 * the directory because they use other API calls
1646 * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1647 * to open the directory again without write permission.
1649 if (fd == -1 && errno == EISDIR)
1651 /* Try again but don't try to make it writable */
1652 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1655 if (fd == -1) {
1656 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s: %s", __func__, filename,
1657 strerror(errno));
1658 _wapi_set_last_path_error_from_errno (NULL, filename);
1659 g_free (filename);
1661 return(INVALID_HANDLE_VALUE);
1664 if (fd >= _wapi_fd_reserve) {
1665 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
1667 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1669 close (fd);
1670 g_free (filename);
1672 return(INVALID_HANDLE_VALUE);
1675 ret = fstat (fd, &statbuf);
1676 if (ret == -1) {
1677 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fstat error of file %s: %s", __func__,
1678 filename, strerror (errno));
1679 _wapi_set_last_error_from_errno ();
1680 g_free (filename);
1681 close (fd);
1683 return(INVALID_HANDLE_VALUE);
1685 #ifdef __native_client__
1686 /* Workaround: Native Client currently returns the same fake inode
1687 * for all files, so do a simple hash on the filename so we don't
1688 * use the same share info for each file.
1690 statbuf.st_ino = g_str_hash(filename);
1691 #endif
1693 if (share_allows_open (&statbuf, sharemode, fileaccess,
1694 &file_handle.share_info) == FALSE) {
1695 SetLastError (ERROR_SHARING_VIOLATION);
1696 g_free (filename);
1697 close (fd);
1699 return (INVALID_HANDLE_VALUE);
1701 if (file_handle.share_info == NULL) {
1702 /* No space, so no more files can be opened */
1703 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No space in the share table", __func__);
1705 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1706 close (fd);
1707 g_free (filename);
1709 return(INVALID_HANDLE_VALUE);
1712 file_handle.filename = filename;
1714 if(security!=NULL) {
1715 //file_handle->security_attributes=_wapi_handle_scratch_store (
1716 //security, sizeof(WapiSecurityAttributes));
1719 file_handle.fd = fd;
1720 file_handle.fileaccess=fileaccess;
1721 file_handle.sharemode=sharemode;
1722 file_handle.attrs=attrs;
1724 #ifdef HAVE_POSIX_FADVISE
1725 if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1726 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1727 if (attrs & FILE_FLAG_RANDOM_ACCESS)
1728 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1729 #endif
1731 #ifndef S_ISFIFO
1732 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1733 #endif
1734 if (S_ISFIFO (statbuf.st_mode)) {
1735 handle_type = WAPI_HANDLE_PIPE;
1736 /* maintain invariant that pipes have no filename */
1737 file_handle.filename = NULL;
1738 g_free (filename);
1739 filename = NULL;
1740 } else if (S_ISCHR (statbuf.st_mode)) {
1741 handle_type = WAPI_HANDLE_CONSOLE;
1742 } else {
1743 handle_type = WAPI_HANDLE_FILE;
1746 handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1747 if (handle == _WAPI_HANDLE_INVALID) {
1748 g_warning ("%s: error creating file handle", __func__);
1749 g_free (filename);
1750 close (fd);
1752 SetLastError (ERROR_GEN_FAILURE);
1753 return(INVALID_HANDLE_VALUE);
1756 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p", __func__, handle);
1758 return(handle);
1762 * DeleteFile:
1763 * @name: a pointer to a NULL-terminated unicode string, that names
1764 * the file to be deleted.
1766 * Deletes file @name.
1768 * Return value: %TRUE on success, %FALSE otherwise.
1770 gboolean DeleteFile(const gunichar2 *name)
1772 gchar *filename;
1773 int retval;
1774 gboolean ret = FALSE;
1775 guint32 attrs;
1776 #if 0
1777 struct stat statbuf;
1778 struct _WapiFileShare *shareinfo;
1779 #endif
1781 if(name==NULL) {
1782 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1784 SetLastError (ERROR_INVALID_NAME);
1785 return(FALSE);
1788 filename=mono_unicode_to_external(name);
1789 if(filename==NULL) {
1790 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1792 SetLastError (ERROR_INVALID_NAME);
1793 return(FALSE);
1796 attrs = GetFileAttributes (name);
1797 if (attrs == INVALID_FILE_ATTRIBUTES) {
1798 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file attributes error", __func__);
1799 /* Error set by GetFileAttributes() */
1800 g_free (filename);
1801 return(FALSE);
1804 #if 0
1805 /* Check to make sure sharing allows us to open the file for
1806 * writing. See bug 323389.
1808 * Do the checks that don't need an open file descriptor, for
1809 * simplicity's sake. If we really have to do the full checks
1810 * then we can implement that later.
1812 if (_wapi_stat (filename, &statbuf) < 0) {
1813 _wapi_set_last_path_error_from_errno (NULL, filename);
1814 g_free (filename);
1815 return(FALSE);
1818 if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1819 &shareinfo) == FALSE) {
1820 SetLastError (ERROR_SHARING_VIOLATION);
1821 g_free (filename);
1822 return FALSE;
1824 if (shareinfo)
1825 _wapi_handle_share_release (shareinfo);
1826 #endif
1828 retval = _wapi_unlink (filename);
1830 if (retval == -1) {
1831 _wapi_set_last_path_error_from_errno (NULL, filename);
1832 } else {
1833 ret = TRUE;
1836 g_free(filename);
1838 return(ret);
1842 * MoveFile:
1843 * @name: a pointer to a NULL-terminated unicode string, that names
1844 * the file to be moved.
1845 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1846 * new name for the file.
1848 * Renames file @name to @dest_name.
1849 * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1850 * when it is the same file as the source. In that case it silently succeeds.
1852 * Return value: %TRUE on success, %FALSE otherwise.
1854 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1856 gchar *utf8_name, *utf8_dest_name;
1857 int result, errno_copy;
1858 struct stat stat_src, stat_dest;
1859 gboolean ret = FALSE;
1860 struct _WapiFileShare *shareinfo;
1862 if(name==NULL) {
1863 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1865 SetLastError (ERROR_INVALID_NAME);
1866 return(FALSE);
1869 utf8_name = mono_unicode_to_external (name);
1870 if (utf8_name == NULL) {
1871 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1873 SetLastError (ERROR_INVALID_NAME);
1874 return FALSE;
1877 if(dest_name==NULL) {
1878 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1880 g_free (utf8_name);
1881 SetLastError (ERROR_INVALID_NAME);
1882 return(FALSE);
1885 utf8_dest_name = mono_unicode_to_external (dest_name);
1886 if (utf8_dest_name == NULL) {
1887 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1889 g_free (utf8_name);
1890 SetLastError (ERROR_INVALID_NAME);
1891 return FALSE;
1895 * In C# land we check for the existence of src, but not for dest.
1896 * We check it here and return the failure if dest exists and is not
1897 * the same file as src.
1899 if (_wapi_stat (utf8_name, &stat_src) < 0) {
1900 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1901 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1902 g_free (utf8_name);
1903 g_free (utf8_dest_name);
1904 return FALSE;
1908 if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1909 if (stat_dest.st_dev != stat_src.st_dev ||
1910 stat_dest.st_ino != stat_src.st_ino) {
1911 g_free (utf8_name);
1912 g_free (utf8_dest_name);
1913 SetLastError (ERROR_ALREADY_EXISTS);
1914 return FALSE;
1918 /* Check to make that we have delete sharing permission.
1919 * See https://bugzilla.xamarin.com/show_bug.cgi?id=17009
1921 * Do the checks that don't need an open file descriptor, for
1922 * simplicity's sake. If we really have to do the full checks
1923 * then we can implement that later.
1925 if (share_allows_delete (&stat_src, &shareinfo) == FALSE) {
1926 SetLastError (ERROR_SHARING_VIOLATION);
1927 return FALSE;
1929 if (shareinfo)
1930 _wapi_handle_share_release (shareinfo);
1932 result = _wapi_rename (utf8_name, utf8_dest_name);
1933 errno_copy = errno;
1935 if (result == -1) {
1936 switch(errno_copy) {
1937 case EEXIST:
1938 SetLastError (ERROR_ALREADY_EXISTS);
1939 break;
1941 case EXDEV:
1942 /* Ignore here, it is dealt with below */
1943 break;
1945 default:
1946 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1950 g_free (utf8_name);
1951 g_free (utf8_dest_name);
1953 if (result != 0 && errno_copy == EXDEV) {
1954 if (S_ISDIR (stat_src.st_mode)) {
1955 SetLastError (ERROR_NOT_SAME_DEVICE);
1956 return FALSE;
1958 /* Try a copy to the new location, and delete the source */
1959 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1960 /* CopyFile will set the error */
1961 return(FALSE);
1964 return(DeleteFile (name));
1967 if (result == 0) {
1968 ret = TRUE;
1971 return(ret);
1974 static gboolean
1975 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1977 int remain, n;
1978 char *buf, *wbuf;
1979 int buf_size = st_src->st_blksize;
1981 buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1982 buf = (char *) malloc (buf_size);
1984 for (;;) {
1985 remain = read (src_fd, buf, buf_size);
1986 if (remain < 0) {
1987 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1988 continue;
1990 if (report_errors)
1991 _wapi_set_last_error_from_errno ();
1993 free (buf);
1994 return FALSE;
1996 if (remain == 0) {
1997 break;
2000 wbuf = buf;
2001 while (remain > 0) {
2002 if ((n = write (dest_fd, wbuf, remain)) < 0) {
2003 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
2004 continue;
2006 if (report_errors)
2007 _wapi_set_last_error_from_errno ();
2008 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write failed.", __func__);
2009 free (buf);
2010 return FALSE;
2013 remain -= n;
2014 wbuf += n;
2018 free (buf);
2019 return TRUE ;
2023 * CopyFile:
2024 * @name: a pointer to a NULL-terminated unicode string, that names
2025 * the file to be copied.
2026 * @dest_name: a pointer to a NULL-terminated unicode string, that is the
2027 * new name for the file.
2028 * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
2030 * Copies file @name to @dest_name
2032 * Return value: %TRUE on success, %FALSE otherwise.
2034 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
2035 gboolean fail_if_exists)
2037 gchar *utf8_src, *utf8_dest;
2038 int src_fd, dest_fd;
2039 struct stat st, dest_st;
2040 struct utimbuf dest_time;
2041 gboolean ret = TRUE;
2042 int ret_utime;
2044 if(name==NULL) {
2045 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2047 SetLastError (ERROR_INVALID_NAME);
2048 return(FALSE);
2051 utf8_src = mono_unicode_to_external (name);
2052 if (utf8_src == NULL) {
2053 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of source returned NULL",
2054 __func__);
2056 SetLastError (ERROR_INVALID_PARAMETER);
2057 return(FALSE);
2060 if(dest_name==NULL) {
2061 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: dest is NULL", __func__);
2063 g_free (utf8_src);
2064 SetLastError (ERROR_INVALID_NAME);
2065 return(FALSE);
2068 utf8_dest = mono_unicode_to_external (dest_name);
2069 if (utf8_dest == NULL) {
2070 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of dest returned NULL",
2071 __func__);
2073 SetLastError (ERROR_INVALID_PARAMETER);
2075 g_free (utf8_src);
2077 return(FALSE);
2080 src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2081 if (src_fd < 0) {
2082 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2084 g_free (utf8_src);
2085 g_free (utf8_dest);
2087 return(FALSE);
2090 if (fstat (src_fd, &st) < 0) {
2091 _wapi_set_last_error_from_errno ();
2093 g_free (utf8_src);
2094 g_free (utf8_dest);
2095 close (src_fd);
2097 return(FALSE);
2100 /* Before trying to open/create the dest, we need to report a 'file busy'
2101 * error if src and dest are actually the same file. We do the check here to take
2102 * advantage of the IOMAP capability */
2103 if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev &&
2104 st.st_ino == dest_st.st_ino) {
2106 g_free (utf8_src);
2107 g_free (utf8_dest);
2108 close (src_fd);
2110 SetLastError (ERROR_SHARING_VIOLATION);
2111 return (FALSE);
2114 if (fail_if_exists) {
2115 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2116 } else {
2117 /* FIXME: it kinda sucks that this code path potentially scans
2118 * the directory twice due to the weird SetLastError()
2119 * behavior. */
2120 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2121 if (dest_fd < 0) {
2122 /* The file does not exist, try creating it */
2123 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2124 } else {
2125 /* Apparently this error is set if we
2126 * overwrite the dest file
2128 SetLastError (ERROR_ALREADY_EXISTS);
2131 if (dest_fd < 0) {
2132 _wapi_set_last_error_from_errno ();
2134 g_free (utf8_src);
2135 g_free (utf8_dest);
2136 close (src_fd);
2138 return(FALSE);
2141 if (!write_file (src_fd, dest_fd, &st, TRUE))
2142 ret = FALSE;
2144 close (src_fd);
2145 close (dest_fd);
2147 dest_time.modtime = st.st_mtime;
2148 dest_time.actime = st.st_atime;
2149 ret_utime = utime (utf8_dest, &dest_time);
2150 if (ret_utime == -1)
2151 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file [%s] utime failed: %s", __func__, utf8_dest, strerror(errno));
2153 g_free (utf8_src);
2154 g_free (utf8_dest);
2156 return ret;
2159 static gchar*
2160 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2162 gchar *utf8_ret;
2164 if (arg == NULL) {
2165 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: %s is NULL", __func__, arg_name);
2166 SetLastError (ERROR_INVALID_NAME);
2167 return NULL;
2170 utf8_ret = mono_unicode_to_external (arg);
2171 if (utf8_ret == NULL) {
2172 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of %s returned NULL",
2173 __func__, arg_name);
2174 SetLastError (ERROR_INVALID_PARAMETER);
2175 return NULL;
2178 return utf8_ret;
2181 gboolean
2182 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2183 const gunichar2 *backupFileName, guint32 replaceFlags,
2184 gpointer exclude, gpointer reserved)
2186 int result, backup_fd = -1,replaced_fd = -1;
2187 gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2188 struct stat stBackup;
2189 gboolean ret = FALSE;
2191 if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2192 return FALSE;
2193 if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2194 goto replace_cleanup;
2195 if (backupFileName != NULL) {
2196 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2197 goto replace_cleanup;
2200 if (utf8_backupFileName) {
2201 // Open the backup file for read so we can restore the file if an error occurs.
2202 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2203 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2204 if (result == -1)
2205 goto replace_cleanup;
2208 result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2209 if (result == -1) {
2210 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2211 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2212 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2213 replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2214 stBackup.st_mode);
2216 if (replaced_fd == -1)
2217 goto replace_cleanup;
2219 write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2222 goto replace_cleanup;
2225 ret = TRUE;
2227 replace_cleanup:
2228 g_free (utf8_replacedFileName);
2229 g_free (utf8_replacementFileName);
2230 g_free (utf8_backupFileName);
2231 if (backup_fd != -1)
2232 close (backup_fd);
2233 if (replaced_fd != -1)
2234 close (replaced_fd);
2235 return ret;
2239 * GetStdHandle:
2240 * @stdhandle: specifies the file descriptor
2242 * Returns a handle for stdin, stdout, or stderr. Always returns the
2243 * same handle for the same @stdhandle.
2245 * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2248 static mono_mutex_t stdhandle_mutex;
2250 gpointer GetStdHandle(WapiStdHandle stdhandle)
2252 struct _WapiHandle_file *file_handle;
2253 gpointer handle;
2254 int thr_ret, fd;
2255 const gchar *name;
2256 gboolean ok;
2258 switch(stdhandle) {
2259 case STD_INPUT_HANDLE:
2260 fd = 0;
2261 name = "<stdin>";
2262 break;
2264 case STD_OUTPUT_HANDLE:
2265 fd = 1;
2266 name = "<stdout>";
2267 break;
2269 case STD_ERROR_HANDLE:
2270 fd = 2;
2271 name = "<stderr>";
2272 break;
2274 default:
2275 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unknown standard handle type", __func__);
2277 SetLastError (ERROR_INVALID_PARAMETER);
2278 return(INVALID_HANDLE_VALUE);
2281 handle = GINT_TO_POINTER (fd);
2283 thr_ret = mono_os_mutex_lock (&stdhandle_mutex);
2284 g_assert (thr_ret == 0);
2286 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2287 (gpointer *)&file_handle);
2288 if (ok == FALSE) {
2289 /* Need to create this console handle */
2290 handle = _wapi_stdhandle_create (fd, name);
2292 if (handle == INVALID_HANDLE_VALUE) {
2293 SetLastError (ERROR_NO_MORE_FILES);
2294 goto done;
2296 } else {
2297 /* Add a reference to this handle */
2298 _wapi_handle_ref (handle);
2301 done:
2302 thr_ret = mono_os_mutex_unlock (&stdhandle_mutex);
2303 g_assert (thr_ret == 0);
2305 return(handle);
2309 * ReadFile:
2310 * @handle: The file handle to read from. The handle must have
2311 * %GENERIC_READ access.
2312 * @buffer: The buffer to store read data in
2313 * @numbytes: The maximum number of bytes to read
2314 * @bytesread: The actual number of bytes read is stored here. This
2315 * value can be zero if the handle is positioned at the end of the
2316 * file.
2317 * @overlapped: points to a required %WapiOverlapped structure if
2318 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2319 * otherwise.
2321 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2322 * function reads up to @numbytes bytes from the file from the current
2323 * file position, and stores them in @buffer. If there are not enough
2324 * bytes left in the file, just the amount available will be read.
2325 * The actual number of bytes read is stored in @bytesread.
2327 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2328 * file position is ignored and the read position is taken from data
2329 * in the @overlapped structure.
2331 * Return value: %TRUE if the read succeeds (even if no bytes were
2332 * read due to an attempt to read past the end of the file), %FALSE on
2333 * error.
2335 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2336 guint32 *bytesread, WapiOverlapped *overlapped)
2338 WapiHandleType type;
2340 type = _wapi_handle_type (handle);
2342 if(io_ops[type].readfile==NULL) {
2343 SetLastError (ERROR_INVALID_HANDLE);
2344 return(FALSE);
2347 return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2348 overlapped));
2352 * WriteFile:
2353 * @handle: The file handle to write to. The handle must have
2354 * %GENERIC_WRITE access.
2355 * @buffer: The buffer to read data from.
2356 * @numbytes: The maximum number of bytes to write.
2357 * @byteswritten: The actual number of bytes written is stored here.
2358 * If the handle is positioned at the file end, the length of the file
2359 * is extended. This parameter may be %NULL.
2360 * @overlapped: points to a required %WapiOverlapped structure if
2361 * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2362 * otherwise.
2364 * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2365 * function writes up to @numbytes bytes from @buffer to the file at
2366 * the current file position. If @handle is positioned at the end of
2367 * the file, the file is extended. The actual number of bytes written
2368 * is stored in @byteswritten.
2370 * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2371 * file position is ignored and the write position is taken from data
2372 * in the @overlapped structure.
2374 * Return value: %TRUE if the write succeeds, %FALSE on error.
2376 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2377 guint32 *byteswritten, WapiOverlapped *overlapped)
2379 WapiHandleType type;
2381 type = _wapi_handle_type (handle);
2383 if(io_ops[type].writefile==NULL) {
2384 SetLastError (ERROR_INVALID_HANDLE);
2385 return(FALSE);
2388 return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2389 overlapped));
2393 * FlushFileBuffers:
2394 * @handle: Handle to open file. The handle must have
2395 * %GENERIC_WRITE access.
2397 * Flushes buffers of the file and causes all unwritten data to
2398 * be written.
2400 * Return value: %TRUE on success, %FALSE otherwise.
2402 gboolean FlushFileBuffers(gpointer handle)
2404 WapiHandleType type;
2406 type = _wapi_handle_type (handle);
2408 if(io_ops[type].flushfile==NULL) {
2409 SetLastError (ERROR_INVALID_HANDLE);
2410 return(FALSE);
2413 return(io_ops[type].flushfile (handle));
2417 * SetEndOfFile:
2418 * @handle: The file handle to set. The handle must have
2419 * %GENERIC_WRITE access.
2421 * Moves the end-of-file position to the current position of the file
2422 * pointer. This function is used to truncate or extend a file.
2424 * Return value: %TRUE on success, %FALSE otherwise.
2426 gboolean SetEndOfFile(gpointer handle)
2428 WapiHandleType type;
2430 type = _wapi_handle_type (handle);
2432 if (io_ops[type].setendoffile == NULL) {
2433 SetLastError (ERROR_INVALID_HANDLE);
2434 return(FALSE);
2437 return(io_ops[type].setendoffile (handle));
2441 * SetFilePointer:
2442 * @handle: The file handle to set. The handle must have
2443 * %GENERIC_READ or %GENERIC_WRITE access.
2444 * @movedistance: Low 32 bits of a signed value that specifies the
2445 * number of bytes to move the file pointer.
2446 * @highmovedistance: Pointer to the high 32 bits of a signed value
2447 * that specifies the number of bytes to move the file pointer, or
2448 * %NULL.
2449 * @method: The starting point for the file pointer move.
2451 * Sets the file pointer of an open file.
2453 * The distance to move the file pointer is calculated from
2454 * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2455 * @movedistance is the 32-bit signed value; otherwise, @movedistance
2456 * is the low 32 bits and @highmovedistance a pointer to the high 32
2457 * bits of a 64 bit signed value. A positive distance moves the file
2458 * pointer forward from the position specified by @method; a negative
2459 * distance moves the file pointer backward.
2461 * If the library is compiled without large file support,
2462 * @highmovedistance is ignored and its value is set to zero on a
2463 * successful return.
2465 * Return value: On success, the low 32 bits of the new file pointer.
2466 * If @highmovedistance is not %NULL, the high 32 bits of the new file
2467 * pointer are stored there. On failure, %INVALID_SET_FILE_POINTER.
2469 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2470 gint32 *highmovedistance, WapiSeekMethod method)
2472 WapiHandleType type;
2474 type = _wapi_handle_type (handle);
2476 if (io_ops[type].seek == NULL) {
2477 SetLastError (ERROR_INVALID_HANDLE);
2478 return(INVALID_SET_FILE_POINTER);
2481 return(io_ops[type].seek (handle, movedistance, highmovedistance,
2482 method));
2486 * GetFileType:
2487 * @handle: The file handle to test.
2489 * Finds the type of file @handle.
2491 * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2492 * unknown. %FILE_TYPE_DISK - @handle is a disk file.
2493 * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2494 * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2496 WapiFileType GetFileType(gpointer handle)
2498 WapiHandleType type;
2500 type = _wapi_handle_type (handle);
2502 if (io_ops[type].getfiletype == NULL) {
2503 SetLastError (ERROR_INVALID_HANDLE);
2504 return(FILE_TYPE_UNKNOWN);
2507 return(io_ops[type].getfiletype ());
2511 * GetFileSize:
2512 * @handle: The file handle to query. The handle must have
2513 * %GENERIC_READ or %GENERIC_WRITE access.
2514 * @highsize: If non-%NULL, the high 32 bits of the file size are
2515 * stored here.
2517 * Retrieves the size of the file @handle.
2519 * If the library is compiled without large file support, @highsize
2520 * has its value set to zero on a successful return.
2522 * Return value: On success, the low 32 bits of the file size. If
2523 * @highsize is non-%NULL then the high 32 bits of the file size are
2524 * stored here. On failure %INVALID_FILE_SIZE is returned.
2526 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2528 WapiHandleType type;
2530 type = _wapi_handle_type (handle);
2532 if (io_ops[type].getfilesize == NULL) {
2533 SetLastError (ERROR_INVALID_HANDLE);
2534 return(INVALID_FILE_SIZE);
2537 return(io_ops[type].getfilesize (handle, highsize));
2541 * GetFileTime:
2542 * @handle: The file handle to query. The handle must have
2543 * %GENERIC_READ access.
2544 * @create_time: Points to a %WapiFileTime structure to receive the
2545 * number of ticks since the epoch that file was created. May be
2546 * %NULL.
2547 * @last_access: Points to a %WapiFileTime structure to receive the
2548 * number of ticks since the epoch when file was last accessed. May be
2549 * %NULL.
2550 * @last_write: Points to a %WapiFileTime structure to receive the
2551 * number of ticks since the epoch when file was last written to. May
2552 * be %NULL.
2554 * Finds the number of ticks since the epoch that the file referenced
2555 * by @handle was created, last accessed and last modified. A tick is
2556 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2557 * GMT.
2559 * Create time isn't recorded on POSIX file systems or reported by
2560 * stat(2), so that time is guessed by returning the oldest of the
2561 * other times.
2563 * Return value: %TRUE on success, %FALSE otherwise.
2565 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2566 WapiFileTime *last_access, WapiFileTime *last_write)
2568 WapiHandleType type;
2570 type = _wapi_handle_type (handle);
2572 if (io_ops[type].getfiletime == NULL) {
2573 SetLastError (ERROR_INVALID_HANDLE);
2574 return(FALSE);
2577 return(io_ops[type].getfiletime (handle, create_time, last_access,
2578 last_write));
2582 * SetFileTime:
2583 * @handle: The file handle to set. The handle must have
2584 * %GENERIC_WRITE access.
2585 * @create_time: Points to a %WapiFileTime structure that contains the
2586 * number of ticks since the epoch that the file was created. May be
2587 * %NULL.
2588 * @last_access: Points to a %WapiFileTime structure that contains the
2589 * number of ticks since the epoch when the file was last accessed.
2590 * May be %NULL.
2591 * @last_write: Points to a %WapiFileTime structure that contains the
2592 * number of ticks since the epoch when the file was last written to.
2593 * May be %NULL.
2595 * Sets the number of ticks since the epoch that the file referenced
2596 * by @handle was created, last accessed or last modified. A tick is
2597 * a 100 nanosecond interval. The epoch is Midnight, January 1 1601
2598 * GMT.
2600 * Create time isn't recorded on POSIX file systems, and is ignored.
2602 * Return value: %TRUE on success, %FALSE otherwise.
2604 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2605 const WapiFileTime *last_access,
2606 const WapiFileTime *last_write)
2608 WapiHandleType type;
2610 type = _wapi_handle_type (handle);
2612 if (io_ops[type].setfiletime == NULL) {
2613 SetLastError (ERROR_INVALID_HANDLE);
2614 return(FALSE);
2617 return(io_ops[type].setfiletime (handle, create_time, last_access,
2618 last_write));
2621 /* A tick is a 100-nanosecond interval. File time epoch is Midnight,
2622 * January 1 1601 GMT
2625 #define TICKS_PER_MILLISECOND 10000L
2626 #define TICKS_PER_SECOND 10000000L
2627 #define TICKS_PER_MINUTE 600000000L
2628 #define TICKS_PER_HOUR 36000000000LL
2629 #define TICKS_PER_DAY 864000000000LL
2631 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2633 static const guint16 mon_yday[2][13]={
2634 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2635 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2639 * FileTimeToSystemTime:
2640 * @file_time: Points to a %WapiFileTime structure that contains the
2641 * number of ticks to convert.
2642 * @system_time: Points to a %WapiSystemTime structure to receive the
2643 * broken-out time.
2645 * Converts a tick count into broken-out time values.
2647 * Return value: %TRUE on success, %FALSE otherwise.
2649 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2650 WapiSystemTime *system_time)
2652 gint64 file_ticks, totaldays, rem, y;
2653 const guint16 *ip;
2655 if(system_time==NULL) {
2656 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: system_time NULL", __func__);
2658 SetLastError (ERROR_INVALID_PARAMETER);
2659 return(FALSE);
2662 file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2663 file_time->dwLowDateTime;
2665 /* Really compares if file_ticks>=0x8000000000000000
2666 * (LLONG_MAX+1) but we're working with a signed value for the
2667 * year and day calculation to work later
2669 if(file_ticks<0) {
2670 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file_time too big", __func__);
2672 SetLastError (ERROR_INVALID_PARAMETER);
2673 return(FALSE);
2676 totaldays=(file_ticks / TICKS_PER_DAY);
2677 rem = file_ticks % TICKS_PER_DAY;
2678 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2680 system_time->wHour=rem/TICKS_PER_HOUR;
2681 rem %= TICKS_PER_HOUR;
2682 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2684 system_time->wMinute = rem / TICKS_PER_MINUTE;
2685 rem %= TICKS_PER_MINUTE;
2686 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2687 rem);
2689 system_time->wSecond = rem / TICKS_PER_SECOND;
2690 rem %= TICKS_PER_SECOND;
2691 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2692 rem);
2694 system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2695 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Milliseconds: %d", __func__,
2696 system_time->wMilliseconds);
2698 /* January 1, 1601 was a Monday, according to Emacs calendar */
2699 system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2700 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2702 /* This algorithm to find year and month given days from epoch
2703 * from glibc
2705 y=1601;
2707 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2708 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2710 while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2711 /* Guess a corrected year, assuming 365 days per year */
2712 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2713 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld yg: %lld y: %lld", __func__,
2714 totaldays, yg,
2716 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2717 LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2719 /* Adjust days and y to match the guessed year. */
2720 totaldays -= ((yg - y) * 365
2721 + LEAPS_THRU_END_OF (yg - 1)
2722 - LEAPS_THRU_END_OF (y - 1));
2723 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2724 y = yg;
2725 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: y: %lld", __func__, y);
2728 system_time->wYear = y;
2729 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Year: %d", __func__, system_time->wYear);
2731 ip = mon_yday[isleap(y)];
2733 for(y=11; totaldays < ip[y]; --y) {
2734 continue;
2736 totaldays-=ip[y];
2737 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2739 system_time->wMonth = y + 1;
2740 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Month: %d", __func__, system_time->wMonth);
2742 system_time->wDay = totaldays + 1;
2743 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day: %d", __func__, system_time->wDay);
2745 return(TRUE);
2748 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2750 struct _WapiHandle_find find_handle = {0};
2751 gpointer handle;
2752 gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2753 int result;
2755 if (pattern == NULL) {
2756 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: pattern is NULL", __func__);
2758 SetLastError (ERROR_PATH_NOT_FOUND);
2759 return(INVALID_HANDLE_VALUE);
2762 utf8_pattern = mono_unicode_to_external (pattern);
2763 if (utf8_pattern == NULL) {
2764 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2766 SetLastError (ERROR_INVALID_NAME);
2767 return(INVALID_HANDLE_VALUE);
2770 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for [%s]", __func__, utf8_pattern);
2772 /* Figure out which bit of the pattern is the directory */
2773 dir_part = _wapi_dirname (utf8_pattern);
2774 entry_part = _wapi_basename (utf8_pattern);
2776 #if 0
2777 /* Don't do this check for now, it breaks if directories
2778 * really do have metachars in their names (see bug 58116).
2779 * FIXME: Figure out a better solution to keep some checks...
2781 if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2782 SetLastError (ERROR_INVALID_NAME);
2783 g_free (dir_part);
2784 g_free (entry_part);
2785 g_free (utf8_pattern);
2786 return(INVALID_HANDLE_VALUE);
2788 #endif
2790 /* The pattern can specify a directory or a set of files.
2792 * The pattern can have wildcard characters ? and *, but only
2793 * in the section after the last directory delimiter. (Return
2794 * ERROR_INVALID_NAME if there are wildcards in earlier path
2795 * sections.) "*" has the usual 0-or-more chars meaning. "?"
2796 * means "match one character", "??" seems to mean "match one
2797 * or two characters", "???" seems to mean "match one, two or
2798 * three characters", etc. Windows will also try and match
2799 * the mangled "short name" of files, so 8 character patterns
2800 * with wildcards will show some surprising results.
2802 * All the written documentation I can find says that '?'
2803 * should only match one character, and doesn't mention '??',
2804 * '???' etc. I'm going to assume that the strict behaviour
2805 * (ie '???' means three and only three characters) is the
2806 * correct one, because that lets me use fnmatch(3) rather
2807 * than mess around with regexes.
2810 find_handle.namelist = NULL;
2811 result = _wapi_io_scandir (dir_part, entry_part,
2812 &find_handle.namelist);
2814 if (result == 0) {
2815 /* No files, which windows seems to call
2816 * FILE_NOT_FOUND
2818 SetLastError (ERROR_FILE_NOT_FOUND);
2819 g_free (utf8_pattern);
2820 g_free (entry_part);
2821 g_free (dir_part);
2822 return (INVALID_HANDLE_VALUE);
2825 if (result < 0) {
2826 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2827 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: scandir error: %s", __func__, g_strerror (errno));
2828 g_free (utf8_pattern);
2829 g_free (entry_part);
2830 g_free (dir_part);
2831 return (INVALID_HANDLE_VALUE);
2834 g_free (utf8_pattern);
2835 g_free (entry_part);
2837 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Got %d matches", __func__, result);
2839 find_handle.dir_part = dir_part;
2840 find_handle.num = result;
2841 find_handle.count = 0;
2843 handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2844 if (handle == _WAPI_HANDLE_INVALID) {
2845 g_warning ("%s: error creating find handle", __func__);
2846 g_free (dir_part);
2847 g_free (entry_part);
2848 g_free (utf8_pattern);
2849 SetLastError (ERROR_GEN_FAILURE);
2851 return(INVALID_HANDLE_VALUE);
2854 if (handle != INVALID_HANDLE_VALUE &&
2855 !FindNextFile (handle, find_data)) {
2856 FindClose (handle);
2857 SetLastError (ERROR_NO_MORE_FILES);
2858 handle = INVALID_HANDLE_VALUE;
2861 return (handle);
2864 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2866 struct _WapiHandle_find *find_handle;
2867 gboolean ok;
2868 struct stat buf, linkbuf;
2869 int result;
2870 gchar *filename;
2871 gchar *utf8_filename, *utf8_basename;
2872 gunichar2 *utf16_basename;
2873 time_t create_time;
2874 glong bytes;
2875 int thr_ret;
2876 gboolean ret = FALSE;
2878 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2879 (gpointer *)&find_handle);
2880 if(ok==FALSE) {
2881 g_warning ("%s: error looking up find handle %p", __func__,
2882 handle);
2883 SetLastError (ERROR_INVALID_HANDLE);
2884 return(FALSE);
2887 thr_ret = _wapi_handle_lock_handle (handle);
2888 g_assert (thr_ret == 0);
2890 retry:
2891 if (find_handle->count >= find_handle->num) {
2892 SetLastError (ERROR_NO_MORE_FILES);
2893 goto cleanup;
2896 /* stat next match */
2898 filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2900 result = _wapi_stat (filename, &buf);
2901 if (result == -1 && errno == ENOENT) {
2902 /* Might be a dangling symlink */
2903 result = _wapi_lstat (filename, &buf);
2906 if (result != 0) {
2907 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: stat failed: %s", __func__, filename);
2909 g_free (filename);
2910 goto retry;
2913 #ifndef __native_client__
2914 result = _wapi_lstat (filename, &linkbuf);
2915 if (result != 0) {
2916 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lstat failed: %s", __func__, filename);
2918 g_free (filename);
2919 goto retry;
2921 #endif
2923 utf8_filename = mono_utf8_from_external (filename);
2924 if (utf8_filename == NULL) {
2925 /* We couldn't turn this filename into utf8 (eg the
2926 * encoding of the name wasn't convertible), so just
2927 * ignore it.
2929 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2931 g_free (filename);
2932 goto retry;
2934 g_free (filename);
2936 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Found [%s]", __func__, utf8_filename);
2938 /* fill data block */
2940 if (buf.st_mtime < buf.st_ctime)
2941 create_time = buf.st_mtime;
2942 else
2943 create_time = buf.st_ctime;
2945 #ifdef __native_client__
2946 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, NULL);
2947 #else
2948 find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2949 #endif
2951 _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2952 _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2953 _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2955 if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2956 find_data->nFileSizeHigh = 0;
2957 find_data->nFileSizeLow = 0;
2958 } else {
2959 find_data->nFileSizeHigh = buf.st_size >> 32;
2960 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2963 find_data->dwReserved0 = 0;
2964 find_data->dwReserved1 = 0;
2966 utf8_basename = _wapi_basename (utf8_filename);
2967 utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2968 NULL);
2969 if(utf16_basename==NULL) {
2970 g_free (utf8_basename);
2971 g_free (utf8_filename);
2972 goto retry;
2974 ret = TRUE;
2976 /* utf16 is 2 * utf8 */
2977 bytes *= 2;
2979 memset (find_data->cFileName, '\0', (MAX_PATH*2));
2981 /* Truncating a utf16 string like this might leave the last
2982 * char incomplete
2984 memcpy (find_data->cFileName, utf16_basename,
2985 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
2987 find_data->cAlternateFileName [0] = 0; /* not used */
2989 g_free (utf8_basename);
2990 g_free (utf8_filename);
2991 g_free (utf16_basename);
2993 cleanup:
2994 thr_ret = _wapi_handle_unlock_handle (handle);
2995 g_assert (thr_ret == 0);
2997 return(ret);
3001 * FindClose:
3002 * @wapi_handle: the find handle to close.
3004 * Closes find handle @wapi_handle
3006 * Return value: %TRUE on success, %FALSE otherwise.
3008 gboolean FindClose (gpointer handle)
3010 struct _WapiHandle_find *find_handle;
3011 gboolean ok;
3012 int thr_ret;
3014 if (handle == NULL) {
3015 SetLastError (ERROR_INVALID_HANDLE);
3016 return(FALSE);
3019 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
3020 (gpointer *)&find_handle);
3021 if(ok==FALSE) {
3022 g_warning ("%s: error looking up find handle %p", __func__,
3023 handle);
3024 SetLastError (ERROR_INVALID_HANDLE);
3025 return(FALSE);
3028 thr_ret = _wapi_handle_lock_handle (handle);
3029 g_assert (thr_ret == 0);
3031 g_strfreev (find_handle->namelist);
3032 g_free (find_handle->dir_part);
3034 thr_ret = _wapi_handle_unlock_handle (handle);
3035 g_assert (thr_ret == 0);
3037 _wapi_handle_unref (handle);
3039 return(TRUE);
3043 * CreateDirectory:
3044 * @name: a pointer to a NULL-terminated unicode string, that names
3045 * the directory to be created.
3046 * @security: ignored for now
3048 * Creates directory @name
3050 * Return value: %TRUE on success, %FALSE otherwise.
3052 gboolean CreateDirectory (const gunichar2 *name,
3053 WapiSecurityAttributes *security)
3055 gchar *utf8_name;
3056 int result;
3058 if (name == NULL) {
3059 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3061 SetLastError (ERROR_INVALID_NAME);
3062 return(FALSE);
3065 utf8_name = mono_unicode_to_external (name);
3066 if (utf8_name == NULL) {
3067 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3069 SetLastError (ERROR_INVALID_NAME);
3070 return FALSE;
3073 result = _wapi_mkdir (utf8_name, 0777);
3075 if (result == 0) {
3076 g_free (utf8_name);
3077 return TRUE;
3080 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3081 g_free (utf8_name);
3082 return FALSE;
3086 * RemoveDirectory:
3087 * @name: a pointer to a NULL-terminated unicode string, that names
3088 * the directory to be removed.
3090 * Removes directory @name
3092 * Return value: %TRUE on success, %FALSE otherwise.
3094 gboolean RemoveDirectory (const gunichar2 *name)
3096 gchar *utf8_name;
3097 int result;
3099 if (name == NULL) {
3100 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3102 SetLastError (ERROR_INVALID_NAME);
3103 return(FALSE);
3106 utf8_name = mono_unicode_to_external (name);
3107 if (utf8_name == NULL) {
3108 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3110 SetLastError (ERROR_INVALID_NAME);
3111 return FALSE;
3114 result = _wapi_rmdir (utf8_name);
3115 if (result == -1) {
3116 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3117 g_free (utf8_name);
3119 return(FALSE);
3121 g_free (utf8_name);
3123 return(TRUE);
3127 * GetFileAttributes:
3128 * @name: a pointer to a NULL-terminated unicode filename.
3130 * Gets the attributes for @name;
3132 * Return value: %INVALID_FILE_ATTRIBUTES on failure
3134 guint32 GetFileAttributes (const gunichar2 *name)
3136 gchar *utf8_name;
3137 struct stat buf, linkbuf;
3138 int result;
3139 guint32 ret;
3141 if (name == NULL) {
3142 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3144 SetLastError (ERROR_INVALID_NAME);
3145 return(FALSE);
3148 utf8_name = mono_unicode_to_external (name);
3149 if (utf8_name == NULL) {
3150 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3152 SetLastError (ERROR_INVALID_PARAMETER);
3153 return (INVALID_FILE_ATTRIBUTES);
3156 result = _wapi_stat (utf8_name, &buf);
3157 if (result == -1 && errno == ENOENT) {
3158 /* Might be a dangling symlink... */
3159 result = _wapi_lstat (utf8_name, &buf);
3162 if (result != 0) {
3163 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3164 g_free (utf8_name);
3165 return (INVALID_FILE_ATTRIBUTES);
3168 #ifndef __native_client__
3169 result = _wapi_lstat (utf8_name, &linkbuf);
3170 if (result != 0) {
3171 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3172 g_free (utf8_name);
3173 return (INVALID_FILE_ATTRIBUTES);
3175 #endif
3177 #ifdef __native_client__
3178 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, NULL);
3179 #else
3180 ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3181 #endif
3183 g_free (utf8_name);
3185 return(ret);
3189 * GetFileAttributesEx:
3190 * @name: a pointer to a NULL-terminated unicode filename.
3191 * @level: must be GetFileExInfoStandard
3192 * @info: pointer to a WapiFileAttributesData structure
3194 * Gets attributes, size and filetimes for @name;
3196 * Return value: %TRUE on success, %FALSE on failure
3198 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3200 gchar *utf8_name;
3201 WapiFileAttributesData *data;
3203 struct stat buf, linkbuf;
3204 time_t create_time;
3205 int result;
3207 if (level != GetFileExInfoStandard) {
3208 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: info level %d not supported.", __func__,
3209 level);
3211 SetLastError (ERROR_INVALID_PARAMETER);
3212 return FALSE;
3215 if (name == NULL) {
3216 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3218 SetLastError (ERROR_INVALID_NAME);
3219 return(FALSE);
3222 utf8_name = mono_unicode_to_external (name);
3223 if (utf8_name == NULL) {
3224 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3226 SetLastError (ERROR_INVALID_PARAMETER);
3227 return FALSE;
3230 result = _wapi_stat (utf8_name, &buf);
3231 if (result == -1 && errno == ENOENT) {
3232 /* Might be a dangling symlink... */
3233 result = _wapi_lstat (utf8_name, &buf);
3236 if (result != 0) {
3237 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3238 g_free (utf8_name);
3239 return FALSE;
3242 result = _wapi_lstat (utf8_name, &linkbuf);
3243 if (result != 0) {
3244 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3245 g_free (utf8_name);
3246 return(FALSE);
3249 /* fill data block */
3251 data = (WapiFileAttributesData *)info;
3253 if (buf.st_mtime < buf.st_ctime)
3254 create_time = buf.st_mtime;
3255 else
3256 create_time = buf.st_ctime;
3258 data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3259 &buf,
3260 &linkbuf);
3262 g_free (utf8_name);
3264 _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3265 _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3266 _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3268 if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3269 data->nFileSizeHigh = 0;
3270 data->nFileSizeLow = 0;
3272 else {
3273 data->nFileSizeHigh = buf.st_size >> 32;
3274 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3277 return TRUE;
3281 * SetFileAttributes
3282 * @name: name of file
3283 * @attrs: attributes to set
3285 * Changes the attributes on a named file.
3287 * Return value: %TRUE on success, %FALSE on failure.
3289 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3291 /* FIXME: think of something clever to do on unix */
3292 gchar *utf8_name;
3293 struct stat buf;
3294 int result;
3297 * Currently we only handle one *internal* case, with a value that is
3298 * not standard: 0x80000000, which means `set executable bit'
3301 if (name == NULL) {
3302 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3304 SetLastError (ERROR_INVALID_NAME);
3305 return(FALSE);
3308 utf8_name = mono_unicode_to_external (name);
3309 if (utf8_name == NULL) {
3310 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3312 SetLastError (ERROR_INVALID_NAME);
3313 return FALSE;
3316 result = _wapi_stat (utf8_name, &buf);
3317 if (result == -1 && errno == ENOENT) {
3318 /* Might be a dangling symlink... */
3319 result = _wapi_lstat (utf8_name, &buf);
3322 if (result != 0) {
3323 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3324 g_free (utf8_name);
3325 return FALSE;
3328 /* Contrary to the documentation, ms allows NORMAL to be
3329 * specified along with other attributes, so dont bother to
3330 * catch that case here.
3332 if (attrs & FILE_ATTRIBUTE_READONLY) {
3333 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWUSR | S_IWOTH | S_IWGRP));
3334 } else {
3335 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWUSR);
3338 /* Ignore the other attributes for now */
3340 if (attrs & 0x80000000){
3341 mode_t exec_mask = 0;
3343 if ((buf.st_mode & S_IRUSR) != 0)
3344 exec_mask |= S_IXUSR;
3346 if ((buf.st_mode & S_IRGRP) != 0)
3347 exec_mask |= S_IXGRP;
3349 if ((buf.st_mode & S_IROTH) != 0)
3350 exec_mask |= S_IXOTH;
3352 result = chmod (utf8_name, buf.st_mode | exec_mask);
3354 /* Don't bother to reset executable (might need to change this
3355 * policy)
3358 g_free (utf8_name);
3360 return(TRUE);
3364 * GetCurrentDirectory
3365 * @length: size of the buffer
3366 * @buffer: pointer to buffer that recieves path
3368 * Retrieves the current directory for the current process.
3370 * Return value: number of characters in buffer on success, zero on failure
3372 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3374 gunichar2 *utf16_path;
3375 glong count;
3376 gsize bytes;
3378 #ifdef __native_client__
3379 gchar *path = g_get_current_dir ();
3380 if (length < strlen(path) + 1 || path == NULL)
3381 return 0;
3382 memcpy (buffer, path, strlen(path) + 1);
3383 #else
3384 if (getcwd ((char*)buffer, length) == NULL) {
3385 if (errno == ERANGE) { /*buffer length is not big enough */
3386 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*/
3387 if (path == NULL)
3388 return 0;
3389 utf16_path = mono_unicode_from_external (path, &bytes);
3390 g_free (utf16_path);
3391 g_free (path);
3392 return (bytes/2)+1;
3394 _wapi_set_last_error_from_errno ();
3395 return 0;
3397 #endif
3399 utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3400 count = (bytes/2)+1;
3401 g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3403 /* Add the terminator */
3404 memset (buffer, '\0', bytes+2);
3405 memcpy (buffer, utf16_path, bytes);
3407 g_free (utf16_path);
3409 return count;
3413 * SetCurrentDirectory
3414 * @path: path to new directory
3416 * Changes the directory path for the current process.
3418 * Return value: %TRUE on success, %FALSE on failure.
3420 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3422 gchar *utf8_path;
3423 gboolean result;
3425 if (path == NULL) {
3426 SetLastError (ERROR_INVALID_PARAMETER);
3427 return(FALSE);
3430 utf8_path = mono_unicode_to_external (path);
3431 if (_wapi_chdir (utf8_path) != 0) {
3432 _wapi_set_last_error_from_errno ();
3433 result = FALSE;
3435 else
3436 result = TRUE;
3438 g_free (utf8_path);
3439 return result;
3442 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3443 WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3445 struct _WapiHandle_file pipe_read_handle = {0};
3446 struct _WapiHandle_file pipe_write_handle = {0};
3447 gpointer read_handle;
3448 gpointer write_handle;
3449 int filedes[2];
3450 int ret;
3452 mono_once (&io_ops_once, io_ops_init);
3454 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Creating pipe", __func__);
3456 ret=pipe (filedes);
3457 if(ret==-1) {
3458 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error creating pipe: %s", __func__,
3459 strerror (errno));
3461 _wapi_set_last_error_from_errno ();
3462 return(FALSE);
3465 if (filedes[0] >= _wapi_fd_reserve ||
3466 filedes[1] >= _wapi_fd_reserve) {
3467 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
3469 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3471 close (filedes[0]);
3472 close (filedes[1]);
3474 return(FALSE);
3477 /* filedes[0] is open for reading, filedes[1] for writing */
3479 pipe_read_handle.fd = filedes [0];
3480 pipe_read_handle.fileaccess = GENERIC_READ;
3481 read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3482 &pipe_read_handle);
3483 if (read_handle == _WAPI_HANDLE_INVALID) {
3484 g_warning ("%s: error creating pipe read handle", __func__);
3485 close (filedes[0]);
3486 close (filedes[1]);
3487 SetLastError (ERROR_GEN_FAILURE);
3489 return(FALSE);
3492 pipe_write_handle.fd = filedes [1];
3493 pipe_write_handle.fileaccess = GENERIC_WRITE;
3494 write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3495 &pipe_write_handle);
3496 if (write_handle == _WAPI_HANDLE_INVALID) {
3497 g_warning ("%s: error creating pipe write handle", __func__);
3498 _wapi_handle_unref (read_handle);
3500 close (filedes[0]);
3501 close (filedes[1]);
3502 SetLastError (ERROR_GEN_FAILURE);
3504 return(FALSE);
3507 *readpipe = read_handle;
3508 *writepipe = write_handle;
3510 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning pipe: read handle %p, write handle %p",
3511 __func__, read_handle, write_handle);
3513 return(TRUE);
3516 #ifdef HAVE_GETFSSTAT
3517 /* Darwin has getfsstat */
3518 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3520 struct statfs *stats;
3521 int size, n, i;
3522 gunichar2 *dir;
3523 glong length, total = 0;
3525 n = getfsstat (NULL, 0, MNT_NOWAIT);
3526 if (n == -1)
3527 return 0;
3528 size = n * sizeof (struct statfs);
3529 stats = (struct statfs *) g_malloc (size);
3530 if (stats == NULL)
3531 return 0;
3532 if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3533 g_free (stats);
3534 return 0;
3536 for (i = 0; i < n; i++){
3537 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3538 if (total + length < len){
3539 memcpy (buf + total, dir, sizeof (gunichar2) * length);
3540 buf [total+length] = 0;
3542 g_free (dir);
3543 total += length + 1;
3545 if (total < len)
3546 buf [total] = 0;
3547 total++;
3548 g_free (stats);
3549 return total;
3551 #else
3552 /* In-place octal sequence replacement */
3553 static void
3554 unescape_octal (gchar *str)
3556 gchar *rptr;
3557 gchar *wptr;
3559 if (str == NULL)
3560 return;
3562 rptr = wptr = str;
3563 while (*rptr != '\0') {
3564 if (*rptr == '\\') {
3565 char c;
3566 rptr++;
3567 c = (*(rptr++) - '0') << 6;
3568 c += (*(rptr++) - '0') << 3;
3569 c += *(rptr++) - '0';
3570 *wptr++ = c;
3571 } else if (wptr != rptr) {
3572 *wptr++ = *rptr++;
3573 } else {
3574 rptr++; wptr++;
3577 *wptr = '\0';
3579 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3581 #if __linux__
3582 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3583 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3584 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3586 typedef struct
3588 glong total;
3589 guint32 buffer_index;
3590 guint32 mountpoint_index;
3591 guint32 field_number;
3592 guint32 allocated_size;
3593 guint32 fsname_index;
3594 guint32 fstype_index;
3595 gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3596 gchar *mountpoint_allocated;
3597 gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3598 gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3599 gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3600 ssize_t nbytes;
3601 gchar delimiter;
3602 gboolean check_mount_source;
3603 } LinuxMountInfoParseState;
3605 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3606 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3607 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3608 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3610 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3612 int fd;
3613 gint32 ret = 0;
3614 LinuxMountInfoParseState state;
3615 gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3617 memset (buf, 0, len * sizeof (gunichar2));
3618 fd = open ("/proc/self/mountinfo", O_RDONLY);
3619 if (fd != -1)
3620 parser = GetLogicalDriveStrings_MountInfo;
3621 else {
3622 fd = open ("/proc/mounts", O_RDONLY);
3623 if (fd != -1)
3624 parser = GetLogicalDriveStrings_Mounts;
3627 if (!parser) {
3628 ret = GetLogicalDriveStrings_Mtab (len, buf);
3629 goto done_and_out;
3632 memset (&state, 0, sizeof (LinuxMountInfoParseState));
3633 state.field_number = 1;
3634 state.delimiter = ' ';
3636 while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3637 state.buffer_index = 0;
3639 while ((*parser)(len, buf, &state)) {
3640 if (state.buffer [state.buffer_index] == '\n') {
3641 gboolean quit = add_drive_string (len, buf, &state);
3642 state.field_number = 1;
3643 state.buffer_index++;
3644 if (state.mountpoint_allocated) {
3645 g_free (state.mountpoint_allocated);
3646 state.mountpoint_allocated = NULL;
3648 if (quit) {
3649 ret = state.total;
3650 goto done_and_out;
3655 ret = state.total;
3657 done_and_out:
3658 if (fd != -1)
3659 close (fd);
3660 return ret;
3663 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3665 gchar *ptr;
3667 if (state->field_number == 1)
3668 state->check_mount_source = TRUE;
3670 while (state->buffer_index < (guint32)state->nbytes) {
3671 if (state->buffer [state->buffer_index] == state->delimiter) {
3672 state->field_number++;
3673 switch (state->field_number) {
3674 case 2:
3675 state->mountpoint_index = 0;
3676 break;
3678 case 3:
3679 if (state->mountpoint_allocated)
3680 state->mountpoint_allocated [state->mountpoint_index] = 0;
3681 else
3682 state->mountpoint [state->mountpoint_index] = 0;
3683 break;
3685 default:
3686 ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3687 if (ptr)
3688 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3689 else
3690 state->buffer_index = state->nbytes;
3691 return TRUE;
3693 state->buffer_index++;
3694 continue;
3695 } else if (state->buffer [state->buffer_index] == '\n')
3696 return TRUE;
3698 switch (state->field_number) {
3699 case 1:
3700 if (state->check_mount_source) {
3701 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3702 /* We can ignore the rest, it's a device
3703 * path */
3704 state->check_mount_source = FALSE;
3705 state->fsname [state->fsname_index++] = '/';
3706 break;
3708 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3709 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3711 break;
3713 case 2:
3714 append_to_mountpoint (state);
3715 break;
3717 case 3:
3718 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3719 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3720 break;
3723 state->buffer_index++;
3726 return FALSE;
3729 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3731 while (state->buffer_index < (guint32)state->nbytes) {
3732 if (state->buffer [state->buffer_index] == state->delimiter) {
3733 state->field_number++;
3734 switch (state->field_number) {
3735 case 5:
3736 state->mountpoint_index = 0;
3737 break;
3739 case 6:
3740 if (state->mountpoint_allocated)
3741 state->mountpoint_allocated [state->mountpoint_index] = 0;
3742 else
3743 state->mountpoint [state->mountpoint_index] = 0;
3744 break;
3746 case 7:
3747 state->delimiter = '-';
3748 break;
3750 case 8:
3751 state->delimiter = ' ';
3752 break;
3754 case 10:
3755 state->check_mount_source = TRUE;
3756 break;
3758 state->buffer_index++;
3759 continue;
3760 } else if (state->buffer [state->buffer_index] == '\n')
3761 return TRUE;
3763 switch (state->field_number) {
3764 case 5:
3765 append_to_mountpoint (state);
3766 break;
3768 case 9:
3769 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3770 state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3771 break;
3773 case 10:
3774 if (state->check_mount_source) {
3775 if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3776 /* We can ignore the rest, it's a device
3777 * path */
3778 state->check_mount_source = FALSE;
3779 state->fsname [state->fsname_index++] = '/';
3780 break;
3782 if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3783 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3785 break;
3788 state->buffer_index++;
3791 return FALSE;
3794 static void
3795 append_to_mountpoint (LinuxMountInfoParseState *state)
3797 gchar ch = state->buffer [state->buffer_index];
3798 if (state->mountpoint_allocated) {
3799 if (state->mountpoint_index >= state->allocated_size) {
3800 guint32 newsize = (state->allocated_size << 1) + 1;
3801 gchar *newbuf = (gchar *)g_malloc0 (newsize * sizeof (gchar));
3803 memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3804 g_free (state->mountpoint_allocated);
3805 state->mountpoint_allocated = newbuf;
3806 state->allocated_size = newsize;
3808 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3809 } else {
3810 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3811 state->allocated_size = (state->mountpoint_index << 1) + 1;
3812 state->mountpoint_allocated = (gchar *)g_malloc0 (state->allocated_size * sizeof (gchar));
3813 memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3814 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3815 } else
3816 state->mountpoint [state->mountpoint_index++] = ch;
3820 static gboolean
3821 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3823 gboolean quit = FALSE;
3824 gboolean ignore_entry;
3826 if (state->fsname_index == 1 && state->fsname [0] == '/')
3827 ignore_entry = FALSE;
3828 else if (memcmp ("overlay", state->fsname, state->fsname_index) == 0 ||
3829 memcmp ("aufs", state->fstype, state->fstype_index) == 0) {
3830 /* Don't ignore overlayfs and aufs - these might be used on Docker
3831 * (https://bugzilla.xamarin.com/show_bug.cgi?id=31021) */
3832 ignore_entry = FALSE;
3833 } else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0) {
3834 ignore_entry = TRUE;
3835 } else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3836 /* Ignore GNOME's gvfs */
3837 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3838 ignore_entry = TRUE;
3839 else
3840 ignore_entry = FALSE;
3841 } else if (state->fstype_index == 3 && memcmp ("nfs", state->fstype, state->fstype_index) == 0)
3842 ignore_entry = FALSE;
3843 else
3844 ignore_entry = TRUE;
3846 if (!ignore_entry) {
3847 gunichar2 *dir;
3848 glong length;
3849 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3851 unescape_octal (mountpoint);
3852 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3853 if (state->total + length + 1 > len) {
3854 quit = TRUE;
3855 state->total = len * 2;
3856 } else {
3857 length++;
3858 memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3859 state->total += length;
3861 g_free (dir);
3863 state->fsname_index = 0;
3864 state->fstype_index = 0;
3866 return quit;
3868 #else
3869 gint32
3870 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3872 return GetLogicalDriveStrings_Mtab (len, buf);
3874 #endif
3875 static gint32
3876 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3878 FILE *fp;
3879 gunichar2 *ptr, *dir;
3880 glong length, total = 0;
3881 gchar buffer [512];
3882 gchar **splitted;
3884 memset (buf, 0, sizeof (gunichar2) * (len + 1));
3885 buf [0] = '/';
3886 buf [1] = 0;
3887 buf [2] = 0;
3889 /* Sigh, mntent and friends don't work well.
3890 * It stops on the first line that doesn't begin with a '/'.
3891 * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3892 fp = fopen ("/etc/mtab", "rt");
3893 if (fp == NULL) {
3894 fp = fopen ("/etc/mnttab", "rt");
3895 if (fp == NULL)
3896 return 1;
3899 ptr = buf;
3900 while (fgets (buffer, 512, fp) != NULL) {
3901 if (*buffer != '/')
3902 continue;
3904 splitted = g_strsplit (buffer, " ", 0);
3905 if (!*splitted || !*(splitted + 1)) {
3906 g_strfreev (splitted);
3907 continue;
3910 unescape_octal (*(splitted + 1));
3911 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3912 g_strfreev (splitted);
3913 if (total + length + 1 > len) {
3914 fclose (fp);
3915 g_free (dir);
3916 return len * 2; /* guess */
3919 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3920 g_free (dir);
3921 total += length + 1;
3924 fclose (fp);
3925 return total;
3926 /* Commented out, does not work with my mtab!!! - Gonz */
3927 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3929 FILE *fp;
3930 struct mntent *mnt;
3931 gunichar2 *ptr, *dir;
3932 glong len, total = 0;
3935 fp = setmntent ("/etc/mtab", "rt");
3936 if (fp == NULL) {
3937 fp = setmntent ("/etc/mnttab", "rt");
3938 if (fp == NULL)
3939 return;
3942 ptr = buf;
3943 while ((mnt = getmntent (fp)) != NULL) {
3944 g_print ("GOT %s\n", mnt->mnt_dir);
3945 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3946 if (total + len + 1 > len) {
3947 return len * 2; /* guess */
3950 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3951 g_free (dir);
3952 total += len + 1;
3955 endmntent (fp);
3956 return total;
3958 #endif
3960 #endif
3962 #if defined(HAVE_STATVFS) || defined(HAVE_STATFS)
3963 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3964 WapiULargeInteger *total_number_of_bytes,
3965 WapiULargeInteger *total_number_of_free_bytes)
3967 #ifdef HAVE_STATVFS
3968 struct statvfs fsstat;
3969 #elif defined(HAVE_STATFS)
3970 struct statfs fsstat;
3971 #endif
3972 gboolean isreadonly;
3973 gchar *utf8_path_name;
3974 int ret;
3975 unsigned long block_size;
3977 if (path_name == NULL) {
3978 utf8_path_name = g_strdup (g_get_current_dir());
3979 if (utf8_path_name == NULL) {
3980 SetLastError (ERROR_DIRECTORY);
3981 return(FALSE);
3984 else {
3985 utf8_path_name = mono_unicode_to_external (path_name);
3986 if (utf8_path_name == NULL) {
3987 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3989 SetLastError (ERROR_INVALID_NAME);
3990 return(FALSE);
3994 do {
3995 #ifdef HAVE_STATVFS
3996 ret = statvfs (utf8_path_name, &fsstat);
3997 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
3998 block_size = fsstat.f_frsize;
3999 #elif defined(HAVE_STATFS)
4000 ret = statfs (utf8_path_name, &fsstat);
4001 #if defined (MNT_RDONLY)
4002 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
4003 #elif defined (MS_RDONLY)
4004 isreadonly = ((fsstat.f_flags & MS_RDONLY) == MS_RDONLY);
4005 #endif
4006 block_size = fsstat.f_bsize;
4007 #endif
4008 } while(ret == -1 && errno == EINTR);
4010 g_free(utf8_path_name);
4012 if (ret == -1) {
4013 _wapi_set_last_error_from_errno ();
4014 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: statvfs failed: %s", __func__, strerror (errno));
4015 return(FALSE);
4018 /* total number of free bytes for non-root */
4019 if (free_bytes_avail != NULL) {
4020 if (isreadonly) {
4021 free_bytes_avail->QuadPart = 0;
4023 else {
4024 free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
4028 /* total number of bytes available for non-root */
4029 if (total_number_of_bytes != NULL) {
4030 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
4033 /* total number of bytes available for root */
4034 if (total_number_of_free_bytes != NULL) {
4035 if (isreadonly) {
4036 total_number_of_free_bytes->QuadPart = 0;
4038 else {
4039 total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
4043 return(TRUE);
4045 #else
4046 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4047 WapiULargeInteger *total_number_of_bytes,
4048 WapiULargeInteger *total_number_of_free_bytes)
4050 if (free_bytes_avail != NULL) {
4051 free_bytes_avail->QuadPart = (guint64) -1;
4054 if (total_number_of_bytes != NULL) {
4055 total_number_of_bytes->QuadPart = (guint64) -1;
4058 if (total_number_of_free_bytes != NULL) {
4059 total_number_of_free_bytes->QuadPart = (guint64) -1;
4062 return(TRUE);
4064 #endif
4067 * General Unix support
4069 typedef struct {
4070 guint32 drive_type;
4071 #if __linux__
4072 const long fstypeid;
4073 #endif
4074 const gchar* fstype;
4075 } _wapi_drive_type;
4077 static _wapi_drive_type _wapi_drive_types[] = {
4078 #if PLATFORM_MACOSX
4079 { DRIVE_REMOTE, "afp" },
4080 { DRIVE_REMOTE, "autofs" },
4081 { DRIVE_CDROM, "cddafs" },
4082 { DRIVE_CDROM, "cd9660" },
4083 { DRIVE_RAMDISK, "devfs" },
4084 { DRIVE_FIXED, "exfat" },
4085 { DRIVE_RAMDISK, "fdesc" },
4086 { DRIVE_REMOTE, "ftp" },
4087 { DRIVE_FIXED, "hfs" },
4088 { DRIVE_FIXED, "msdos" },
4089 { DRIVE_REMOTE, "nfs" },
4090 { DRIVE_FIXED, "ntfs" },
4091 { DRIVE_REMOTE, "smbfs" },
4092 { DRIVE_FIXED, "udf" },
4093 { DRIVE_REMOTE, "webdav" },
4094 { DRIVE_UNKNOWN, NULL }
4095 #elif __linux__
4096 { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
4097 { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
4098 { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
4099 { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
4100 { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
4101 { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
4102 { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
4103 { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
4104 { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
4105 { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
4106 { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
4107 { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
4108 { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
4109 { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
4110 { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
4111 { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
4112 { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
4113 { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4114 { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4115 { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4116 { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4117 { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4118 { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4119 { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4120 { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4121 { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4122 { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4123 { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4124 { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4125 { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4126 { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4127 { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4128 { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4129 { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4130 { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4131 { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4132 { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4133 { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4134 { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4135 { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4136 { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4137 { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4138 { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4139 { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4140 { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4141 { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4142 { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4143 { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4144 { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4145 { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4146 { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4147 { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4148 { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4149 { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4150 { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4151 { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4152 { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4153 { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4154 { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4155 { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4156 { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4157 { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4158 { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4159 { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4160 { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4161 { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4162 { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4163 { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4164 { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4165 { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4166 { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4167 { DRIVE_UNKNOWN, 0, NULL}
4168 #else
4169 { DRIVE_RAMDISK, "ramfs" },
4170 { DRIVE_RAMDISK, "tmpfs" },
4171 { DRIVE_RAMDISK, "proc" },
4172 { DRIVE_RAMDISK, "sysfs" },
4173 { DRIVE_RAMDISK, "debugfs" },
4174 { DRIVE_RAMDISK, "devpts" },
4175 { DRIVE_RAMDISK, "securityfs" },
4176 { DRIVE_CDROM, "iso9660" },
4177 { DRIVE_FIXED, "ext2" },
4178 { DRIVE_FIXED, "ext3" },
4179 { DRIVE_FIXED, "ext4" },
4180 { DRIVE_FIXED, "sysv" },
4181 { DRIVE_FIXED, "reiserfs" },
4182 { DRIVE_FIXED, "ufs" },
4183 { DRIVE_FIXED, "vfat" },
4184 { DRIVE_FIXED, "msdos" },
4185 { DRIVE_FIXED, "udf" },
4186 { DRIVE_FIXED, "hfs" },
4187 { DRIVE_FIXED, "hpfs" },
4188 { DRIVE_FIXED, "qnx4" },
4189 { DRIVE_FIXED, "ntfs" },
4190 { DRIVE_FIXED, "ntfs-3g" },
4191 { DRIVE_REMOTE, "smbfs" },
4192 { DRIVE_REMOTE, "fuse" },
4193 { DRIVE_REMOTE, "nfs" },
4194 { DRIVE_REMOTE, "nfs4" },
4195 { DRIVE_REMOTE, "cifs" },
4196 { DRIVE_REMOTE, "ncpfs" },
4197 { DRIVE_REMOTE, "coda" },
4198 { DRIVE_REMOTE, "afs" },
4199 { DRIVE_UNKNOWN, NULL }
4200 #endif
4203 #if __linux__
4204 static guint32 _wapi_get_drive_type(long f_type)
4206 _wapi_drive_type *current;
4208 current = &_wapi_drive_types[0];
4209 while (current->drive_type != DRIVE_UNKNOWN) {
4210 if (current->fstypeid == f_type)
4211 return current->drive_type;
4212 current++;
4215 return DRIVE_UNKNOWN;
4217 #else
4218 static guint32 _wapi_get_drive_type(const gchar* fstype)
4220 _wapi_drive_type *current;
4222 current = &_wapi_drive_types[0];
4223 while (current->drive_type != DRIVE_UNKNOWN) {
4224 if (strcmp (current->fstype, fstype) == 0)
4225 break;
4227 current++;
4230 return current->drive_type;
4232 #endif
4234 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4235 static guint32
4236 GetDriveTypeFromPath (const char *utf8_root_path_name)
4238 struct statfs buf;
4240 if (statfs (utf8_root_path_name, &buf) == -1)
4241 return DRIVE_UNKNOWN;
4242 #if PLATFORM_MACOSX
4243 return _wapi_get_drive_type (buf.f_fstypename);
4244 #else
4245 return _wapi_get_drive_type (buf.f_type);
4246 #endif
4248 #else
4249 static guint32
4250 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4252 guint32 drive_type;
4253 FILE *fp;
4254 gchar buffer [512];
4255 gchar **splitted;
4257 fp = fopen ("/etc/mtab", "rt");
4258 if (fp == NULL) {
4259 fp = fopen ("/etc/mnttab", "rt");
4260 if (fp == NULL)
4261 return(DRIVE_UNKNOWN);
4264 drive_type = DRIVE_NO_ROOT_DIR;
4265 while (fgets (buffer, 512, fp) != NULL) {
4266 splitted = g_strsplit (buffer, " ", 0);
4267 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4268 g_strfreev (splitted);
4269 continue;
4272 /* compare given root_path_name with the one from mtab,
4273 if length of utf8_root_path_name is zero it must be the root dir */
4274 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4275 (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4276 drive_type = _wapi_get_drive_type (*(splitted + 2));
4277 /* it is possible this path might be mounted again with
4278 a known type...keep looking */
4279 if (drive_type != DRIVE_UNKNOWN) {
4280 g_strfreev (splitted);
4281 break;
4285 g_strfreev (splitted);
4288 fclose (fp);
4289 return drive_type;
4291 #endif
4293 guint32 GetDriveType(const gunichar2 *root_path_name)
4295 gchar *utf8_root_path_name;
4296 guint32 drive_type;
4298 if (root_path_name == NULL) {
4299 utf8_root_path_name = g_strdup (g_get_current_dir());
4300 if (utf8_root_path_name == NULL) {
4301 return(DRIVE_NO_ROOT_DIR);
4304 else {
4305 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4306 if (utf8_root_path_name == NULL) {
4307 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4308 return(DRIVE_NO_ROOT_DIR);
4311 /* strip trailing slash for compare below */
4312 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4313 utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4316 drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4317 g_free (utf8_root_path_name);
4319 return (drive_type);
4322 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__) || defined(__FreeBSD_kernel__)
4323 static gchar*
4324 get_fstypename (gchar *utfpath)
4326 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4327 struct statfs stat;
4328 #if __linux__
4329 _wapi_drive_type *current;
4330 #endif
4331 if (statfs (utfpath, &stat) == -1)
4332 return NULL;
4333 #if PLATFORM_MACOSX
4334 return g_strdup (stat.f_fstypename);
4335 #else
4336 current = &_wapi_drive_types[0];
4337 while (current->drive_type != DRIVE_UNKNOWN) {
4338 if (stat.f_type == current->fstypeid)
4339 return g_strdup (current->fstype);
4340 current++;
4342 return NULL;
4343 #endif
4344 #else
4345 return NULL;
4346 #endif
4349 /* Linux has struct statfs which has a different layout */
4350 gboolean
4351 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4353 gchar *utfpath;
4354 gchar *fstypename;
4355 gboolean status = FALSE;
4356 glong len;
4358 // We only support getting the file system type
4359 if (fsbuffer == NULL)
4360 return 0;
4362 utfpath = mono_unicode_to_external (path);
4363 if ((fstypename = get_fstypename (utfpath)) != NULL){
4364 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4365 if (ret != NULL && len < fsbuffersize){
4366 memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4367 fsbuffer [len] = 0;
4368 status = TRUE;
4370 if (ret != NULL)
4371 g_free (ret);
4372 g_free (fstypename);
4374 g_free (utfpath);
4375 return status;
4377 #endif
4380 void
4381 _wapi_io_init (void)
4383 mono_os_mutex_init (&stdhandle_mutex);
4386 void
4387 _wapi_io_cleanup (void)
4389 if (file_share_hash) {
4390 g_hash_table_destroy (file_share_hash);
4391 mono_os_mutex_destroy (&file_share_hash_mutex);