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>
33 #include <mono/io-layer/wapi.h>
34 #include <mono/io-layer/wapi-private.h>
35 #include <mono/io-layer/handles-private.h>
36 #include <mono/io-layer/misc-private.h>
37 #include <mono/io-layer/shared.h>
38 #include <mono/io-layer/collection.h>
39 #include <mono/io-layer/process-private.h>
40 #include <mono/io-layer/critical-section-private.h>
42 #include <mono/utils/mono-mutex.h>
46 #define DEBUG(...) g_message(__VA_ARGS__)
51 static void (*_wapi_handle_ops_get_close_func (WapiHandleType type))(gpointer, gpointer);
53 static WapiHandleCapability handle_caps[WAPI_HANDLE_COUNT]={0};
54 static struct _WapiHandleOps *handle_ops[WAPI_HANDLE_COUNT]={
62 #ifndef DISABLE_SOCKETS
68 &_wapi_namedmutex_ops,
70 &_wapi_namedevent_ops,
73 static void _wapi_shared_details (gpointer handle_info);
75 static void (*handle_details[WAPI_HANDLE_COUNT])(gpointer) = {
78 _wapi_console_details,
79 _wapi_shared_details, /* thread */
83 NULL, /* Nothing useful to see in a socket handle */
84 NULL, /* Nothing useful to see in a find handle */
85 _wapi_shared_details, /* process */
87 _wapi_shared_details, /* namedmutex */
88 _wapi_shared_details, /* namedsem */
89 _wapi_shared_details, /* namedevent */
92 const char *_wapi_handle_typename[] = {
111 * We can hold _WAPI_PRIVATE_MAX_SLOTS * _WAPI_HANDLE_INITIAL_COUNT handles.
112 * If 4M handles are not enough... Oh, well... we will crash.
114 #define SLOT_INDEX(x) (x / _WAPI_HANDLE_INITIAL_COUNT)
115 #define SLOT_OFFSET(x) (x % _WAPI_HANDLE_INITIAL_COUNT)
117 struct _WapiHandleUnshared *_wapi_private_handles [_WAPI_PRIVATE_MAX_SLOTS];
118 static guint32 _wapi_private_handle_count = 0;
119 static guint32 _wapi_private_handle_slot_count = 0;
121 struct _WapiHandleSharedLayout *_wapi_shared_layout = NULL;
124 * If SHM is enabled, this will point to shared memory, otherwise it will be NULL.
126 struct _WapiFileShareLayout *_wapi_fileshare_layout = NULL;
129 * If SHM is disabled, this will point to a hash of _WapiFileShare structures, otherwise
130 * it will be NULL. We use this instead of _wapi_fileshare_layout to avoid allocating a
133 static GHashTable *file_share_hash;
134 static CRITICAL_SECTION file_share_hash_mutex;
136 #define file_share_hash_lock() EnterCriticalSection (&file_share_hash_mutex)
137 #define file_share_hash_unlock() LeaveCriticalSection (&file_share_hash_mutex)
139 guint32 _wapi_fd_reserve;
142 * This is an internal handle which is used for handling waiting for multiple handles.
143 * Threads which wait for multiple handles wait on this one handle, and when a handle
144 * is signalled, this handle is signalled too.
146 static gpointer _wapi_global_signal_handle;
148 /* Point to the mutex/cond inside _wapi_global_signal_handle */
149 mono_mutex_t *_wapi_global_signal_mutex;
150 pthread_cond_t *_wapi_global_signal_cond;
153 gboolean _wapi_has_shut_down = FALSE;
155 /* Use this instead of getpid(), to cope with linuxthreads. It's a
156 * function rather than a variable lookup because we need to get at
157 * this before share_init() might have been called.
159 static pid_t _wapi_pid;
160 static mono_once_t pid_init_once = MONO_ONCE_INIT;
162 static void _wapi_handle_unref_full (gpointer handle, gboolean ignore_private_busy_handles);
164 static void pid_init (void)
166 _wapi_pid = getpid ();
169 pid_t _wapi_getpid (void)
171 mono_once (&pid_init_once, pid_init);
177 static mono_mutex_t scan_mutex;
179 static void handle_cleanup (void)
183 /* Every shared handle we were using ought really to be closed
184 * by now, but to make sure just blow them all away. The
185 * exiting finalizer thread in particular races us to the
186 * program exit and doesn't always win, so it can be left
187 * cluttering up the shared file. Anything else left over is
190 for(i = SLOT_INDEX (0); _wapi_private_handles[i] != NULL; i++) {
191 for(j = SLOT_OFFSET (0); j < _WAPI_HANDLE_INITIAL_COUNT; j++) {
192 struct _WapiHandleUnshared *handle_data = &_wapi_private_handles[i][j];
193 gpointer handle = GINT_TO_POINTER (i*_WAPI_HANDLE_INITIAL_COUNT+j);
195 for(k = handle_data->ref; k > 0; k--) {
196 DEBUG ("%s: unreffing %s handle %p", __func__, _wapi_handle_typename[type], handle);
198 _wapi_handle_unref_full (handle, TRUE);
203 _wapi_shm_semaphores_remove ();
205 _wapi_shm_detach (WAPI_SHM_DATA);
206 _wapi_shm_detach (WAPI_SHM_FILESHARE);
208 if (file_share_hash) {
209 g_hash_table_destroy (file_share_hash);
210 DeleteCriticalSection (&file_share_hash_mutex);
213 for (i = 0; i < _WAPI_PRIVATE_MAX_SLOTS; ++i)
214 g_free (_wapi_private_handles [i]);
220 * Initialize the io-layer.
225 g_assert ((sizeof (handle_ops) / sizeof (handle_ops[0]))
226 == WAPI_HANDLE_COUNT);
228 _wapi_fd_reserve = getdtablesize();
230 /* This is needed by the code in _wapi_handle_new_internal */
231 _wapi_fd_reserve = (_wapi_fd_reserve + (_WAPI_HANDLE_INITIAL_COUNT - 1)) & ~(_WAPI_HANDLE_INITIAL_COUNT - 1);
235 * The entries in _wapi_private_handles reserved for fds are allocated lazily to
239 _wapi_private_handles [idx++] = g_new0 (struct _WapiHandleUnshared,
240 _WAPI_HANDLE_INITIAL_COUNT);
243 _wapi_private_handle_count += _WAPI_HANDLE_INITIAL_COUNT;
244 _wapi_private_handle_slot_count ++;
245 } while(_wapi_fd_reserve > _wapi_private_handle_count);
247 _wapi_shm_semaphores_init ();
249 _wapi_shared_layout = _wapi_shm_attach (WAPI_SHM_DATA);
250 g_assert (_wapi_shared_layout != NULL);
252 if (_wapi_shm_enabled ()) {
253 /* This allocates a 4mb array, so do it only if SHM is enabled */
254 _wapi_fileshare_layout = _wapi_shm_attach (WAPI_SHM_FILESHARE);
255 g_assert (_wapi_fileshare_layout != NULL);
258 #if !defined (DISABLE_SHARED_HANDLES)
259 if (_wapi_shm_enabled ())
260 _wapi_collection_init ();
263 mono_mutex_init (&scan_mutex);
265 _wapi_global_signal_handle = _wapi_handle_new (WAPI_HANDLE_EVENT, NULL);
267 _wapi_global_signal_cond = &_WAPI_PRIVATE_HANDLES (GPOINTER_TO_UINT (_wapi_global_signal_handle)).signal_cond;
268 _wapi_global_signal_mutex = &_WAPI_PRIVATE_HANDLES (GPOINTER_TO_UINT (_wapi_global_signal_handle)).signal_mutex;
271 /* Using g_atexit here instead of an explicit function call in
272 * a cleanup routine lets us cope when a third-party library
273 * calls exit (eg if an X client loses the connection to its
276 g_atexit (handle_cleanup);
282 g_assert (_wapi_has_shut_down == FALSE);
284 _wapi_has_shut_down = TRUE;
286 _wapi_error_cleanup ();
287 _wapi_thread_cleanup ();
288 wapi_processes_cleanup ();
291 static void _wapi_handle_init_shared (struct _WapiHandleShared *handle,
293 gpointer handle_specific)
295 g_assert (_wapi_has_shut_down == FALSE);
298 handle->timestamp = (guint32)(time (NULL) & 0xFFFFFFFF);
299 handle->signalled = FALSE;
300 handle->handle_refs = 1;
302 if (handle_specific != NULL) {
303 memcpy (&handle->u, handle_specific, sizeof (handle->u));
307 static size_t _wapi_handle_struct_size (WapiHandleType type)
312 case WAPI_HANDLE_FILE: case WAPI_HANDLE_CONSOLE: case WAPI_HANDLE_PIPE:
313 type_size = sizeof (struct _WapiHandle_file);
315 case WAPI_HANDLE_THREAD:
316 type_size = sizeof (struct _WapiHandle_thread);
318 case WAPI_HANDLE_SEM:
319 type_size = sizeof (struct _WapiHandle_sem);
321 case WAPI_HANDLE_MUTEX:
322 type_size = sizeof (struct _WapiHandle_mutex);
324 case WAPI_HANDLE_EVENT:
325 type_size = sizeof (struct _WapiHandle_event);
327 case WAPI_HANDLE_SOCKET:
328 type_size = sizeof (struct _WapiHandle_socket);
330 case WAPI_HANDLE_FIND:
331 type_size = sizeof (struct _WapiHandle_find);
333 case WAPI_HANDLE_PROCESS:
334 type_size = sizeof (struct _WapiHandle_process);
336 case WAPI_HANDLE_NAMEDMUTEX:
337 type_size = sizeof (struct _WapiHandle_namedmutex);
339 case WAPI_HANDLE_NAMEDSEM:
340 type_size = sizeof (struct _WapiHandle_namedsem);
342 case WAPI_HANDLE_NAMEDEVENT:
343 type_size = sizeof (struct _WapiHandle_namedevent);
347 g_error ("Unknown WapiHandleType: %d\n", type);
353 static void _wapi_handle_init (struct _WapiHandleUnshared *handle,
354 WapiHandleType type, gpointer handle_specific)
359 g_assert (_wapi_has_shut_down == FALSE);
362 handle->signalled = FALSE;
365 if (!_WAPI_SHARED_HANDLE(type)) {
366 thr_ret = pthread_cond_init (&handle->signal_cond, NULL);
367 g_assert (thr_ret == 0);
369 thr_ret = mono_mutex_init (&handle->signal_mutex);
370 g_assert (thr_ret == 0);
372 if (handle_specific != NULL) {
373 type_size = _wapi_handle_struct_size (type);
374 memcpy (&handle->u, handle_specific,
380 static guint32 _wapi_handle_new_shared (WapiHandleType type,
381 gpointer handle_specific)
384 static guint32 last = 1;
387 g_assert (_wapi_has_shut_down == FALSE);
389 /* Leave the first slot empty as a guard */
391 /* FIXME: expandable array */
392 for(offset = last; offset <_WAPI_HANDLE_INITIAL_COUNT; offset++) {
393 struct _WapiHandleShared *handle = &_wapi_shared_layout->handles[offset];
395 if(handle->type == WAPI_HANDLE_UNUSED) {
396 thr_ret = _wapi_handle_lock_shared_handles ();
397 g_assert (thr_ret == 0);
399 if (InterlockedCompareExchange ((gint32 *)&handle->type, type, WAPI_HANDLE_UNUSED) == WAPI_HANDLE_UNUSED) {
402 _wapi_handle_init_shared (handle, type,
405 _wapi_handle_unlock_shared_handles ();
409 /* Someone else beat us to it, just
414 _wapi_handle_unlock_shared_handles ();
419 /* Try again from the beginning */
424 /* Will need to expand the array. The caller will sort it out */
430 * _wapi_handle_new_internal:
431 * @type: Init handle to this type
433 * Search for a free handle and initialize it. Return the handle on
434 * success and 0 on failure. This is only called from
435 * _wapi_handle_new, and scan_mutex must be held.
437 static guint32 _wapi_handle_new_internal (WapiHandleType type,
438 gpointer handle_specific)
441 static guint32 last = 0;
442 gboolean retry = FALSE;
444 g_assert (_wapi_has_shut_down == FALSE);
446 /* A linear scan should be fast enough. Start from the last
447 * allocation, assuming that handles are allocated more often
448 * than they're freed. Leave the space reserved for file
452 if (last < _wapi_fd_reserve) {
453 last = _wapi_fd_reserve;
460 for(i = SLOT_INDEX (count); i < _wapi_private_handle_slot_count; i++) {
461 if (_wapi_private_handles [i]) {
462 for (k = SLOT_OFFSET (count); k < _WAPI_HANDLE_INITIAL_COUNT; k++) {
463 struct _WapiHandleUnshared *handle = &_wapi_private_handles [i][k];
465 if(handle->type == WAPI_HANDLE_UNUSED) {
468 _wapi_handle_init (handle, type, handle_specific);
476 if(retry && last > _wapi_fd_reserve) {
477 /* Try again from the beginning */
478 last = _wapi_fd_reserve;
482 /* Will need to expand the array. The caller will sort it out */
488 _wapi_handle_new (WapiHandleType type, gpointer handle_specific)
490 guint32 handle_idx = 0;
494 g_assert (_wapi_has_shut_down == FALSE);
496 DEBUG ("%s: Creating new handle of type %s", __func__,
497 _wapi_handle_typename[type]);
499 g_assert(!_WAPI_FD_HANDLE(type));
501 thr_ret = mono_mutex_lock (&scan_mutex);
502 g_assert (thr_ret == 0);
504 while ((handle_idx = _wapi_handle_new_internal (type, handle_specific)) == 0) {
505 /* Try and expand the array, and have another go */
506 int idx = SLOT_INDEX (_wapi_private_handle_count);
507 if (idx >= _WAPI_PRIVATE_MAX_SLOTS) {
511 _wapi_private_handles [idx] = g_new0 (struct _WapiHandleUnshared,
512 _WAPI_HANDLE_INITIAL_COUNT);
514 _wapi_private_handle_count += _WAPI_HANDLE_INITIAL_COUNT;
515 _wapi_private_handle_slot_count ++;
518 thr_ret = mono_mutex_unlock (&scan_mutex);
519 g_assert (thr_ret == 0);
521 if (handle_idx == 0) {
522 /* We ran out of slots */
523 handle = _WAPI_HANDLE_INVALID;
527 /* Make sure we left the space for fd mappings */
528 g_assert (handle_idx >= _wapi_fd_reserve);
530 handle = GUINT_TO_POINTER (handle_idx);
532 DEBUG ("%s: Allocated new handle %p", __func__, handle);
534 if (_WAPI_SHARED_HANDLE(type)) {
535 /* Add the shared section too */
538 ref = _wapi_handle_new_shared (type, handle_specific);
540 _wapi_handle_collect ();
541 ref = _wapi_handle_new_shared (type, handle_specific);
543 /* FIXME: grow the arrays */
544 handle = _WAPI_HANDLE_INVALID;
549 _WAPI_PRIVATE_HANDLES(handle_idx).u.shared.offset = ref;
550 DEBUG ("%s: New shared handle at offset 0x%x", __func__,
558 gpointer _wapi_handle_new_from_offset (WapiHandleType type, guint32 offset,
561 guint32 handle_idx = 0;
562 gpointer handle = INVALID_HANDLE_VALUE;
564 struct _WapiHandleShared *shared;
566 g_assert (_wapi_has_shut_down == FALSE);
568 DEBUG ("%s: Creating new handle of type %s to offset %d", __func__,
569 _wapi_handle_typename[type], offset);
571 g_assert(!_WAPI_FD_HANDLE(type));
572 g_assert(_WAPI_SHARED_HANDLE(type));
573 g_assert(offset != 0);
575 shared = &_wapi_shared_layout->handles[offset];
577 guint32 now = (guint32)(time (NULL) & 0xFFFFFFFF);
578 /* Bump up the timestamp for this offset */
579 InterlockedExchange ((gint32 *)&shared->timestamp, now);
582 thr_ret = mono_mutex_lock (&scan_mutex);
583 g_assert (thr_ret == 0);
585 for (i = SLOT_INDEX (0); i < _wapi_private_handle_slot_count; i++) {
586 if (_wapi_private_handles [i]) {
587 for (k = SLOT_OFFSET (0); k < _WAPI_HANDLE_INITIAL_COUNT; k++) {
588 struct _WapiHandleUnshared *handle_data = &_wapi_private_handles [i][k];
590 if (handle_data->type == type &&
591 handle_data->u.shared.offset == offset) {
592 handle = GUINT_TO_POINTER (i * _WAPI_HANDLE_INITIAL_COUNT + k);
593 goto first_pass_done;
600 thr_ret = mono_mutex_unlock (&scan_mutex);
601 g_assert (thr_ret == 0);
603 if (handle != INVALID_HANDLE_VALUE) {
604 _wapi_handle_ref (handle);
606 DEBUG ("%s: Returning old handle %p referencing 0x%x",
607 __func__, handle, offset);
611 /* Prevent entries expiring under us as we search */
612 thr_ret = _wapi_handle_lock_shared_handles ();
613 g_assert (thr_ret == 0);
615 if (shared->type == WAPI_HANDLE_UNUSED) {
616 /* Someone deleted this handle while we were working */
617 DEBUG ("%s: Handle at 0x%x unused", __func__, offset);
621 if (shared->type != type) {
622 DEBUG ("%s: Wrong type at %d 0x%x! Found %s wanted %s",
623 __func__, offset, offset,
624 _wapi_handle_typename[shared->type],
625 _wapi_handle_typename[type]);
629 thr_ret = mono_mutex_lock (&scan_mutex);
630 g_assert (thr_ret == 0);
632 while ((handle_idx = _wapi_handle_new_internal (type, NULL)) == 0) {
633 /* Try and expand the array, and have another go */
634 int idx = SLOT_INDEX (_wapi_private_handle_count);
635 _wapi_private_handles [idx] = g_new0 (struct _WapiHandleUnshared,
636 _WAPI_HANDLE_INITIAL_COUNT);
638 _wapi_private_handle_count += _WAPI_HANDLE_INITIAL_COUNT;
639 _wapi_private_handle_slot_count ++;
642 thr_ret = mono_mutex_unlock (&scan_mutex);
643 g_assert (thr_ret == 0);
645 /* Make sure we left the space for fd mappings */
646 g_assert (handle_idx >= _wapi_fd_reserve);
648 handle = GUINT_TO_POINTER (handle_idx);
650 _WAPI_PRIVATE_HANDLES(handle_idx).u.shared.offset = offset;
651 InterlockedIncrement ((gint32 *)&shared->handle_refs);
653 DEBUG ("%s: Allocated new handle %p referencing 0x%x (shared refs %d)", __func__, handle, offset, shared->handle_refs);
656 _wapi_handle_unlock_shared_handles ();
662 init_handles_slot (int idx)
666 thr_ret = mono_mutex_lock (&scan_mutex);
667 g_assert (thr_ret == 0);
669 if (_wapi_private_handles [idx] == NULL) {
670 _wapi_private_handles [idx] = g_new0 (struct _WapiHandleUnshared,
671 _WAPI_HANDLE_INITIAL_COUNT);
672 g_assert (_wapi_private_handles [idx]);
675 thr_ret = mono_mutex_unlock (&scan_mutex);
676 g_assert (thr_ret == 0);
679 gpointer _wapi_handle_new_fd (WapiHandleType type, int fd,
680 gpointer handle_specific)
682 struct _WapiHandleUnshared *handle;
685 g_assert (_wapi_has_shut_down == FALSE);
687 DEBUG ("%s: Creating new handle of type %s", __func__,
688 _wapi_handle_typename[type]);
690 g_assert(_WAPI_FD_HANDLE(type));
691 g_assert(!_WAPI_SHARED_HANDLE(type));
693 if (fd >= _wapi_fd_reserve) {
694 DEBUG ("%s: fd %d is too big", __func__, fd);
696 return(GUINT_TO_POINTER (_WAPI_HANDLE_INVALID));
699 /* Initialize the array entries on demand */
700 if (_wapi_private_handles [SLOT_INDEX (fd)] == NULL)
701 init_handles_slot (SLOT_INDEX (fd));
703 handle = &_WAPI_PRIVATE_HANDLES(fd);
705 if (handle->type != WAPI_HANDLE_UNUSED) {
706 DEBUG ("%s: fd %d is already in use!", __func__, fd);
707 /* FIXME: clean up this handle? We can't do anything
708 * with the fd, cos thats the new one
712 DEBUG ("%s: Assigning new fd handle %d", __func__, fd);
714 /* Prevent file share entries racing with us, when the file
715 * handle is only half initialised
717 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_FILESHARE);
718 g_assert(thr_ret == 0);
720 _wapi_handle_init (handle, type, handle_specific);
722 thr_ret = _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_FILESHARE);
724 return(GUINT_TO_POINTER(fd));
727 gboolean _wapi_lookup_handle (gpointer handle, WapiHandleType type,
728 gpointer *handle_specific)
730 struct _WapiHandleUnshared *handle_data;
731 guint32 handle_idx = GPOINTER_TO_UINT(handle);
733 if (!_WAPI_PRIVATE_VALID_SLOT (handle_idx)) {
737 /* Initialize the array entries on demand */
738 if (_wapi_private_handles [SLOT_INDEX (handle_idx)] == NULL)
739 init_handles_slot (SLOT_INDEX (handle_idx));
741 handle_data = &_WAPI_PRIVATE_HANDLES(handle_idx);
743 if (handle_data->type != type) {
747 if (handle_specific == NULL) {
751 if (_WAPI_SHARED_HANDLE(type)) {
752 struct _WapiHandle_shared_ref *ref;
753 struct _WapiHandleShared *shared_handle_data;
755 ref = &handle_data->u.shared;
756 shared_handle_data = &_wapi_shared_layout->handles[ref->offset];
758 if (shared_handle_data->type != type) {
759 /* The handle must have been deleted on us
764 *handle_specific = &shared_handle_data->u;
766 *handle_specific = &handle_data->u;
773 _wapi_handle_foreach (WapiHandleType type,
774 gboolean (*on_each)(gpointer test, gpointer user),
777 struct _WapiHandleUnshared *handle_data = NULL;
782 thr_ret = mono_mutex_lock (&scan_mutex);
783 g_assert (thr_ret == 0);
785 for (i = SLOT_INDEX (0); i < _wapi_private_handle_slot_count; i++) {
786 if (_wapi_private_handles [i]) {
787 for (k = SLOT_OFFSET (0); k < _WAPI_HANDLE_INITIAL_COUNT; k++) {
788 handle_data = &_wapi_private_handles [i][k];
790 if (handle_data->type == type) {
791 ret = GUINT_TO_POINTER (i * _WAPI_HANDLE_INITIAL_COUNT + k);
792 if (on_each (ret, user_data) == TRUE)
799 thr_ret = mono_mutex_unlock (&scan_mutex);
800 g_assert (thr_ret == 0);
803 /* This might list some shared handles twice if they are already
804 * opened by this process, and the check function returns FALSE the
805 * first time. Shared handles that are created during the search are
806 * unreffed if the check function returns FALSE, so callers must not
807 * rely on the handle persisting (unless the check function returns
809 * The caller owns the returned handle.
811 gpointer _wapi_search_handle (WapiHandleType type,
812 gboolean (*check)(gpointer test, gpointer user),
814 gpointer *handle_specific,
815 gboolean search_shared)
817 struct _WapiHandleUnshared *handle_data = NULL;
818 struct _WapiHandleShared *shared = NULL;
821 gboolean found = FALSE;
824 thr_ret = mono_mutex_lock (&scan_mutex);
825 g_assert (thr_ret == 0);
827 for (i = SLOT_INDEX (0); !found && i < _wapi_private_handle_slot_count; i++) {
828 if (_wapi_private_handles [i]) {
829 for (k = SLOT_OFFSET (0); k < _WAPI_HANDLE_INITIAL_COUNT; k++) {
830 handle_data = &_wapi_private_handles [i][k];
832 if (handle_data->type == type) {
833 ret = GUINT_TO_POINTER (i * _WAPI_HANDLE_INITIAL_COUNT + k);
834 if (check (ret, user_data) == TRUE) {
835 _wapi_handle_ref (ret);
838 if (_WAPI_SHARED_HANDLE (type)) {
839 shared = &_wapi_shared_layout->handles[i];
849 thr_ret = mono_mutex_unlock (&scan_mutex);
850 g_assert (thr_ret == 0);
852 if (!found && search_shared && _WAPI_SHARED_HANDLE (type)) {
853 /* Not found yet, so search the shared memory too */
854 DEBUG ("%s: Looking at other shared handles...", __func__);
856 for (i = 0; i < _WAPI_HANDLE_INITIAL_COUNT; i++) {
857 shared = &_wapi_shared_layout->handles[i];
859 if (shared->type == type) {
860 /* Tell new_from_offset to not
861 * timestamp this handle, because
862 * otherwise it will ping every handle
863 * in the list and they will never
866 ret = _wapi_handle_new_from_offset (type, i,
868 if (ret == INVALID_HANDLE_VALUE) {
869 /* This handle was deleted
870 * while we were looking at it
875 DEBUG ("%s: Opened tmp handle %p (type %s) from offset %d", __func__, ret, _wapi_handle_typename[type], i);
877 /* It's possible that the shared part
878 * of this handle has now been blown
879 * away (after new_from_offset
880 * successfully opened it,) if its
881 * timestamp is too old. The check
882 * function needs to be aware of this,
883 * and cope if the handle has
886 if (check (ret, user_data) == TRUE) {
887 /* Timestamp this handle, but make
888 * sure it still exists first
890 thr_ret = _wapi_handle_lock_shared_handles ();
891 g_assert (thr_ret == 0);
893 if (shared->type == type) {
894 guint32 now = (guint32)(time (NULL) & 0xFFFFFFFF);
895 InterlockedExchange ((gint32 *)&shared->timestamp, now);
898 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(ret));
900 _wapi_handle_unlock_shared_handles ();
903 /* It's been deleted,
907 _wapi_handle_unlock_shared_handles ();
911 /* This isn't the handle we're looking
912 * for, so drop the reference we took
913 * in _wapi_handle_new_from_offset ()
915 _wapi_handle_unref (ret);
925 if(handle_specific != NULL) {
926 if (_WAPI_SHARED_HANDLE(type)) {
927 g_assert(shared->type == type);
929 *handle_specific = &shared->u;
931 *handle_specific = &handle_data->u;
939 /* Returns the offset of the metadata array, or -1 on error, or 0 for
940 * not found (0 is not a valid offset)
942 gint32 _wapi_search_handle_namespace (WapiHandleType type,
945 struct _WapiHandleShared *shared_handle_data;
950 g_assert(_WAPI_SHARED_HANDLE(type));
952 DEBUG ("%s: Lookup for handle named [%s] type %s", __func__,
953 utf8_name, _wapi_handle_typename[type]);
955 /* Do a handle collection before starting to look, so that any
956 * stale cruft gets removed
958 _wapi_handle_collect ();
960 thr_ret = _wapi_handle_lock_shared_handles ();
961 g_assert (thr_ret == 0);
963 for(i = 1; i < _WAPI_HANDLE_INITIAL_COUNT; i++) {
964 WapiSharedNamespace *sharedns;
966 shared_handle_data = &_wapi_shared_layout->handles[i];
968 /* Check mutex, event, semaphore, timer, job and
969 * file-mapping object names. So far only mutex,
970 * semaphore and event are implemented.
972 if (!_WAPI_SHARED_NAMESPACE (shared_handle_data->type)) {
976 DEBUG ("%s: found a shared namespace handle at 0x%x (type %s)", __func__, i, _wapi_handle_typename[shared_handle_data->type]);
978 sharedns=(WapiSharedNamespace *)&shared_handle_data->u;
980 DEBUG ("%s: name is [%s]", __func__, sharedns->name);
982 if (strcmp (sharedns->name, utf8_name) == 0) {
983 if (shared_handle_data->type != type) {
984 /* Its the wrong type, so fail now */
985 DEBUG ("%s: handle 0x%x matches name but is wrong type: %s", __func__, i, _wapi_handle_typename[shared_handle_data->type]);
989 DEBUG ("%s: handle 0x%x matches name and type", __func__, i);
997 _wapi_handle_unlock_shared_handles ();
1002 void _wapi_handle_ref (gpointer handle)
1004 guint32 idx = GPOINTER_TO_UINT(handle);
1005 struct _WapiHandleUnshared *handle_data;
1007 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1011 if (_wapi_handle_type (handle) == WAPI_HANDLE_UNUSED) {
1012 g_warning ("%s: Attempting to ref unused handle %p", __func__,
1017 handle_data = &_WAPI_PRIVATE_HANDLES(idx);
1019 InterlockedIncrement ((gint32 *)&handle_data->ref);
1021 /* It's possible for processes to exit before getting around
1022 * to updating timestamps in the collection thread, so if a
1023 * shared handle is reffed do the timestamp here as well just
1026 if (_WAPI_SHARED_HANDLE(handle_data->type)) {
1027 struct _WapiHandleShared *shared_data = &_wapi_shared_layout->handles[handle_data->u.shared.offset];
1028 guint32 now = (guint32)(time (NULL) & 0xFFFFFFFF);
1029 InterlockedExchange ((gint32 *)&shared_data->timestamp, now);
1033 g_message ("%s: %s handle %p ref now %d", __func__,
1034 _wapi_handle_typename[_WAPI_PRIVATE_HANDLES (idx).type],
1036 _WAPI_PRIVATE_HANDLES(idx).ref);
1040 /* The handle must not be locked on entry to this function */
1041 static void _wapi_handle_unref_full (gpointer handle, gboolean ignore_private_busy_handles)
1043 guint32 idx = GPOINTER_TO_UINT(handle);
1044 gboolean destroy = FALSE, early_exit = FALSE;
1047 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1051 if (_wapi_handle_type (handle) == WAPI_HANDLE_UNUSED) {
1052 g_warning ("%s: Attempting to unref unused handle %p",
1057 /* Possible race condition here if another thread refs the
1058 * handle between here and setting the type to UNUSED. I
1059 * could lock a mutex, but I'm not sure that allowing a handle
1060 * reference to reach 0 isn't an application bug anyway.
1062 destroy = (InterlockedDecrement ((gint32 *)&_WAPI_PRIVATE_HANDLES(idx).ref) ==0);
1065 g_message ("%s: %s handle %p ref now %d (destroy %s)", __func__,
1066 _wapi_handle_typename[_WAPI_PRIVATE_HANDLES (idx).type],
1068 _WAPI_PRIVATE_HANDLES(idx).ref, destroy?"TRUE":"FALSE");
1072 /* Need to copy the handle info, reset the slot in the
1073 * array, and _only then_ call the close function to
1074 * avoid race conditions (eg file descriptors being
1075 * closed, and another file being opened getting the
1076 * same fd racing the memset())
1078 struct _WapiHandleUnshared handle_data;
1079 struct _WapiHandleShared shared_handle_data;
1080 WapiHandleType type = _WAPI_PRIVATE_HANDLES(idx).type;
1081 void (*close_func)(gpointer, gpointer) = _wapi_handle_ops_get_close_func (type);
1082 gboolean is_shared = _WAPI_SHARED_HANDLE(type);
1085 /* If this is a shared handle we need to take
1086 * the shared lock outside of the scan_mutex
1087 * lock to avoid deadlocks
1089 thr_ret = _wapi_handle_lock_shared_handles ();
1090 g_assert (thr_ret == 0);
1093 thr_ret = mono_mutex_lock (&scan_mutex);
1095 DEBUG ("%s: Destroying handle %p", __func__, handle);
1097 memcpy (&handle_data, &_WAPI_PRIVATE_HANDLES(idx),
1098 sizeof (struct _WapiHandleUnshared));
1100 memset (&_WAPI_PRIVATE_HANDLES(idx).u, '\0',
1101 sizeof(_WAPI_PRIVATE_HANDLES(idx).u));
1103 _WAPI_PRIVATE_HANDLES(idx).type = WAPI_HANDLE_UNUSED;
1106 /* Destroy the mutex and cond var. We hope nobody
1107 * tried to grab them between the handle unlock and
1108 * now, but pthreads doesn't have a
1109 * "unlock_and_destroy" atomic function.
1111 thr_ret = mono_mutex_destroy (&_WAPI_PRIVATE_HANDLES(idx).signal_mutex);
1112 /*WARNING gross hack to make cleanup not crash when exiting without the whole runtime teardown.*/
1113 if (thr_ret == EBUSY && ignore_private_busy_handles) {
1117 g_error ("Error destroying handle %p mutex due to %d\n", handle, thr_ret);
1119 thr_ret = pthread_cond_destroy (&_WAPI_PRIVATE_HANDLES(idx).signal_cond);
1120 if (thr_ret == EBUSY && ignore_private_busy_handles)
1122 else if (thr_ret != 0)
1123 g_error ("Error destroying handle %p cond var due to %d\n", handle, thr_ret);
1126 struct _WapiHandleShared *shared = &_wapi_shared_layout->handles[handle_data.u.shared.offset];
1128 memcpy (&shared_handle_data, shared,
1129 sizeof (struct _WapiHandleShared));
1131 /* It's possible that this handle is already
1132 * pointing at a deleted shared section
1135 g_message ("%s: %s handle %p shared refs before dec %d", __func__, _wapi_handle_typename[type], handle, shared->handle_refs);
1138 if (shared->handle_refs > 0) {
1139 shared->handle_refs--;
1140 if (shared->handle_refs == 0) {
1141 memset (shared, '\0', sizeof (struct _WapiHandleShared));
1146 thr_ret = mono_mutex_unlock (&scan_mutex);
1147 g_assert (thr_ret == 0);
1152 _wapi_handle_unlock_shared_handles ();
1155 if (close_func != NULL) {
1157 close_func (handle, &shared_handle_data.u);
1159 close_func (handle, &handle_data.u);
1165 void _wapi_handle_unref (gpointer handle)
1167 _wapi_handle_unref_full (handle, FALSE);
1170 void _wapi_handle_register_capabilities (WapiHandleType type,
1171 WapiHandleCapability caps)
1173 handle_caps[type] = caps;
1176 gboolean _wapi_handle_test_capabilities (gpointer handle,
1177 WapiHandleCapability caps)
1179 guint32 idx = GPOINTER_TO_UINT(handle);
1180 WapiHandleType type;
1182 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1186 type = _WAPI_PRIVATE_HANDLES(idx).type;
1188 DEBUG ("%s: testing 0x%x against 0x%x (%d)", __func__,
1189 handle_caps[type], caps, handle_caps[type] & caps);
1191 return((handle_caps[type] & caps) != 0);
1194 static void (*_wapi_handle_ops_get_close_func (WapiHandleType type))(gpointer, gpointer)
1196 if (handle_ops[type] != NULL &&
1197 handle_ops[type]->close != NULL) {
1198 return (handle_ops[type]->close);
1204 void _wapi_handle_ops_close (gpointer handle, gpointer data)
1206 guint32 idx = GPOINTER_TO_UINT(handle);
1207 WapiHandleType type;
1209 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1213 type = _WAPI_PRIVATE_HANDLES(idx).type;
1215 if (handle_ops[type] != NULL &&
1216 handle_ops[type]->close != NULL) {
1217 handle_ops[type]->close (handle, data);
1221 void _wapi_handle_ops_signal (gpointer handle)
1223 guint32 idx = GPOINTER_TO_UINT(handle);
1224 WapiHandleType type;
1226 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1230 type = _WAPI_PRIVATE_HANDLES(idx).type;
1232 if (handle_ops[type] != NULL && handle_ops[type]->signal != NULL) {
1233 handle_ops[type]->signal (handle);
1237 gboolean _wapi_handle_ops_own (gpointer handle)
1239 guint32 idx = GPOINTER_TO_UINT(handle);
1240 WapiHandleType type;
1242 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1246 type = _WAPI_PRIVATE_HANDLES(idx).type;
1248 if (handle_ops[type] != NULL && handle_ops[type]->own_handle != NULL) {
1249 return(handle_ops[type]->own_handle (handle));
1255 gboolean _wapi_handle_ops_isowned (gpointer handle)
1257 guint32 idx = GPOINTER_TO_UINT(handle);
1258 WapiHandleType type;
1260 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1264 type = _WAPI_PRIVATE_HANDLES(idx).type;
1266 if (handle_ops[type] != NULL && handle_ops[type]->is_owned != NULL) {
1267 return(handle_ops[type]->is_owned (handle));
1273 guint32 _wapi_handle_ops_special_wait (gpointer handle, guint32 timeout, gboolean alertable)
1275 guint32 idx = GPOINTER_TO_UINT(handle);
1276 WapiHandleType type;
1278 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1279 return(WAIT_FAILED);
1282 type = _WAPI_PRIVATE_HANDLES(idx).type;
1284 if (handle_ops[type] != NULL &&
1285 handle_ops[type]->special_wait != NULL) {
1286 return(handle_ops[type]->special_wait (handle, timeout, alertable));
1288 return(WAIT_FAILED);
1292 void _wapi_handle_ops_prewait (gpointer handle)
1294 guint32 idx = GPOINTER_TO_UINT (handle);
1295 WapiHandleType type;
1297 if (!_WAPI_PRIVATE_VALID_SLOT (idx)) {
1301 type = _WAPI_PRIVATE_HANDLES (idx).type;
1303 if (handle_ops[type] != NULL &&
1304 handle_ops[type]->prewait != NULL) {
1305 handle_ops[type]->prewait (handle);
1312 * @handle: The handle to release
1314 * Closes and invalidates @handle, releasing any resources it
1315 * consumes. When the last handle to a temporary or non-persistent
1316 * object is closed, that object can be deleted. Closing the same
1317 * handle twice is an error.
1319 * Return value: %TRUE on success, %FALSE otherwise.
1321 gboolean CloseHandle(gpointer handle)
1323 if (handle == NULL) {
1324 /* Problem: because we map file descriptors to the
1325 * same-numbered handle we can't tell the difference
1326 * between a bogus handle and the handle to stdin.
1327 * Assume that it's the console handle if that handle
1330 if (_WAPI_PRIVATE_HANDLES (0).type != WAPI_HANDLE_CONSOLE) {
1331 SetLastError (ERROR_INVALID_PARAMETER);
1335 if (handle == _WAPI_HANDLE_INVALID){
1336 SetLastError (ERROR_INVALID_PARAMETER);
1340 _wapi_handle_unref (handle);
1345 /* Lots more to implement here, but this is all we need at the moment */
1346 gboolean DuplicateHandle (gpointer srcprocess, gpointer src,
1347 gpointer targetprocess, gpointer *target,
1348 guint32 access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 options G_GNUC_UNUSED)
1350 if (srcprocess != _WAPI_PROCESS_CURRENT ||
1351 targetprocess != _WAPI_PROCESS_CURRENT) {
1352 /* Duplicating other process's handles is not supported */
1353 SetLastError (ERROR_INVALID_HANDLE);
1357 if (src == _WAPI_PROCESS_CURRENT) {
1358 *target = _wapi_process_duplicate ();
1359 } else if (src == _WAPI_THREAD_CURRENT) {
1360 g_assert_not_reached ();
1362 _wapi_handle_ref (src);
1369 gboolean _wapi_handle_count_signalled_handles (guint32 numhandles,
1375 guint32 count, i, iter=0;
1378 WapiHandleType type;
1380 /* Lock all the handles, with backoff */
1382 thr_ret = _wapi_handle_lock_shared_handles ();
1383 g_assert (thr_ret == 0);
1385 for(i=0; i<numhandles; i++) {
1386 gpointer handle = handles[i];
1387 guint32 idx = GPOINTER_TO_UINT(handle);
1389 DEBUG ("%s: attempting to lock %p", __func__, handle);
1391 type = _WAPI_PRIVATE_HANDLES(idx).type;
1393 thr_ret = _wapi_handle_trylock_handle (handle);
1398 DEBUG ("%s: attempt failed for %p: %s", __func__,
1399 handle, strerror (thr_ret));
1401 thr_ret = _wapi_handle_unlock_shared_handles ();
1402 g_assert (thr_ret == 0);
1405 handle = handles[i];
1406 idx = GPOINTER_TO_UINT(handle);
1408 thr_ret = _wapi_handle_unlock_handle (handle);
1409 g_assert (thr_ret == 0);
1412 /* If iter ever reaches 100 the nanosleep will
1413 * return EINVAL immediately, but we have a
1414 * design flaw if that happens.
1418 g_warning ("%s: iteration overflow!",
1423 DEBUG ("%s: Backing off for %d ms", __func__,
1425 _wapi_handle_spin (10 * iter);
1431 DEBUG ("%s: Locked all handles", __func__);
1436 for(i=0; i<numhandles; i++) {
1437 gpointer handle = handles[i];
1438 guint32 idx = GPOINTER_TO_UINT(handle);
1440 type = _WAPI_PRIVATE_HANDLES(idx).type;
1442 DEBUG ("%s: Checking handle %p", __func__, handle);
1444 if(((_wapi_handle_test_capabilities (handle, WAPI_HANDLE_CAP_OWN)==TRUE) &&
1445 (_wapi_handle_ops_isowned (handle) == TRUE)) ||
1446 (_WAPI_SHARED_HANDLE(type) &&
1447 WAPI_SHARED_HANDLE_DATA(handle).signalled == TRUE) ||
1448 (!_WAPI_SHARED_HANDLE(type) &&
1449 _WAPI_PRIVATE_HANDLES(idx).signalled == TRUE)) {
1452 DEBUG ("%s: Handle %p signalled", __func__,
1460 DEBUG ("%s: %d event handles signalled", __func__, count);
1462 if ((waitall == TRUE && count == numhandles) ||
1463 (waitall == FALSE && count > 0)) {
1469 DEBUG ("%s: Returning %d", __func__, ret);
1476 void _wapi_handle_unlock_handles (guint32 numhandles, gpointer *handles)
1481 thr_ret = _wapi_handle_unlock_shared_handles ();
1482 g_assert (thr_ret == 0);
1484 for(i=0; i<numhandles; i++) {
1485 gpointer handle = handles[i];
1487 DEBUG ("%s: unlocking handle %p", __func__, handle);
1489 thr_ret = _wapi_handle_unlock_handle (handle);
1490 g_assert (thr_ret == 0);
1494 static int timedwait_signal_poll_cond (pthread_cond_t *cond, mono_mutex_t *mutex, struct timespec *timeout, gboolean alertable)
1496 struct timespec fake_timeout;
1501 ret=mono_cond_timedwait (cond, mutex, timeout);
1503 ret=mono_cond_wait (cond, mutex);
1505 _wapi_calc_timeout (&fake_timeout, 100);
1507 if (timeout != NULL && ((fake_timeout.tv_sec > timeout->tv_sec) ||
1508 (fake_timeout.tv_sec == timeout->tv_sec &&
1509 fake_timeout.tv_nsec > timeout->tv_nsec))) {
1510 /* Real timeout is less than 100ms time */
1511 ret=mono_cond_timedwait (cond, mutex, timeout);
1513 ret=mono_cond_timedwait (cond, mutex, &fake_timeout);
1515 /* Mask the fake timeout, this will cause
1516 * another poll if the cond was not really signaled
1518 if (ret==ETIMEDOUT) {
1527 int _wapi_handle_wait_signal (gboolean poll)
1529 return _wapi_handle_timedwait_signal_handle (_wapi_global_signal_handle, NULL, TRUE, poll);
1532 int _wapi_handle_timedwait_signal (struct timespec *timeout, gboolean poll)
1534 return _wapi_handle_timedwait_signal_handle (_wapi_global_signal_handle, timeout, TRUE, poll);
1537 int _wapi_handle_wait_signal_handle (gpointer handle, gboolean alertable)
1539 DEBUG ("%s: waiting for %p", __func__, handle);
1541 return _wapi_handle_timedwait_signal_handle (handle, NULL, alertable, FALSE);
1544 int _wapi_handle_timedwait_signal_handle (gpointer handle,
1545 struct timespec *timeout, gboolean alertable, gboolean poll)
1547 DEBUG ("%s: waiting for %p (type %s)", __func__, handle,
1548 _wapi_handle_typename[_wapi_handle_type (handle)]);
1550 if (_WAPI_SHARED_HANDLE (_wapi_handle_type (handle))) {
1551 if (WAPI_SHARED_HANDLE_DATA(handle).signalled == TRUE) {
1554 if (timeout != NULL) {
1555 struct timespec fake_timeout;
1556 _wapi_calc_timeout (&fake_timeout, 100);
1558 if ((fake_timeout.tv_sec > timeout->tv_sec) ||
1559 (fake_timeout.tv_sec == timeout->tv_sec &&
1560 fake_timeout.tv_nsec > timeout->tv_nsec)) {
1561 /* FIXME: Real timeout is less than
1562 * 100ms time, but is it really worth
1563 * calculating to the exact ms?
1565 _wapi_handle_spin (100);
1567 if (WAPI_SHARED_HANDLE_DATA(handle).signalled == TRUE) {
1574 _wapi_handle_spin (100);
1578 guint32 idx = GPOINTER_TO_UINT(handle);
1580 pthread_cond_t *cond;
1581 mono_mutex_t *mutex;
1583 if (alertable && !wapi_thread_set_wait_handle (handle))
1586 cond = &_WAPI_PRIVATE_HANDLES (idx).signal_cond;
1587 mutex = &_WAPI_PRIVATE_HANDLES (idx).signal_mutex;
1590 /* This is needed when waiting for process handles */
1591 res = timedwait_signal_poll_cond (cond, mutex, timeout, alertable);
1594 res = mono_cond_timedwait (cond, mutex, timeout);
1596 res = mono_cond_wait (cond, mutex);
1600 wapi_thread_clear_wait_handle (handle);
1607 _wapi_free_share_info (_WapiFileShare *share_info)
1609 if (!_wapi_shm_enabled ()) {
1610 file_share_hash_lock ();
1611 g_hash_table_remove (file_share_hash, share_info);
1612 file_share_hash_unlock ();
1613 /* The hashtable dtor frees share_info */
1615 memset (share_info, '\0', sizeof(struct _WapiFileShare));
1620 wapi_share_info_equal (gconstpointer ka, gconstpointer kb)
1622 const _WapiFileShare *s1 = ka;
1623 const _WapiFileShare *s2 = kb;
1625 return (s1->device == s2->device && s1->inode == s2->inode) ? 1 : 0;
1629 wapi_share_info_hash (gconstpointer data)
1631 const _WapiFileShare *s = data;
1636 gboolean _wapi_handle_get_or_set_share (dev_t device, ino_t inode,
1637 guint32 new_sharemode,
1639 guint32 *old_sharemode,
1640 guint32 *old_access,
1641 struct _WapiFileShare **share_info)
1643 struct _WapiFileShare *file_share;
1644 guint32 now = (guint32)(time(NULL) & 0xFFFFFFFF);
1645 int thr_ret, i, first_unused = -1;
1646 gboolean exists = FALSE;
1648 /* Prevents entries from expiring under us as we search
1650 thr_ret = _wapi_handle_lock_shared_handles ();
1651 g_assert (thr_ret == 0);
1653 /* Prevent new entries racing with us */
1654 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_FILESHARE);
1655 g_assert (thr_ret == 0);
1657 if (!_wapi_shm_enabled ()) {
1661 * Instead of allocating a 4MB array, we use a hash table to keep track of this
1662 * info. This is needed even if SHM is disabled, to track sharing inside
1663 * the current process.
1665 if (!file_share_hash) {
1666 file_share_hash = g_hash_table_new_full (wapi_share_info_hash, wapi_share_info_equal, NULL, g_free);
1667 InitializeCriticalSection (&file_share_hash_mutex);
1670 tmp.device = device;
1673 file_share_hash_lock ();
1675 file_share = g_hash_table_lookup (file_share_hash, &tmp);
1677 *old_sharemode = file_share->sharemode;
1678 *old_access = file_share->access;
1679 *share_info = file_share;
1681 InterlockedIncrement ((gint32 *)&file_share->handle_refs);
1684 file_share = g_new0 (_WapiFileShare, 1);
1686 file_share->device = device;
1687 file_share->inode = inode;
1688 file_share->opened_by_pid = _wapi_getpid ();
1689 file_share->sharemode = new_sharemode;
1690 file_share->access = new_access;
1691 file_share->handle_refs = 1;
1692 *share_info = file_share;
1694 g_hash_table_insert (file_share_hash, file_share, file_share);
1697 file_share_hash_unlock ();
1699 /* If a linear scan gets too slow we'll have to fit a hash
1700 * table onto the shared mem backing store
1703 for (i = 0; i <= _wapi_fileshare_layout->hwm; i++) {
1704 file_share = &_wapi_fileshare_layout->share_info[i];
1706 /* Make a note of an unused slot, in case we need to
1709 if (first_unused == -1 && file_share->handle_refs == 0) {
1714 if (file_share->handle_refs == 0) {
1718 if (file_share->device == device &&
1719 file_share->inode == inode) {
1720 *old_sharemode = file_share->sharemode;
1721 *old_access = file_share->access;
1722 *share_info = file_share;
1724 /* Increment the reference count while we
1725 * still have sole access to the shared area.
1726 * This makes the increment atomic wrt
1729 InterlockedIncrement ((gint32 *)&file_share->handle_refs);
1737 if (i == _WAPI_FILESHARE_SIZE && first_unused == -1) {
1740 if (first_unused == -1) {
1741 file_share = &_wapi_fileshare_layout->share_info[++i];
1742 _wapi_fileshare_layout->hwm = i;
1744 file_share = &_wapi_fileshare_layout->share_info[first_unused];
1747 file_share->device = device;
1748 file_share->inode = inode;
1749 file_share->opened_by_pid = _wapi_getpid ();
1750 file_share->sharemode = new_sharemode;
1751 file_share->access = new_access;
1752 file_share->handle_refs = 1;
1753 *share_info = file_share;
1757 if (*share_info != NULL) {
1758 InterlockedExchange ((gint32 *)&(*share_info)->timestamp, now);
1762 thr_ret = _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_FILESHARE);
1764 _wapi_handle_unlock_shared_handles ();
1769 /* If we don't have the info in /proc, check if the process that
1770 * opened this share info is still there (it's not a perfect method,
1773 static void _wapi_handle_check_share_by_pid (struct _WapiFileShare *share_info)
1775 #if defined(__native_client__)
1776 g_assert_not_reached ();
1778 if (kill (share_info->opened_by_pid, 0) == -1 &&
1781 /* It's gone completely (or there's a new process
1782 * owned by someone else) so mark this share info as
1785 DEBUG ("%s: Didn't find it, destroying entry", __func__);
1787 _wapi_free_share_info (share_info);
1793 /* Scan /proc/<pids>/fd/ for open file descriptors to the file in
1794 * question. If there are none, reset the share info.
1796 * This implementation is Linux-specific; legacy systems will have to
1797 * implement their own ways of finding out if a particular file is
1798 * open by a process.
1800 void _wapi_handle_check_share (struct _WapiFileShare *share_info, int fd)
1802 gboolean found = FALSE, proc_fds = FALSE;
1803 pid_t self = _wapi_getpid ();
1807 /* Prevents entries from expiring under us if we remove this
1810 thr_ret = _wapi_handle_lock_shared_handles ();
1811 g_assert (thr_ret == 0);
1813 /* Prevent new entries racing with us */
1814 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_FILESHARE);
1815 g_assert (thr_ret == 0);
1817 /* If there is no /proc, there's nothing more we can do here */
1818 if (access ("/proc", F_OK) == -1) {
1819 _wapi_handle_check_share_by_pid (share_info);
1823 /* If there's another handle that thinks it owns this fd, then even
1824 * if the fd has been closed behind our back consider it still owned.
1825 * See bugs 75764 and 75891
1827 for (i = 0; i < _wapi_fd_reserve; i++) {
1828 if (_wapi_private_handles [SLOT_INDEX (i)]) {
1829 struct _WapiHandleUnshared *handle = &_WAPI_PRIVATE_HANDLES(i);
1832 handle->type == WAPI_HANDLE_FILE) {
1833 struct _WapiHandle_file *file_handle = &handle->u.file;
1835 if (file_handle->share_info == share_info) {
1836 DEBUG ("%s: handle 0x%x has this file open!",
1845 for (i = 0; i < _WAPI_HANDLE_INITIAL_COUNT; i++) {
1846 struct _WapiHandleShared *shared;
1847 struct _WapiHandle_process *process_handle;
1849 shared = &_wapi_shared_layout->handles[i];
1851 if (shared->type == WAPI_HANDLE_PROCESS) {
1853 struct dirent *fd_entry;
1854 char subdir[_POSIX_PATH_MAX];
1856 process_handle = &shared->u.process;
1857 pid = process_handle->id;
1859 /* Look in /proc/<pid>/fd/ but ignore
1860 * /proc/<our pid>/fd/<fd>, as we have the
1863 g_snprintf (subdir, _POSIX_PATH_MAX, "/proc/%d/fd",
1866 fd_dir = opendir (subdir);
1867 if (fd_dir == NULL) {
1871 DEBUG ("%s: Looking in %s", __func__, subdir);
1875 while ((fd_entry = readdir (fd_dir)) != NULL) {
1876 char path[_POSIX_PATH_MAX];
1877 struct stat link_stat;
1879 if (!strcmp (fd_entry->d_name, ".") ||
1880 !strcmp (fd_entry->d_name, "..") ||
1882 fd == atoi (fd_entry->d_name))) {
1886 g_snprintf (path, _POSIX_PATH_MAX,
1887 "/proc/%d/fd/%s", pid,
1890 stat (path, &link_stat);
1891 if (link_stat.st_dev == share_info->device &&
1892 link_stat.st_ino == share_info->inode) {
1893 DEBUG ("%s: Found it at %s",
1904 if (proc_fds == FALSE) {
1905 _wapi_handle_check_share_by_pid (share_info);
1906 } else if (found == FALSE) {
1907 /* Blank out this entry, as it is stale */
1908 DEBUG ("%s: Didn't find it, destroying entry", __func__);
1910 _wapi_free_share_info (share_info);
1914 thr_ret = _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_FILESHARE);
1916 _wapi_handle_unlock_shared_handles ();
1920 // Other implementations (non-Linux)
1922 void _wapi_handle_check_share (struct _WapiFileShare *share_info, int fd)
1926 /* Prevents entries from expiring under us if we remove this
1928 thr_ret = _wapi_handle_lock_shared_handles ();
1929 g_assert (thr_ret == 0);
1931 /* Prevent new entries racing with us */
1932 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_FILESHARE);
1933 g_assert (thr_ret == 0);
1935 _wapi_handle_check_share_by_pid (share_info);
1937 thr_ret = _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_FILESHARE);
1938 _wapi_handle_unlock_shared_handles ();
1942 void _wapi_handle_dump (void)
1944 struct _WapiHandleUnshared *handle_data;
1948 thr_ret = mono_mutex_lock (&scan_mutex);
1949 g_assert (thr_ret == 0);
1951 for(i = SLOT_INDEX (0); i < _wapi_private_handle_slot_count; i++) {
1952 if (_wapi_private_handles [i]) {
1953 for (k = SLOT_OFFSET (0); k < _WAPI_HANDLE_INITIAL_COUNT; k++) {
1954 handle_data = &_wapi_private_handles [i][k];
1956 if (handle_data->type == WAPI_HANDLE_UNUSED) {
1960 g_print ("%3x [%7s] %s %d ",
1961 i * _WAPI_HANDLE_INITIAL_COUNT + k,
1962 _wapi_handle_typename[handle_data->type],
1963 handle_data->signalled?"Sg":"Un",
1965 handle_details[handle_data->type](&handle_data->u);
1971 thr_ret = mono_mutex_unlock (&scan_mutex);
1972 g_assert (thr_ret == 0);
1975 static void _wapi_shared_details (gpointer handle_info)
1977 struct _WapiHandle_shared_ref *shared = (struct _WapiHandle_shared_ref *)handle_info;
1979 g_print ("offset: 0x%x", shared->offset);
1982 void _wapi_handle_update_refs (void)
1986 guint32 now = (guint32)(time (NULL) & 0xFFFFFFFF);
1988 thr_ret = _wapi_handle_lock_shared_handles ();
1989 g_assert (thr_ret == 0);
1991 /* Prevent file share entries racing with us */
1992 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_FILESHARE);
1993 g_assert(thr_ret == 0);
1995 thr_ret = mono_mutex_lock (&scan_mutex);
1997 for(i = SLOT_INDEX (0); i < _wapi_private_handle_slot_count; i++) {
1998 if (_wapi_private_handles [i]) {
1999 for (k = SLOT_OFFSET (0); k < _WAPI_HANDLE_INITIAL_COUNT; k++) {
2000 struct _WapiHandleUnshared *handle = &_wapi_private_handles [i][k];
2002 if (_WAPI_SHARED_HANDLE(handle->type)) {
2003 struct _WapiHandleShared *shared_data;
2005 DEBUG ("%s: (%d) handle 0x%x is SHARED (%s)", __func__, _wapi_getpid (), i * _WAPI_HANDLE_INITIAL_COUNT + k, _wapi_handle_typename[handle->type]);
2007 shared_data = &_wapi_shared_layout->handles[handle->u.shared.offset];
2009 DEBUG ("%s: (%d) Updating timestamp of handle 0x%x", __func__, _wapi_getpid (), handle->u.shared.offset);
2011 InterlockedExchange ((gint32 *)&shared_data->timestamp, now);
2012 } else if (handle->type == WAPI_HANDLE_FILE) {
2013 struct _WapiHandle_file *file_handle = &handle->u.file;
2015 DEBUG ("%s: (%d) handle 0x%x is FILE", __func__, _wapi_getpid (), i * _WAPI_HANDLE_INITIAL_COUNT + k);
2017 g_assert (file_handle->share_info != NULL);
2019 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));
2021 InterlockedExchange ((gint32 *)&file_handle->share_info->timestamp, now);
2027 thr_ret = mono_mutex_unlock (&scan_mutex);
2028 g_assert (thr_ret == 0);
2030 thr_ret = _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_FILESHARE);
2032 _wapi_handle_unlock_shared_handles ();