2 * handles.c: Generic and internal operations on handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2011 Novell, Inc.
8 * Copyright 2011 Xamarin Inc
18 #include <sys/types.h>
19 #ifdef HAVE_SYS_SOCKET_H
20 # include <sys/socket.h>
25 #ifdef HAVE_SYS_MMAN_H
26 # include <sys/mman.h>
32 #ifdef HAVE_SYS_RESOURCE_H
33 # include <sys/resource.h>
36 #include <mono/io-layer/wapi.h>
37 #include <mono/io-layer/wapi-private.h>
38 #include <mono/io-layer/handles-private.h>
39 #include <mono/io-layer/misc-private.h>
40 #include <mono/io-layer/shared.h>
41 #include <mono/io-layer/collection.h>
42 #include <mono/io-layer/process-private.h>
44 #include <mono/utils/mono-mutex.h>
45 #include <mono/utils/mono-proclib.h>
49 #define DEBUG(...) g_message(__VA_ARGS__)
54 static void (*_wapi_handle_ops_get_close_func (WapiHandleType type))(gpointer, gpointer);
56 static WapiHandleCapability handle_caps[WAPI_HANDLE_COUNT]={0};
57 static struct _WapiHandleOps *handle_ops[WAPI_HANDLE_COUNT]={
65 #ifndef DISABLE_SOCKETS
71 &_wapi_namedmutex_ops,
73 &_wapi_namedevent_ops,
76 static void _wapi_shared_details (gpointer handle_info);
78 static void (*handle_details[WAPI_HANDLE_COUNT])(gpointer) = {
81 _wapi_console_details,
82 _wapi_shared_details, /* thread */
86 NULL, /* Nothing useful to see in a socket handle */
87 NULL, /* Nothing useful to see in a find handle */
88 _wapi_shared_details, /* process */
90 _wapi_shared_details, /* namedmutex */
91 _wapi_shared_details, /* namedsem */
92 _wapi_shared_details, /* namedevent */
95 const char *_wapi_handle_typename[] = {
114 * We can hold _WAPI_PRIVATE_MAX_SLOTS * _WAPI_HANDLE_INITIAL_COUNT handles.
115 * If 4M handles are not enough... Oh, well... we will crash.
117 #define SLOT_INDEX(x) (x / _WAPI_HANDLE_INITIAL_COUNT)
118 #define SLOT_OFFSET(x) (x % _WAPI_HANDLE_INITIAL_COUNT)
120 struct _WapiHandleUnshared *_wapi_private_handles [_WAPI_PRIVATE_MAX_SLOTS];
121 static guint32 _wapi_private_handle_count = 0;
122 static guint32 _wapi_private_handle_slot_count = 0;
124 struct _WapiHandleSharedLayout *_wapi_shared_layout = NULL;
127 * If SHM is enabled, this will point to shared memory, otherwise it will be NULL.
129 struct _WapiFileShareLayout *_wapi_fileshare_layout = NULL;
132 * If SHM is disabled, this will point to a hash of _WapiFileShare structures, otherwise
133 * it will be NULL. We use this instead of _wapi_fileshare_layout to avoid allocating a
136 static GHashTable *file_share_hash;
137 static mono_mutex_t file_share_hash_mutex;
139 #define file_share_hash_lock() mono_mutex_lock (&file_share_hash_mutex)
140 #define file_share_hash_unlock() mono_mutex_unlock (&file_share_hash_mutex)
142 guint32 _wapi_fd_reserve;
145 * This is an internal handle which is used for handling waiting for multiple handles.
146 * Threads which wait for multiple handles wait on this one handle, and when a handle
147 * is signalled, this handle is signalled too.
149 static gpointer _wapi_global_signal_handle;
151 /* Point to the mutex/cond inside _wapi_global_signal_handle */
152 mono_mutex_t *_wapi_global_signal_mutex;
153 pthread_cond_t *_wapi_global_signal_cond;
156 gboolean _wapi_has_shut_down = FALSE;
158 /* Use this instead of getpid(), to cope with linuxthreads. It's a
159 * function rather than a variable lookup because we need to get at
160 * this before share_init() might have been called.
162 static pid_t _wapi_pid;
163 static mono_once_t pid_init_once = MONO_ONCE_INIT;
165 static void _wapi_handle_unref_full (gpointer handle, gboolean ignore_private_busy_handles);
167 static void pid_init (void)
169 _wapi_pid = getpid ();
172 pid_t _wapi_getpid (void)
174 mono_once (&pid_init_once, pid_init);
180 static mono_mutex_t scan_mutex;
182 static void handle_cleanup (void)
186 /* Every shared handle we were using ought really to be closed
187 * by now, but to make sure just blow them all away. The
188 * exiting finalizer thread in particular races us to the
189 * program exit and doesn't always win, so it can be left
190 * cluttering up the shared file. Anything else left over is
193 for(i = SLOT_INDEX (0); _wapi_private_handles[i] != NULL; i++) {
194 for(j = SLOT_OFFSET (0); j < _WAPI_HANDLE_INITIAL_COUNT; j++) {
195 struct _WapiHandleUnshared *handle_data = &_wapi_private_handles[i][j];
196 gpointer handle = GINT_TO_POINTER (i*_WAPI_HANDLE_INITIAL_COUNT+j);
198 for(k = handle_data->ref; k > 0; k--) {
199 DEBUG ("%s: unreffing %s handle %p", __func__, _wapi_handle_typename[type], handle);
201 _wapi_handle_unref_full (handle, TRUE);
206 _wapi_shm_semaphores_remove ();
208 _wapi_shm_detach (WAPI_SHM_DATA);
209 _wapi_shm_detach (WAPI_SHM_FILESHARE);
211 if (file_share_hash) {
212 g_hash_table_destroy (file_share_hash);
213 mono_mutex_destroy (&file_share_hash_mutex);
216 for (i = 0; i < _WAPI_PRIVATE_MAX_SLOTS; ++i)
217 g_free (_wapi_private_handles [i]);
221 wapi_getdtablesize (void)
223 #ifdef HAVE_GETRLIMIT
227 res = getrlimit (RLIMIT_NOFILE, &limit);
229 return limit.rlim_cur;
231 return getdtablesize ();
238 * Initialize the io-layer.
243 g_assert ((sizeof (handle_ops) / sizeof (handle_ops[0]))
244 == WAPI_HANDLE_COUNT);
246 _wapi_fd_reserve = wapi_getdtablesize ();
248 /* This is needed by the code in _wapi_handle_new_internal */
249 _wapi_fd_reserve = (_wapi_fd_reserve + (_WAPI_HANDLE_INITIAL_COUNT - 1)) & ~(_WAPI_HANDLE_INITIAL_COUNT - 1);
253 * The entries in _wapi_private_handles reserved for fds are allocated lazily to
257 _wapi_private_handles [idx++] = g_new0 (struct _WapiHandleUnshared,
258 _WAPI_HANDLE_INITIAL_COUNT);
261 _wapi_private_handle_count += _WAPI_HANDLE_INITIAL_COUNT;
262 _wapi_private_handle_slot_count ++;
263 } while(_wapi_fd_reserve > _wapi_private_handle_count);
265 _wapi_shm_semaphores_init ();
267 _wapi_shared_layout = _wapi_shm_attach (WAPI_SHM_DATA);
268 g_assert (_wapi_shared_layout != NULL);
270 if (_wapi_shm_enabled ()) {
271 /* This allocates a 4mb array, so do it only if SHM is enabled */
272 _wapi_fileshare_layout = _wapi_shm_attach (WAPI_SHM_FILESHARE);
273 g_assert (_wapi_fileshare_layout != NULL);
276 #if !defined (DISABLE_SHARED_HANDLES)
277 if (_wapi_shm_enabled ())
278 _wapi_collection_init ();
281 mono_mutex_init (&scan_mutex);
283 _wapi_global_signal_handle = _wapi_handle_new (WAPI_HANDLE_EVENT, NULL);
285 _wapi_global_signal_cond = &_WAPI_PRIVATE_HANDLES (GPOINTER_TO_UINT (_wapi_global_signal_handle)).signal_cond;
286 _wapi_global_signal_mutex = &_WAPI_PRIVATE_HANDLES (GPOINTER_TO_UINT (_wapi_global_signal_handle)).signal_mutex;
288 wapi_processes_init ();
290 /* Using atexit here instead of an explicit function call in
291 * a cleanup routine lets us cope when a third-party library
292 * calls exit (eg if an X client loses the connection to its
295 mono_atexit (handle_cleanup);
301 g_assert (_wapi_has_shut_down == FALSE);
303 _wapi_has_shut_down = TRUE;
305 _wapi_error_cleanup ();
306 _wapi_thread_cleanup ();
307 wapi_processes_cleanup ();
310 static void _wapi_handle_init_shared (struct _WapiHandleShared *handle,
312 gpointer handle_specific)
314 g_assert (_wapi_has_shut_down == FALSE);
317 handle->timestamp = (guint32)(time (NULL) & 0xFFFFFFFF);
318 handle->signalled = FALSE;
319 handle->handle_refs = 1;
321 if (handle_specific != NULL) {
322 memcpy (&handle->u, handle_specific, sizeof (handle->u));
326 static size_t _wapi_handle_struct_size (WapiHandleType type)
331 case WAPI_HANDLE_FILE: case WAPI_HANDLE_CONSOLE: case WAPI_HANDLE_PIPE:
332 type_size = sizeof (struct _WapiHandle_file);
334 case WAPI_HANDLE_THREAD:
335 type_size = sizeof (struct _WapiHandle_thread);
337 case WAPI_HANDLE_SEM:
338 type_size = sizeof (struct _WapiHandle_sem);
340 case WAPI_HANDLE_MUTEX:
341 type_size = sizeof (struct _WapiHandle_mutex);
343 case WAPI_HANDLE_EVENT:
344 type_size = sizeof (struct _WapiHandle_event);
346 case WAPI_HANDLE_SOCKET:
347 type_size = sizeof (struct _WapiHandle_socket);
349 case WAPI_HANDLE_FIND:
350 type_size = sizeof (struct _WapiHandle_find);
352 case WAPI_HANDLE_PROCESS:
353 type_size = sizeof (struct _WapiHandle_process);
355 case WAPI_HANDLE_NAMEDMUTEX:
356 type_size = sizeof (struct _WapiHandle_namedmutex);
358 case WAPI_HANDLE_NAMEDSEM:
359 type_size = sizeof (struct _WapiHandle_namedsem);
361 case WAPI_HANDLE_NAMEDEVENT:
362 type_size = sizeof (struct _WapiHandle_namedevent);
366 g_error ("Unknown WapiHandleType: %d\n", type);
372 static void _wapi_handle_init (struct _WapiHandleUnshared *handle,
373 WapiHandleType type, gpointer handle_specific)
378 g_assert (_wapi_has_shut_down == FALSE);
381 handle->signalled = FALSE;
384 if (!_WAPI_SHARED_HANDLE(type)) {
385 thr_ret = pthread_cond_init (&handle->signal_cond, NULL);
386 g_assert (thr_ret == 0);
388 thr_ret = mono_mutex_init (&handle->signal_mutex);
389 g_assert (thr_ret == 0);
391 if (handle_specific != NULL) {
392 type_size = _wapi_handle_struct_size (type);
393 memcpy (&handle->u, handle_specific,
399 static guint32 _wapi_handle_new_shared (WapiHandleType type,
400 gpointer handle_specific)
403 static guint32 last = 1;
406 g_assert (_wapi_has_shut_down == FALSE);
408 /* Leave the first slot empty as a guard */
410 /* FIXME: expandable array */
411 for(offset = last; offset <_WAPI_HANDLE_INITIAL_COUNT; offset++) {
412 struct _WapiHandleShared *handle = &_wapi_shared_layout->handles[offset];
414 if(handle->type == WAPI_HANDLE_UNUSED) {
415 thr_ret = _wapi_handle_lock_shared_handles ();
416 g_assert (thr_ret == 0);
418 if (InterlockedCompareExchange ((gint32 *)&handle->type, type, WAPI_HANDLE_UNUSED) == WAPI_HANDLE_UNUSED) {
421 _wapi_handle_init_shared (handle, type,
424 _wapi_handle_unlock_shared_handles ();
428 /* Someone else beat us to it, just
433 _wapi_handle_unlock_shared_handles ();
438 /* Try again from the beginning */
443 /* Will need to expand the array. The caller will sort it out */
449 * _wapi_handle_new_internal:
450 * @type: Init handle to this type
452 * Search for a free handle and initialize it. Return the handle on
453 * success and 0 on failure. This is only called from
454 * _wapi_handle_new, and scan_mutex must be held.
456 static guint32 _wapi_handle_new_internal (WapiHandleType type,
457 gpointer handle_specific)
460 static guint32 last = 0;
461 gboolean retry = FALSE;
463 g_assert (_wapi_has_shut_down == FALSE);
465 /* A linear scan should be fast enough. Start from the last
466 * allocation, assuming that handles are allocated more often
467 * than they're freed. Leave the space reserved for file
471 if (last < _wapi_fd_reserve) {
472 last = _wapi_fd_reserve;
479 for(i = SLOT_INDEX (count); i < _wapi_private_handle_slot_count; i++) {
480 if (_wapi_private_handles [i]) {
481 for (k = SLOT_OFFSET (count); k < _WAPI_HANDLE_INITIAL_COUNT; k++) {
482 struct _WapiHandleUnshared *handle = &_wapi_private_handles [i][k];
484 if(handle->type == WAPI_HANDLE_UNUSED) {
487 _wapi_handle_init (handle, type, handle_specific);
495 if(retry && last > _wapi_fd_reserve) {
496 /* Try again from the beginning */
497 last = _wapi_fd_reserve;
501 /* Will need to expand the array. The caller will sort it out */
507 _wapi_handle_new (WapiHandleType type, gpointer handle_specific)
509 guint32 handle_idx = 0;
513 g_assert (_wapi_has_shut_down == FALSE);
515 DEBUG ("%s: Creating new handle of type %s", __func__,
516 _wapi_handle_typename[type]);
518 g_assert(!_WAPI_FD_HANDLE(type));
520 thr_ret = mono_mutex_lock (&scan_mutex);
521 g_assert (thr_ret == 0);
523 while ((handle_idx = _wapi_handle_new_internal (type, handle_specific)) == 0) {
524 /* Try and expand the array, and have another go */
525 int idx = SLOT_INDEX (_wapi_private_handle_count);
526 if (idx >= _WAPI_PRIVATE_MAX_SLOTS) {
530 _wapi_private_handles [idx] = g_new0 (struct _WapiHandleUnshared,
531 _WAPI_HANDLE_INITIAL_COUNT);
533 _wapi_private_handle_count += _WAPI_HANDLE_INITIAL_COUNT;
534 _wapi_private_handle_slot_count ++;
537 thr_ret = mono_mutex_unlock (&scan_mutex);
538 g_assert (thr_ret == 0);
540 if (handle_idx == 0) {
541 /* We ran out of slots */
542 handle = _WAPI_HANDLE_INVALID;
546 /* Make sure we left the space for fd mappings */
547 g_assert (handle_idx >= _wapi_fd_reserve);
549 handle = GUINT_TO_POINTER (handle_idx);
551 DEBUG ("%s: Allocated new handle %p", __func__, handle);
553 if (_WAPI_SHARED_HANDLE(type)) {
554 /* Add the shared section too */
557 ref = _wapi_handle_new_shared (type, handle_specific);
559 _wapi_handle_collect ();
560 ref = _wapi_handle_new_shared (type, handle_specific);
562 /* FIXME: grow the arrays */
563 handle = _WAPI_HANDLE_INVALID;
568 _WAPI_PRIVATE_HANDLES(handle_idx).u.shared.offset = ref;
569 DEBUG ("%s: New shared handle at offset 0x%x", __func__,
577 gpointer _wapi_handle_new_from_offset (WapiHandleType type, guint32 offset,
580 guint32 handle_idx = 0;
581 gpointer handle = INVALID_HANDLE_VALUE;
583 struct _WapiHandleShared *shared;
585 g_assert (_wapi_has_shut_down == FALSE);
587 DEBUG ("%s: Creating new handle of type %s to offset %d", __func__,
588 _wapi_handle_typename[type], offset);
590 g_assert(!_WAPI_FD_HANDLE(type));
591 g_assert(_WAPI_SHARED_HANDLE(type));
592 g_assert(offset != 0);
594 shared = &_wapi_shared_layout->handles[offset];
596 guint32 now = (guint32)(time (NULL) & 0xFFFFFFFF);
597 /* Bump up the timestamp for this offset */
598 InterlockedExchange ((gint32 *)&shared->timestamp, now);
601 thr_ret = mono_mutex_lock (&scan_mutex);
602 g_assert (thr_ret == 0);
604 for (i = SLOT_INDEX (0); i < _wapi_private_handle_slot_count; i++) {
605 if (_wapi_private_handles [i]) {
606 for (k = SLOT_OFFSET (0); k < _WAPI_HANDLE_INITIAL_COUNT; k++) {
607 struct _WapiHandleUnshared *handle_data = &_wapi_private_handles [i][k];
609 if (handle_data->type == type &&
610 handle_data->u.shared.offset == offset) {
611 handle = GUINT_TO_POINTER (i * _WAPI_HANDLE_INITIAL_COUNT + k);
612 goto first_pass_done;
619 thr_ret = mono_mutex_unlock (&scan_mutex);
620 g_assert (thr_ret == 0);
622 if (handle != INVALID_HANDLE_VALUE) {
623 _wapi_handle_ref (handle);
625 DEBUG ("%s: Returning old handle %p referencing 0x%x",
626 __func__, handle, offset);
630 /* Prevent entries expiring under us as we search */
631 thr_ret = _wapi_handle_lock_shared_handles ();
632 g_assert (thr_ret == 0);
634 if (shared->type == WAPI_HANDLE_UNUSED) {
635 /* Someone deleted this handle while we were working */
636 DEBUG ("%s: Handle at 0x%x unused", __func__, offset);
640 if (shared->type != type) {
641 DEBUG ("%s: Wrong type at %d 0x%x! Found %s wanted %s",
642 __func__, offset, offset,
643 _wapi_handle_typename[shared->type],
644 _wapi_handle_typename[type]);
648 thr_ret = mono_mutex_lock (&scan_mutex);
649 g_assert (thr_ret == 0);
651 while ((handle_idx = _wapi_handle_new_internal (type, NULL)) == 0) {
652 /* Try and expand the array, and have another go */
653 int idx = SLOT_INDEX (_wapi_private_handle_count);
654 _wapi_private_handles [idx] = g_new0 (struct _WapiHandleUnshared,
655 _WAPI_HANDLE_INITIAL_COUNT);
657 _wapi_private_handle_count += _WAPI_HANDLE_INITIAL_COUNT;
658 _wapi_private_handle_slot_count ++;
661 thr_ret = mono_mutex_unlock (&scan_mutex);
662 g_assert (thr_ret == 0);
664 /* Make sure we left the space for fd mappings */
665 g_assert (handle_idx >= _wapi_fd_reserve);
667 handle = GUINT_TO_POINTER (handle_idx);
669 _WAPI_PRIVATE_HANDLES(handle_idx).u.shared.offset = offset;
670 InterlockedIncrement ((gint32 *)&shared->handle_refs);
672 DEBUG ("%s: Allocated new handle %p referencing 0x%x (shared refs %d)", __func__, handle, offset, shared->handle_refs);
675 _wapi_handle_unlock_shared_handles ();
681 init_handles_slot (int idx)
685 thr_ret = mono_mutex_lock (&scan_mutex);
686 g_assert (thr_ret == 0);
688 if (_wapi_private_handles [idx] == NULL) {
689 _wapi_private_handles [idx] = g_new0 (struct _WapiHandleUnshared,
690 _WAPI_HANDLE_INITIAL_COUNT);
691 g_assert (_wapi_private_handles [idx]);
694 thr_ret = mono_mutex_unlock (&scan_mutex);
695 g_assert (thr_ret == 0);
698 gpointer _wapi_handle_new_fd (WapiHandleType type, int fd,
699 gpointer handle_specific)
701 struct _WapiHandleUnshared *handle;
704 g_assert (_wapi_has_shut_down == FALSE);
706 DEBUG ("%s: Creating new handle of type %s", __func__,
707 _wapi_handle_typename[type]);
709 g_assert(_WAPI_FD_HANDLE(type));
710 g_assert(!_WAPI_SHARED_HANDLE(type));
712 if (fd >= _wapi_fd_reserve) {
713 DEBUG ("%s: fd %d is too big", __func__, fd);
715 return(GUINT_TO_POINTER (_WAPI_HANDLE_INVALID));
718 /* Initialize the array entries on demand */
719 if (_wapi_private_handles [SLOT_INDEX (fd)] == NULL)
720 init_handles_slot (SLOT_INDEX (fd));
722 handle = &_WAPI_PRIVATE_HANDLES(fd);
724 if (handle->type != WAPI_HANDLE_UNUSED) {
725 DEBUG ("%s: fd %d is already in use!", __func__, fd);
726 /* FIXME: clean up this handle? We can't do anything
727 * with the fd, cos thats the new one
731 DEBUG ("%s: Assigning new fd handle %d", __func__, fd);
733 /* Prevent file share entries racing with us, when the file
734 * handle is only half initialised
736 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_FILESHARE);
737 g_assert(thr_ret == 0);
739 _wapi_handle_init (handle, type, handle_specific);
741 thr_ret = _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_FILESHARE);
743 return(GUINT_TO_POINTER(fd));
746 gboolean _wapi_lookup_handle (gpointer handle, WapiHandleType type,
747 gpointer *handle_specific)
749 struct _WapiHandleUnshared *handle_data;
750 guint32 handle_idx = GPOINTER_TO_UINT(handle);
752 if (!_WAPI_PRIVATE_VALID_SLOT (handle_idx)) {
756 /* Initialize the array entries on demand */
757 if (_wapi_private_handles [SLOT_INDEX (handle_idx)] == NULL)
758 init_handles_slot (SLOT_INDEX (handle_idx));
760 handle_data = &_WAPI_PRIVATE_HANDLES(handle_idx);
762 if (handle_data->type != type) {
766 if (handle_specific == NULL) {
770 if (_WAPI_SHARED_HANDLE(type)) {
771 struct _WapiHandle_shared_ref *ref;
772 struct _WapiHandleShared *shared_handle_data;
774 ref = &handle_data->u.shared;
775 shared_handle_data = &_wapi_shared_layout->handles[ref->offset];
777 if (shared_handle_data->type != type) {
778 /* The handle must have been deleted on us
783 *handle_specific = &shared_handle_data->u;
785 *handle_specific = &handle_data->u;
792 _wapi_handle_foreach (WapiHandleType type,
793 gboolean (*on_each)(gpointer test, gpointer user),
796 struct _WapiHandleUnshared *handle_data = NULL;
801 thr_ret = mono_mutex_lock (&scan_mutex);
802 g_assert (thr_ret == 0);
804 for (i = SLOT_INDEX (0); i < _wapi_private_handle_slot_count; i++) {
805 if (_wapi_private_handles [i]) {
806 for (k = SLOT_OFFSET (0); k < _WAPI_HANDLE_INITIAL_COUNT; k++) {
807 handle_data = &_wapi_private_handles [i][k];
809 if (handle_data->type == type) {
810 ret = GUINT_TO_POINTER (i * _WAPI_HANDLE_INITIAL_COUNT + k);
811 if (on_each (ret, user_data) == TRUE)
818 thr_ret = mono_mutex_unlock (&scan_mutex);
819 g_assert (thr_ret == 0);
822 /* This might list some shared handles twice if they are already
823 * opened by this process, and the check function returns FALSE the
824 * first time. Shared handles that are created during the search are
825 * unreffed if the check function returns FALSE, so callers must not
826 * rely on the handle persisting (unless the check function returns
828 * The caller owns the returned handle.
830 gpointer _wapi_search_handle (WapiHandleType type,
831 gboolean (*check)(gpointer test, gpointer user),
833 gpointer *handle_specific,
834 gboolean search_shared)
836 struct _WapiHandleUnshared *handle_data = NULL;
837 struct _WapiHandleShared *shared = NULL;
840 gboolean found = FALSE;
843 thr_ret = mono_mutex_lock (&scan_mutex);
844 g_assert (thr_ret == 0);
846 for (i = SLOT_INDEX (0); !found && i < _wapi_private_handle_slot_count; i++) {
847 if (_wapi_private_handles [i]) {
848 for (k = SLOT_OFFSET (0); k < _WAPI_HANDLE_INITIAL_COUNT; k++) {
849 handle_data = &_wapi_private_handles [i][k];
851 if (handle_data->type == type) {
852 ret = GUINT_TO_POINTER (i * _WAPI_HANDLE_INITIAL_COUNT + k);
853 if (check (ret, user_data) == TRUE) {
854 _wapi_handle_ref (ret);
857 if (_WAPI_SHARED_HANDLE (type)) {
858 shared = &_wapi_shared_layout->handles[i];
868 thr_ret = mono_mutex_unlock (&scan_mutex);
869 g_assert (thr_ret == 0);
871 if (!found && search_shared && _WAPI_SHARED_HANDLE (type)) {
872 /* Not found yet, so search the shared memory too */
873 DEBUG ("%s: Looking at other shared handles...", __func__);
875 for (i = 0; i < _WAPI_HANDLE_INITIAL_COUNT; i++) {
876 shared = &_wapi_shared_layout->handles[i];
878 if (shared->type == type) {
879 /* Tell new_from_offset to not
880 * timestamp this handle, because
881 * otherwise it will ping every handle
882 * in the list and they will never
885 ret = _wapi_handle_new_from_offset (type, i,
887 if (ret == INVALID_HANDLE_VALUE) {
888 /* This handle was deleted
889 * while we were looking at it
894 DEBUG ("%s: Opened tmp handle %p (type %s) from offset %d", __func__, ret, _wapi_handle_typename[type], i);
896 /* It's possible that the shared part
897 * of this handle has now been blown
898 * away (after new_from_offset
899 * successfully opened it,) if its
900 * timestamp is too old. The check
901 * function needs to be aware of this,
902 * and cope if the handle has
905 if (check (ret, user_data) == TRUE) {
906 /* Timestamp this handle, but make
907 * sure it still exists first
909 thr_ret = _wapi_handle_lock_shared_handles ();
910 g_assert (thr_ret == 0);
912 if (shared->type == type) {
913 guint32 now = (guint32)(time (NULL) & 0xFFFFFFFF);
914 InterlockedExchange ((gint32 *)&shared->timestamp, now);
917 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(ret));
919 _wapi_handle_unlock_shared_handles ();
922 /* It's been deleted,
926 _wapi_handle_unlock_shared_handles ();
930 /* This isn't the handle we're looking
931 * for, so drop the reference we took
932 * in _wapi_handle_new_from_offset ()
934 _wapi_handle_unref (ret);
944 if(handle_specific != NULL) {
945 if (_WAPI_SHARED_HANDLE(type)) {
946 g_assert(shared->type == type);
948 *handle_specific = &shared->u;
950 *handle_specific = &handle_data->u;
958 /* Returns the offset of the metadata array, or -1 on error, or 0 for
959 * not found (0 is not a valid offset)
961 gint32 _wapi_search_handle_namespace (WapiHandleType type,
964 struct _WapiHandleShared *shared_handle_data;
969 g_assert(_WAPI_SHARED_HANDLE(type));
971 DEBUG ("%s: Lookup for handle named [%s] type %s", __func__,
972 utf8_name, _wapi_handle_typename[type]);
974 /* Do a handle collection before starting to look, so that any
975 * stale cruft gets removed
977 _wapi_handle_collect ();
979 thr_ret = _wapi_handle_lock_shared_handles ();
980 g_assert (thr_ret == 0);
982 for(i = 1; i < _WAPI_HANDLE_INITIAL_COUNT; i++) {
983 WapiSharedNamespace *sharedns;
985 shared_handle_data = &_wapi_shared_layout->handles[i];
987 /* Check mutex, event, semaphore, timer, job and
988 * file-mapping object names. So far only mutex,
989 * semaphore and event are implemented.
991 if (!_WAPI_SHARED_NAMESPACE (shared_handle_data->type)) {
995 DEBUG ("%s: found a shared namespace handle at 0x%x (type %s)", __func__, i, _wapi_handle_typename[shared_handle_data->type]);
997 sharedns=(WapiSharedNamespace *)&shared_handle_data->u;
999 DEBUG ("%s: name is [%s]", __func__, sharedns->name);
1001 if (strcmp (sharedns->name, utf8_name) == 0) {
1002 if (shared_handle_data->type != type) {
1003 /* Its the wrong type, so fail now */
1004 DEBUG ("%s: handle 0x%x matches name but is wrong type: %s", __func__, i, _wapi_handle_typename[shared_handle_data->type]);
1008 DEBUG ("%s: handle 0x%x matches name and type", __func__, i);
1016 _wapi_handle_unlock_shared_handles ();
1021 void _wapi_handle_ref (gpointer handle)
1023 guint32 idx = GPOINTER_TO_UINT(handle);
1024 struct _WapiHandleUnshared *handle_data;
1026 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1030 if (_wapi_handle_type (handle) == WAPI_HANDLE_UNUSED) {
1031 g_warning ("%s: Attempting to ref unused handle %p", __func__,
1036 handle_data = &_WAPI_PRIVATE_HANDLES(idx);
1038 InterlockedIncrement ((gint32 *)&handle_data->ref);
1040 /* It's possible for processes to exit before getting around
1041 * to updating timestamps in the collection thread, so if a
1042 * shared handle is reffed do the timestamp here as well just
1045 if (_WAPI_SHARED_HANDLE(handle_data->type)) {
1046 struct _WapiHandleShared *shared_data = &_wapi_shared_layout->handles[handle_data->u.shared.offset];
1047 guint32 now = (guint32)(time (NULL) & 0xFFFFFFFF);
1048 InterlockedExchange ((gint32 *)&shared_data->timestamp, now);
1052 g_message ("%s: %s handle %p ref now %d", __func__,
1053 _wapi_handle_typename[_WAPI_PRIVATE_HANDLES (idx).type],
1055 _WAPI_PRIVATE_HANDLES(idx).ref);
1059 /* The handle must not be locked on entry to this function */
1060 static void _wapi_handle_unref_full (gpointer handle, gboolean ignore_private_busy_handles)
1062 guint32 idx = GPOINTER_TO_UINT(handle);
1063 gboolean destroy = FALSE, early_exit = FALSE;
1066 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1070 if (_wapi_handle_type (handle) == WAPI_HANDLE_UNUSED) {
1071 g_warning ("%s: Attempting to unref unused handle %p",
1076 /* Possible race condition here if another thread refs the
1077 * handle between here and setting the type to UNUSED. I
1078 * could lock a mutex, but I'm not sure that allowing a handle
1079 * reference to reach 0 isn't an application bug anyway.
1081 destroy = (InterlockedDecrement ((gint32 *)&_WAPI_PRIVATE_HANDLES(idx).ref) ==0);
1084 g_message ("%s: %s handle %p ref now %d (destroy %s)", __func__,
1085 _wapi_handle_typename[_WAPI_PRIVATE_HANDLES (idx).type],
1087 _WAPI_PRIVATE_HANDLES(idx).ref, destroy?"TRUE":"FALSE");
1091 /* Need to copy the handle info, reset the slot in the
1092 * array, and _only then_ call the close function to
1093 * avoid race conditions (eg file descriptors being
1094 * closed, and another file being opened getting the
1095 * same fd racing the memset())
1097 struct _WapiHandleUnshared handle_data;
1098 struct _WapiHandleShared shared_handle_data;
1099 WapiHandleType type = _WAPI_PRIVATE_HANDLES(idx).type;
1100 void (*close_func)(gpointer, gpointer) = _wapi_handle_ops_get_close_func (type);
1101 gboolean is_shared = _WAPI_SHARED_HANDLE(type);
1104 /* If this is a shared handle we need to take
1105 * the shared lock outside of the scan_mutex
1106 * lock to avoid deadlocks
1108 thr_ret = _wapi_handle_lock_shared_handles ();
1109 g_assert (thr_ret == 0);
1112 thr_ret = mono_mutex_lock (&scan_mutex);
1114 DEBUG ("%s: Destroying handle %p", __func__, handle);
1116 memcpy (&handle_data, &_WAPI_PRIVATE_HANDLES(idx),
1117 sizeof (struct _WapiHandleUnshared));
1119 memset (&_WAPI_PRIVATE_HANDLES(idx).u, '\0',
1120 sizeof(_WAPI_PRIVATE_HANDLES(idx).u));
1122 _WAPI_PRIVATE_HANDLES(idx).type = WAPI_HANDLE_UNUSED;
1125 /* Destroy the mutex and cond var. We hope nobody
1126 * tried to grab them between the handle unlock and
1127 * now, but pthreads doesn't have a
1128 * "unlock_and_destroy" atomic function.
1130 thr_ret = mono_mutex_destroy (&_WAPI_PRIVATE_HANDLES(idx).signal_mutex);
1131 /*WARNING gross hack to make cleanup not crash when exiting without the whole runtime teardown.*/
1132 if (thr_ret == EBUSY && ignore_private_busy_handles) {
1136 g_error ("Error destroying handle %p mutex due to %d\n", handle, thr_ret);
1138 thr_ret = pthread_cond_destroy (&_WAPI_PRIVATE_HANDLES(idx).signal_cond);
1139 if (thr_ret == EBUSY && ignore_private_busy_handles)
1141 else if (thr_ret != 0)
1142 g_error ("Error destroying handle %p cond var due to %d\n", handle, thr_ret);
1145 struct _WapiHandleShared *shared = &_wapi_shared_layout->handles[handle_data.u.shared.offset];
1147 memcpy (&shared_handle_data, shared,
1148 sizeof (struct _WapiHandleShared));
1150 /* It's possible that this handle is already
1151 * pointing at a deleted shared section
1154 g_message ("%s: %s handle %p shared refs before dec %d", __func__, _wapi_handle_typename[type], handle, shared->handle_refs);
1157 if (shared->handle_refs > 0) {
1158 shared->handle_refs--;
1159 if (shared->handle_refs == 0) {
1160 memset (shared, '\0', sizeof (struct _WapiHandleShared));
1165 thr_ret = mono_mutex_unlock (&scan_mutex);
1166 g_assert (thr_ret == 0);
1171 _wapi_handle_unlock_shared_handles ();
1174 if (close_func != NULL) {
1176 close_func (handle, &shared_handle_data.u);
1178 close_func (handle, &handle_data.u);
1184 void _wapi_handle_unref (gpointer handle)
1186 _wapi_handle_unref_full (handle, FALSE);
1189 void _wapi_handle_register_capabilities (WapiHandleType type,
1190 WapiHandleCapability caps)
1192 handle_caps[type] = caps;
1195 gboolean _wapi_handle_test_capabilities (gpointer handle,
1196 WapiHandleCapability caps)
1198 guint32 idx = GPOINTER_TO_UINT(handle);
1199 WapiHandleType type;
1201 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1205 type = _WAPI_PRIVATE_HANDLES(idx).type;
1207 DEBUG ("%s: testing 0x%x against 0x%x (%d)", __func__,
1208 handle_caps[type], caps, handle_caps[type] & caps);
1210 return((handle_caps[type] & caps) != 0);
1213 static void (*_wapi_handle_ops_get_close_func (WapiHandleType type))(gpointer, gpointer)
1215 if (handle_ops[type] != NULL &&
1216 handle_ops[type]->close != NULL) {
1217 return (handle_ops[type]->close);
1223 void _wapi_handle_ops_close (gpointer handle, gpointer data)
1225 guint32 idx = GPOINTER_TO_UINT(handle);
1226 WapiHandleType type;
1228 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1232 type = _WAPI_PRIVATE_HANDLES(idx).type;
1234 if (handle_ops[type] != NULL &&
1235 handle_ops[type]->close != NULL) {
1236 handle_ops[type]->close (handle, data);
1240 void _wapi_handle_ops_signal (gpointer handle)
1242 guint32 idx = GPOINTER_TO_UINT(handle);
1243 WapiHandleType type;
1245 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1249 type = _WAPI_PRIVATE_HANDLES(idx).type;
1251 if (handle_ops[type] != NULL && handle_ops[type]->signal != NULL) {
1252 handle_ops[type]->signal (handle);
1256 gboolean _wapi_handle_ops_own (gpointer handle)
1258 guint32 idx = GPOINTER_TO_UINT(handle);
1259 WapiHandleType type;
1261 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1265 type = _WAPI_PRIVATE_HANDLES(idx).type;
1267 if (handle_ops[type] != NULL && handle_ops[type]->own_handle != NULL) {
1268 return(handle_ops[type]->own_handle (handle));
1274 gboolean _wapi_handle_ops_isowned (gpointer handle)
1276 guint32 idx = GPOINTER_TO_UINT(handle);
1277 WapiHandleType type;
1279 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1283 type = _WAPI_PRIVATE_HANDLES(idx).type;
1285 if (handle_ops[type] != NULL && handle_ops[type]->is_owned != NULL) {
1286 return(handle_ops[type]->is_owned (handle));
1292 guint32 _wapi_handle_ops_special_wait (gpointer handle, guint32 timeout, gboolean alertable)
1294 guint32 idx = GPOINTER_TO_UINT(handle);
1295 WapiHandleType type;
1297 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1298 return(WAIT_FAILED);
1301 type = _WAPI_PRIVATE_HANDLES(idx).type;
1303 if (handle_ops[type] != NULL &&
1304 handle_ops[type]->special_wait != NULL) {
1305 return(handle_ops[type]->special_wait (handle, timeout, alertable));
1307 return(WAIT_FAILED);
1311 void _wapi_handle_ops_prewait (gpointer handle)
1313 guint32 idx = GPOINTER_TO_UINT (handle);
1314 WapiHandleType type;
1316 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1320 type = _WAPI_PRIVATE_HANDLES (idx).type;
1322 if (handle_ops[type] != NULL &&
1323 handle_ops[type]->prewait != NULL) {
1324 handle_ops[type]->prewait (handle);
1331 * @handle: The handle to release
1333 * Closes and invalidates @handle, releasing any resources it
1334 * consumes. When the last handle to a temporary or non-persistent
1335 * object is closed, that object can be deleted. Closing the same
1336 * handle twice is an error.
1338 * Return value: %TRUE on success, %FALSE otherwise.
1340 gboolean CloseHandle(gpointer handle)
1342 if (handle == NULL) {
1343 /* Problem: because we map file descriptors to the
1344 * same-numbered handle we can't tell the difference
1345 * between a bogus handle and the handle to stdin.
1346 * Assume that it's the console handle if that handle
1349 if (_WAPI_PRIVATE_HANDLES (0).type != WAPI_HANDLE_CONSOLE) {
1350 SetLastError (ERROR_INVALID_PARAMETER);
1354 if (handle == _WAPI_HANDLE_INVALID){
1355 SetLastError (ERROR_INVALID_PARAMETER);
1359 _wapi_handle_unref (handle);
1364 /* Lots more to implement here, but this is all we need at the moment */
1365 gboolean DuplicateHandle (gpointer srcprocess, gpointer src,
1366 gpointer targetprocess, gpointer *target,
1367 guint32 access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 options G_GNUC_UNUSED)
1369 if (srcprocess != _WAPI_PROCESS_CURRENT ||
1370 targetprocess != _WAPI_PROCESS_CURRENT) {
1371 /* Duplicating other process's handles is not supported */
1372 SetLastError (ERROR_INVALID_HANDLE);
1376 if (src == _WAPI_PROCESS_CURRENT) {
1377 *target = _wapi_process_duplicate ();
1378 } else if (src == _WAPI_THREAD_CURRENT) {
1379 g_assert_not_reached ();
1381 _wapi_handle_ref (src);
1388 gboolean _wapi_handle_count_signalled_handles (guint32 numhandles,
1394 guint32 count, i, iter=0;
1397 WapiHandleType type;
1399 /* Lock all the handles, with backoff */
1401 thr_ret = _wapi_handle_lock_shared_handles ();
1402 g_assert (thr_ret == 0);
1404 for(i=0; i<numhandles; i++) {
1405 gpointer handle = handles[i];
1406 guint32 idx = GPOINTER_TO_UINT(handle);
1408 DEBUG ("%s: attempting to lock %p", __func__, handle);
1410 type = _WAPI_PRIVATE_HANDLES(idx).type;
1412 thr_ret = _wapi_handle_trylock_handle (handle);
1417 DEBUG ("%s: attempt failed for %p: %s", __func__,
1418 handle, strerror (thr_ret));
1420 thr_ret = _wapi_handle_unlock_shared_handles ();
1421 g_assert (thr_ret == 0);
1424 handle = handles[i];
1425 idx = GPOINTER_TO_UINT(handle);
1427 thr_ret = _wapi_handle_unlock_handle (handle);
1428 g_assert (thr_ret == 0);
1431 /* If iter ever reaches 100 the nanosleep will
1432 * return EINVAL immediately, but we have a
1433 * design flaw if that happens.
1437 g_warning ("%s: iteration overflow!",
1442 DEBUG ("%s: Backing off for %d ms", __func__,
1444 _wapi_handle_spin (10 * iter);
1450 DEBUG ("%s: Locked all handles", __func__);
1455 for(i=0; i<numhandles; i++) {
1456 gpointer handle = handles[i];
1457 guint32 idx = GPOINTER_TO_UINT(handle);
1459 type = _WAPI_PRIVATE_HANDLES(idx).type;
1461 DEBUG ("%s: Checking handle %p", __func__, handle);
1463 if(((_wapi_handle_test_capabilities (handle, WAPI_HANDLE_CAP_OWN)==TRUE) &&
1464 (_wapi_handle_ops_isowned (handle) == TRUE)) ||
1465 (_WAPI_SHARED_HANDLE(type) &&
1466 WAPI_SHARED_HANDLE_DATA(handle).signalled == TRUE) ||
1467 (!_WAPI_SHARED_HANDLE(type) &&
1468 _WAPI_PRIVATE_HANDLES(idx).signalled == TRUE)) {
1471 DEBUG ("%s: Handle %p signalled", __func__,
1479 DEBUG ("%s: %d event handles signalled", __func__, count);
1481 if ((waitall == TRUE && count == numhandles) ||
1482 (waitall == FALSE && count > 0)) {
1488 DEBUG ("%s: Returning %d", __func__, ret);
1495 void _wapi_handle_unlock_handles (guint32 numhandles, gpointer *handles)
1500 thr_ret = _wapi_handle_unlock_shared_handles ();
1501 g_assert (thr_ret == 0);
1503 for(i=0; i<numhandles; i++) {
1504 gpointer handle = handles[i];
1506 DEBUG ("%s: unlocking handle %p", __func__, handle);
1508 thr_ret = _wapi_handle_unlock_handle (handle);
1509 g_assert (thr_ret == 0);
1513 static int timedwait_signal_poll_cond (pthread_cond_t *cond, mono_mutex_t *mutex, struct timespec *timeout, gboolean alertable)
1515 struct timespec fake_timeout;
1520 ret=mono_cond_timedwait (cond, mutex, timeout);
1522 ret=mono_cond_wait (cond, mutex);
1524 _wapi_calc_timeout (&fake_timeout, 100);
1526 if (timeout != NULL && ((fake_timeout.tv_sec > timeout->tv_sec) ||
1527 (fake_timeout.tv_sec == timeout->tv_sec &&
1528 fake_timeout.tv_nsec > timeout->tv_nsec))) {
1529 /* Real timeout is less than 100ms time */
1530 ret=mono_cond_timedwait (cond, mutex, timeout);
1532 ret=mono_cond_timedwait (cond, mutex, &fake_timeout);
1534 /* Mask the fake timeout, this will cause
1535 * another poll if the cond was not really signaled
1537 if (ret==ETIMEDOUT) {
1546 int _wapi_handle_wait_signal (gboolean poll)
1548 return _wapi_handle_timedwait_signal_handle (_wapi_global_signal_handle, NULL, TRUE, poll);
1551 int _wapi_handle_timedwait_signal (struct timespec *timeout, gboolean poll)
1553 return _wapi_handle_timedwait_signal_handle (_wapi_global_signal_handle, timeout, TRUE, poll);
1556 int _wapi_handle_wait_signal_handle (gpointer handle, gboolean alertable)
1558 DEBUG ("%s: waiting for %p", __func__, handle);
1560 return _wapi_handle_timedwait_signal_handle (handle, NULL, alertable, FALSE);
1563 int _wapi_handle_timedwait_signal_handle (gpointer handle,
1564 struct timespec *timeout, gboolean alertable, gboolean poll)
1566 DEBUG ("%s: waiting for %p (type %s)", __func__, handle,
1567 _wapi_handle_typename[_wapi_handle_type (handle)]);
1569 if (_WAPI_SHARED_HANDLE (_wapi_handle_type (handle))) {
1570 if (WAPI_SHARED_HANDLE_DATA(handle).signalled == TRUE) {
1573 if (timeout != NULL) {
1574 struct timespec fake_timeout;
1575 _wapi_calc_timeout (&fake_timeout, 100);
1577 if ((fake_timeout.tv_sec > timeout->tv_sec) ||
1578 (fake_timeout.tv_sec == timeout->tv_sec &&
1579 fake_timeout.tv_nsec > timeout->tv_nsec)) {
1580 /* FIXME: Real timeout is less than
1581 * 100ms time, but is it really worth
1582 * calculating to the exact ms?
1584 _wapi_handle_spin (100);
1586 if (WAPI_SHARED_HANDLE_DATA(handle).signalled == TRUE) {
1593 _wapi_handle_spin (100);
1597 guint32 idx = GPOINTER_TO_UINT(handle);
1599 pthread_cond_t *cond;
1600 mono_mutex_t *mutex;
1602 if (alertable && !wapi_thread_set_wait_handle (handle))
1605 cond = &_WAPI_PRIVATE_HANDLES (idx).signal_cond;
1606 mutex = &_WAPI_PRIVATE_HANDLES (idx).signal_mutex;
1609 /* This is needed when waiting for process handles */
1610 res = timedwait_signal_poll_cond (cond, mutex, timeout, alertable);
1613 res = mono_cond_timedwait (cond, mutex, timeout);
1615 res = mono_cond_wait (cond, mutex);
1619 wapi_thread_clear_wait_handle (handle);
1626 _wapi_free_share_info (_WapiFileShare *share_info)
1628 if (!_wapi_shm_enabled ()) {
1629 file_share_hash_lock ();
1630 g_hash_table_remove (file_share_hash, share_info);
1631 file_share_hash_unlock ();
1632 /* The hashtable dtor frees share_info */
1634 memset (share_info, '\0', sizeof(struct _WapiFileShare));
1639 wapi_share_info_equal (gconstpointer ka, gconstpointer kb)
1641 const _WapiFileShare *s1 = ka;
1642 const _WapiFileShare *s2 = kb;
1644 return (s1->device == s2->device && s1->inode == s2->inode) ? 1 : 0;
1648 wapi_share_info_hash (gconstpointer data)
1650 const _WapiFileShare *s = data;
1655 gboolean _wapi_handle_get_or_set_share (dev_t device, ino_t inode,
1656 guint32 new_sharemode,
1658 guint32 *old_sharemode,
1659 guint32 *old_access,
1660 struct _WapiFileShare **share_info)
1662 struct _WapiFileShare *file_share;
1663 guint32 now = (guint32)(time(NULL) & 0xFFFFFFFF);
1664 int thr_ret, i, first_unused = -1;
1665 gboolean exists = FALSE;
1667 /* Prevents entries from expiring under us as we search
1669 thr_ret = _wapi_handle_lock_shared_handles ();
1670 g_assert (thr_ret == 0);
1672 /* Prevent new entries racing with us */
1673 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_FILESHARE);
1674 g_assert (thr_ret == 0);
1676 if (!_wapi_shm_enabled ()) {
1680 * Instead of allocating a 4MB array, we use a hash table to keep track of this
1681 * info. This is needed even if SHM is disabled, to track sharing inside
1682 * the current process.
1684 if (!file_share_hash) {
1685 file_share_hash = g_hash_table_new_full (wapi_share_info_hash, wapi_share_info_equal, NULL, g_free);
1686 mono_mutex_init_recursive (&file_share_hash_mutex);
1689 tmp.device = device;
1692 file_share_hash_lock ();
1694 file_share = g_hash_table_lookup (file_share_hash, &tmp);
1696 *old_sharemode = file_share->sharemode;
1697 *old_access = file_share->access;
1698 *share_info = file_share;
1700 InterlockedIncrement ((gint32 *)&file_share->handle_refs);
1703 file_share = g_new0 (_WapiFileShare, 1);
1705 file_share->device = device;
1706 file_share->inode = inode;
1707 file_share->opened_by_pid = _wapi_getpid ();
1708 file_share->sharemode = new_sharemode;
1709 file_share->access = new_access;
1710 file_share->handle_refs = 1;
1711 *share_info = file_share;
1713 g_hash_table_insert (file_share_hash, file_share, file_share);
1716 file_share_hash_unlock ();
1718 /* If a linear scan gets too slow we'll have to fit a hash
1719 * table onto the shared mem backing store
1722 for (i = 0; i <= _wapi_fileshare_layout->hwm; i++) {
1723 file_share = &_wapi_fileshare_layout->share_info[i];
1725 /* Make a note of an unused slot, in case we need to
1728 if (first_unused == -1 && file_share->handle_refs == 0) {
1733 if (file_share->handle_refs == 0) {
1737 if (file_share->device == device &&
1738 file_share->inode == inode) {
1739 *old_sharemode = file_share->sharemode;
1740 *old_access = file_share->access;
1741 *share_info = file_share;
1743 /* Increment the reference count while we
1744 * still have sole access to the shared area.
1745 * This makes the increment atomic wrt
1748 InterlockedIncrement ((gint32 *)&file_share->handle_refs);
1756 if (i == _WAPI_FILESHARE_SIZE && first_unused == -1) {
1759 if (first_unused == -1) {
1760 file_share = &_wapi_fileshare_layout->share_info[++i];
1761 _wapi_fileshare_layout->hwm = i;
1763 file_share = &_wapi_fileshare_layout->share_info[first_unused];
1766 file_share->device = device;
1767 file_share->inode = inode;
1768 file_share->opened_by_pid = _wapi_getpid ();
1769 file_share->sharemode = new_sharemode;
1770 file_share->access = new_access;
1771 file_share->handle_refs = 1;
1772 *share_info = file_share;
1776 if (*share_info != NULL) {
1777 InterlockedExchange ((gint32 *)&(*share_info)->timestamp, now);
1781 thr_ret = _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_FILESHARE);
1783 _wapi_handle_unlock_shared_handles ();
1788 /* If we don't have the info in /proc, check if the process that
1789 * opened this share info is still there (it's not a perfect method,
1792 static void _wapi_handle_check_share_by_pid (struct _WapiFileShare *share_info)
1794 #if defined(__native_client__)
1795 g_assert_not_reached ();
1797 if (kill (share_info->opened_by_pid, 0) == -1 &&
1800 /* It's gone completely (or there's a new process
1801 * owned by someone else) so mark this share info as
1804 DEBUG ("%s: Didn't find it, destroying entry", __func__);
1806 _wapi_free_share_info (share_info);
1812 /* Scan /proc/<pids>/fd/ for open file descriptors to the file in
1813 * question. If there are none, reset the share info.
1815 * This implementation is Linux-specific; legacy systems will have to
1816 * implement their own ways of finding out if a particular file is
1817 * open by a process.
1819 void _wapi_handle_check_share (struct _WapiFileShare *share_info, int fd)
1821 gboolean found = FALSE, proc_fds = FALSE;
1822 pid_t self = _wapi_getpid ();
1826 /* Prevents entries from expiring under us if we remove this
1829 thr_ret = _wapi_handle_lock_shared_handles ();
1830 g_assert (thr_ret == 0);
1832 /* Prevent new entries racing with us */
1833 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_FILESHARE);
1834 g_assert (thr_ret == 0);
1836 /* If there is no /proc, there's nothing more we can do here */
1837 if (access ("/proc", F_OK) == -1) {
1838 _wapi_handle_check_share_by_pid (share_info);
1842 /* If there's another handle that thinks it owns this fd, then even
1843 * if the fd has been closed behind our back consider it still owned.
1844 * See bugs 75764 and 75891
1846 for (i = 0; i < _wapi_fd_reserve; i++) {
1847 if (_wapi_private_handles [SLOT_INDEX (i)]) {
1848 struct _WapiHandleUnshared *handle = &_WAPI_PRIVATE_HANDLES(i);
1851 handle->type == WAPI_HANDLE_FILE) {
1852 struct _WapiHandle_file *file_handle = &handle->u.file;
1854 if (file_handle->share_info == share_info) {
1855 DEBUG ("%s: handle 0x%x has this file open!",
1864 if (proc_fds == FALSE) {
1865 _wapi_handle_check_share_by_pid (share_info);
1866 } else if (found == FALSE) {
1867 /* Blank out this entry, as it is stale */
1868 DEBUG ("%s: Didn't find it, destroying entry", __func__);
1870 _wapi_free_share_info (share_info);
1874 thr_ret = _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_FILESHARE);
1876 _wapi_handle_unlock_shared_handles ();
1880 // Other implementations (non-Linux)
1882 void _wapi_handle_check_share (struct _WapiFileShare *share_info, int fd)
1886 /* Prevents entries from expiring under us if we remove this
1888 thr_ret = _wapi_handle_lock_shared_handles ();
1889 g_assert (thr_ret == 0);
1891 /* Prevent new entries racing with us */
1892 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_FILESHARE);
1893 g_assert (thr_ret == 0);
1895 _wapi_handle_check_share_by_pid (share_info);
1897 thr_ret = _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_FILESHARE);
1898 _wapi_handle_unlock_shared_handles ();
1902 void _wapi_handle_dump (void)
1904 struct _WapiHandleUnshared *handle_data;
1908 thr_ret = mono_mutex_lock (&scan_mutex);
1909 g_assert (thr_ret == 0);
1911 for(i = SLOT_INDEX (0); i < _wapi_private_handle_slot_count; i++) {
1912 if (_wapi_private_handles [i]) {
1913 for (k = SLOT_OFFSET (0); k < _WAPI_HANDLE_INITIAL_COUNT; k++) {
1914 handle_data = &_wapi_private_handles [i][k];
1916 if (handle_data->type == WAPI_HANDLE_UNUSED) {
1920 g_print ("%3x [%7s] %s %d ",
1921 i * _WAPI_HANDLE_INITIAL_COUNT + k,
1922 _wapi_handle_typename[handle_data->type],
1923 handle_data->signalled?"Sg":"Un",
1925 handle_details[handle_data->type](&handle_data->u);
1931 thr_ret = mono_mutex_unlock (&scan_mutex);
1932 g_assert (thr_ret == 0);
1935 static void _wapi_shared_details (gpointer handle_info)
1937 struct _WapiHandle_shared_ref *shared = (struct _WapiHandle_shared_ref *)handle_info;
1939 g_print ("offset: 0x%x", shared->offset);
1942 void _wapi_handle_update_refs (void)
1946 guint32 now = (guint32)(time (NULL) & 0xFFFFFFFF);
1948 thr_ret = _wapi_handle_lock_shared_handles ();
1949 g_assert (thr_ret == 0);
1951 /* Prevent file share entries racing with us */
1952 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_FILESHARE);
1953 g_assert(thr_ret == 0);
1955 thr_ret = mono_mutex_lock (&scan_mutex);
1957 for(i = SLOT_INDEX (0); i < _wapi_private_handle_slot_count; i++) {
1958 if (_wapi_private_handles [i]) {
1959 for (k = SLOT_OFFSET (0); k < _WAPI_HANDLE_INITIAL_COUNT; k++) {
1960 struct _WapiHandleUnshared *handle = &_wapi_private_handles [i][k];
1962 if (_WAPI_SHARED_HANDLE(handle->type)) {
1963 struct _WapiHandleShared *shared_data;
1965 DEBUG ("%s: (%d) handle 0x%x is SHARED (%s)", __func__, _wapi_getpid (), i * _WAPI_HANDLE_INITIAL_COUNT + k, _wapi_handle_typename[handle->type]);
1967 shared_data = &_wapi_shared_layout->handles[handle->u.shared.offset];
1969 DEBUG ("%s: (%d) Updating timestamp of handle 0x%x", __func__, _wapi_getpid (), handle->u.shared.offset);
1971 InterlockedExchange ((gint32 *)&shared_data->timestamp, now);
1972 } else if (handle->type == WAPI_HANDLE_FILE) {
1973 struct _WapiHandle_file *file_handle = &handle->u.file;
1975 DEBUG ("%s: (%d) handle 0x%x is FILE", __func__, _wapi_getpid (), i * _WAPI_HANDLE_INITIAL_COUNT + k);
1977 g_assert (file_handle->share_info != NULL);
1979 DEBUG ("%s: (%d) Inc refs on fileshare 0x%x", __func__, _wapi_getpid (), (file_handle->share_info - &_wapi_fileshare_layout->share_info[0]) / sizeof(struct _WapiFileShare));
1981 InterlockedExchange ((gint32 *)&file_handle->share_info->timestamp, now);
1987 thr_ret = mono_mutex_unlock (&scan_mutex);
1988 g_assert (thr_ret == 0);
1990 thr_ret = _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_FILESHARE);
1992 _wapi_handle_unlock_shared_handles ();