2005-06-21 Dick Porter <dick@ximian.com>
[mono.git] / mono / io-layer / mutexes.c
1 /*
2  * mutexes.c:  Mutex handles
3  *
4  * Author:
5  *      Dick Porter (dick@ximian.com)
6  *
7  * (C) 2002 Ximian, Inc.
8  */
9
10 #include <config.h>
11 #include <glib.h>
12 #include <pthread.h>
13 #include <string.h>
14 #include <unistd.h>
15
16 #include <mono/io-layer/wapi.h>
17 #include <mono/io-layer/wapi-private.h>
18 #include <mono/io-layer/misc-private.h>
19 #include <mono/io-layer/handles-private.h>
20 #include <mono/io-layer/mono-mutex.h>
21 #include <mono/io-layer/mutex-private.h>
22
23 #undef DEBUG
24
25 static void mutex_signal(gpointer handle);
26 static gboolean mutex_own (gpointer handle);
27 static gboolean mutex_is_owned (gpointer handle);
28
29 static void namedmutex_signal (gpointer handle);
30 static gboolean namedmutex_own (gpointer handle);
31 static gboolean namedmutex_is_owned (gpointer handle);
32
33 struct _WapiHandleOps _wapi_mutex_ops = {
34         NULL,                   /* close */
35         mutex_signal,           /* signal */
36         mutex_own,              /* own */
37         mutex_is_owned,         /* is_owned */
38 };
39
40 void _wapi_mutex_details (gpointer handle_info)
41 {
42         struct _WapiHandle_mutex *mut = (struct _WapiHandle_mutex *)handle_info;
43         
44 #ifdef PTHREAD_POINTER_ID
45         g_print ("own: %5d:%5p, count: %5u", mut->pid, mut->tid,
46                  mut->recursion);
47 #else
48         g_print ("own: %5d:%5ld, count: %5u", mut->pid, mut->tid,
49                  mut->recursion);
50 #endif
51 }
52
53 struct _WapiHandleOps _wapi_namedmutex_ops = {
54         NULL,                   /* close */
55         namedmutex_signal,      /* signal */
56         namedmutex_own,         /* own */
57         namedmutex_is_owned,    /* is_owned */
58 };
59
60 static gboolean mutex_release (gpointer handle);
61 static gboolean namedmutex_release (gpointer handle);
62
63 static struct 
64 {
65         gboolean (*release)(gpointer handle);
66 } mutex_ops[WAPI_HANDLE_COUNT] = {
67         {NULL},
68         {NULL},
69         {NULL},
70         {NULL},
71         {NULL},
72         {mutex_release},
73         {NULL},
74         {NULL},
75         {NULL},
76         {NULL},
77         {NULL},
78         {namedmutex_release},
79 };
80
81 static mono_once_t mutex_ops_once=MONO_ONCE_INIT;
82
83 static void mutex_ops_init (void)
84 {
85         _wapi_handle_register_capabilities (WAPI_HANDLE_MUTEX,
86                                             WAPI_HANDLE_CAP_WAIT |
87                                             WAPI_HANDLE_CAP_SIGNAL |
88                                             WAPI_HANDLE_CAP_OWN);
89         _wapi_handle_register_capabilities (WAPI_HANDLE_NAMEDMUTEX,
90                                             WAPI_HANDLE_CAP_WAIT |
91                                             WAPI_HANDLE_CAP_SIGNAL |
92                                             WAPI_HANDLE_CAP_OWN);
93 }
94
95 static void mutex_signal(gpointer handle)
96 {
97         ReleaseMutex(handle);
98 }
99
100 static gboolean mutex_own (gpointer handle)
101 {
102         struct _WapiHandle_mutex *mutex_handle;
103         gboolean ok;
104         
105         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_MUTEX,
106                                   (gpointer *)&mutex_handle);
107         if (ok == FALSE) {
108                 g_warning ("%s: error looking up mutex handle %p", __func__,
109                            handle);
110                 return(FALSE);
111         }
112
113         _wapi_thread_own_mutex (pthread_self (), handle);
114         
115 #ifdef DEBUG
116         g_message("%s: owning mutex handle %p", __func__, handle);
117 #endif
118
119         _wapi_handle_set_signal_state (handle, FALSE, FALSE);
120         
121         mutex_handle->pid = getpid ();
122         mutex_handle->tid = pthread_self ();
123         mutex_handle->recursion++;
124
125 #ifdef DEBUG
126         g_message ("%s: mutex handle %p locked %d times by %d:%ld", __func__,
127                    handle, mutex_handle->recursion, mutex_handle->pid,
128                    mutex_handle->tid);
129 #endif
130
131         return(TRUE);
132 }
133
134 static gboolean mutex_is_owned (gpointer handle)
135 {
136         struct _WapiHandle_mutex *mutex_handle;
137         gboolean ok;
138         
139         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_MUTEX,
140                                 (gpointer *)&mutex_handle);
141         if(ok==FALSE) {
142                 g_warning ("%s: error looking up mutex handle %p", __func__,
143                            handle);
144                 return(FALSE);
145         }
146         
147 #ifdef DEBUG
148         g_message("%s: testing ownership mutex handle %p", __func__, handle);
149 #endif
150
151         if (mutex_handle->recursion > 0 &&
152             mutex_handle->pid == getpid () &&
153             mutex_handle->tid == pthread_self ()) {
154 #ifdef DEBUG
155                 g_message ("%s: mutex handle %p owned by %d:%ld", __func__,
156                            handle, getpid (), pthread_self ());
157 #endif
158
159                 return(TRUE);
160         } else {
161 #ifdef DEBUG
162                 g_message ("%s: mutex handle %p not owned by %d:%ld, but locked %d times by %d:%ld", __func__, handle, getpid (), pthread_self (), mutex_handle->recursion, mutex_handle->pid, mutex_handle->tid);
163 #endif
164
165                 return(FALSE);
166         }
167 }
168
169 static void namedmutex_signal (gpointer handle)
170 {
171         ReleaseMutex(handle);
172 }
173
174 static gboolean namedmutex_own (gpointer handle)
175 {
176         struct _WapiHandleShared shared_handle;
177         struct _WapiHandle_namedmutex *namedmutex_handle;
178         gboolean ok;
179         
180 #ifdef DEBUG
181         g_message ("%s: owning named mutex handle %p", __func__, handle);
182 #endif
183         
184         ok = _wapi_copy_handle (handle, WAPI_HANDLE_NAMEDMUTEX,
185                                 &shared_handle);
186         if (ok == FALSE) {
187                 g_warning ("%s: error looking up named mutex handle %p",
188                            __func__, handle);
189                 return(FALSE);
190         }
191
192         _wapi_thread_own_mutex (pthread_self (), handle);
193
194         namedmutex_handle = &shared_handle.u.namedmutex;
195
196         namedmutex_handle->pid = getpid ();
197         namedmutex_handle->tid = pthread_self ();
198         namedmutex_handle->recursion++;
199
200         ok = _wapi_replace_handle (handle, WAPI_HANDLE_NAMEDMUTEX,
201                                    &shared_handle);
202         if (ok == FALSE) {
203                 SetLastError (ERROR_OUTOFMEMORY);
204                 return (FALSE);
205         }
206         
207         _wapi_shared_handle_set_signal_state (handle, FALSE);
208
209 #ifdef DEBUG
210         g_message ("%s: mutex handle %p locked %d times by %d:%ld", __func__,
211                    handle, namedmutex_handle->recursion,
212                    namedmutex_handle->pid, namedmutex_handle->tid);
213 #endif
214         
215         return(TRUE);
216 }
217
218 static gboolean namedmutex_is_owned (gpointer handle)
219 {
220         struct _WapiHandle_namedmutex *namedmutex_handle;
221         gboolean ok;
222         
223         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_NAMEDMUTEX,
224                                   (gpointer *)&namedmutex_handle);
225         if (ok == FALSE) {
226                 g_warning ("%s: error looking up mutex handle %p", __func__,
227                            handle);
228                 return(FALSE);
229         }
230         
231 #ifdef DEBUG
232         g_message ("%s: testing ownership mutex handle %p", __func__, handle);
233 #endif
234
235         if (namedmutex_handle->recursion > 0 &&
236             namedmutex_handle->pid == getpid () &&
237             namedmutex_handle->tid == pthread_self ()) {
238 #ifdef DEBUG
239                 g_message ("%s: mutex handle %p owned by %d:%ld", __func__,
240                            handle, getpid (), pthread_self ());
241 #endif
242
243                 return(TRUE);
244         } else {
245 #ifdef DEBUG
246                 g_message ("%s: mutex handle %p not owned by %d:%ld, but locked %d times by %d:%ld", __func__, handle, getpid (), pthread_self (), namedmutex_handle->recursion, namedmutex_handle->pid, namedmutex_handle->tid);
247 #endif
248
249                 return(FALSE);
250         }
251 }
252
253 static void mutex_abandon (gpointer handle, pid_t pid, pthread_t tid)
254 {
255         struct _WapiHandle_mutex *mutex_handle;
256         gboolean ok;
257         int thr_ret;
258         
259         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_MUTEX,
260                                   (gpointer *)&mutex_handle);
261         if (ok == FALSE) {
262                 g_warning ("%s: error looking up mutex handle %p", __func__,
263                            handle);
264                 return;
265         }
266
267         pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
268                               handle);
269         thr_ret = _wapi_handle_lock_handle (handle);
270         g_assert (thr_ret == 0);
271         
272         if (mutex_handle->pid == pid &&
273             mutex_handle->tid == tid) {
274 #ifdef DEBUG
275                 g_message ("%s: Mutex handle %p abandoned!", __func__, handle);
276 #endif
277
278                 mutex_handle->recursion = 0;
279                 mutex_handle->pid = 0;
280                 mutex_handle->tid = 0;
281                 
282                 _wapi_handle_set_signal_state (handle, TRUE, FALSE);
283         }
284
285         thr_ret = _wapi_handle_unlock_handle (handle);
286         g_assert (thr_ret == 0);
287         pthread_cleanup_pop (0);
288 }
289
290 static void namedmutex_abandon (gpointer handle, pid_t pid, pthread_t tid)
291 {
292         struct _WapiHandle_namedmutex *mutex_handle;
293         gboolean ok;
294         int thr_ret;
295         
296         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_NAMEDMUTEX,
297                                   (gpointer *)&mutex_handle);
298         if (ok == FALSE) {
299                 g_warning ("%s: error looking up named mutex handle %p",
300                            __func__, handle);
301                 return;
302         }
303
304         thr_ret = _wapi_handle_lock_shared_handles ();
305         g_assert (thr_ret == 0);
306         
307         if (mutex_handle->pid == pid &&
308             mutex_handle->tid == tid) {
309 #ifdef DEBUG
310                 g_message ("%s: Mutex handle %p abandoned!", __func__, handle);
311 #endif
312
313                 mutex_handle->recursion = 0;
314                 mutex_handle->pid = 0;
315                 mutex_handle->tid = 0;
316                 
317                 _wapi_shared_handle_set_signal_state (handle, TRUE);
318         }
319
320         _wapi_handle_unlock_shared_handles ();
321 }
322
323 /* When a thread exits, any mutexes it still holds need to be signalled */
324 void _wapi_mutex_abandon (gpointer data, pid_t pid, pthread_t tid)
325 {
326         WapiHandleType type = _wapi_handle_type (data);
327
328         if (type == WAPI_HANDLE_MUTEX) {
329                 mutex_abandon (data, pid, tid);
330         } else if (type == WAPI_HANDLE_NAMEDMUTEX) {
331                 namedmutex_abandon (data, pid, tid);
332         } else {
333                 g_assert_not_reached ();
334         }
335 }
336
337 static gpointer mutex_create (WapiSecurityAttributes *security G_GNUC_UNUSED,
338                               gboolean owned)
339 {
340         struct _WapiHandle_mutex mutex_handle = {0};
341         gpointer handle;
342         int thr_ret;
343         
344         /* Need to blow away any old errors here, because code tests
345          * for ERROR_ALREADY_EXISTS on success (!) to see if a mutex
346          * was freshly created
347          */
348         SetLastError (ERROR_SUCCESS);
349         
350 #ifdef DEBUG
351         g_message ("%s: Creating unnamed mutex", __func__);
352 #endif
353         
354         handle = _wapi_handle_new (WAPI_HANDLE_MUTEX, &mutex_handle);
355         if (handle == _WAPI_HANDLE_INVALID) {
356                 g_warning ("%s: error creating mutex handle", __func__);
357                 SetLastError (ERROR_GEN_FAILURE);
358                 return(NULL);
359         }
360
361         pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
362                               handle);
363         thr_ret = _wapi_handle_lock_handle (handle);
364         g_assert (thr_ret == 0);
365         
366         if(owned==TRUE) {
367                 mutex_own (handle);
368         } else {
369                 _wapi_handle_set_signal_state (handle, TRUE, FALSE);
370         }
371         
372 #ifdef DEBUG
373         g_message ("%s: returning mutex handle %p", __func__, handle);
374 #endif
375
376         thr_ret = _wapi_handle_unlock_handle (handle);
377         g_assert (thr_ret == 0);
378         pthread_cleanup_pop (0);
379         
380         return(handle);
381 }
382
383 static gpointer namedmutex_create (WapiSecurityAttributes *security G_GNUC_UNUSED, gboolean owned,
384                         const gunichar2 *name)
385 {
386         struct _WapiHandle_namedmutex namedmutex_handle = {{{0}}, 0};
387         gpointer handle;
388         gchar *utf8_name;
389         int thr_ret;
390         gpointer ret = NULL;
391         guint32 namelen;
392         gint32 offset;
393
394         /* w32 seems to guarantee that opening named mutexes can't
395          * race each other
396          */
397         pthread_cleanup_push ((void(*)(void *))_wapi_namespace_unlock, NULL);
398         thr_ret = _wapi_namespace_lock ();
399         g_assert (thr_ret == 0);
400
401         /* Need to blow away any old errors here, because code tests
402          * for ERROR_ALREADY_EXISTS on success (!) to see if a mutex
403          * was freshly created
404          */
405         SetLastError (ERROR_SUCCESS);
406         
407         utf8_name = g_utf16_to_utf8 (name, -1, NULL, NULL, NULL);
408         
409 #ifdef DEBUG
410         g_message ("%s: Creating named mutex [%s]", __func__, utf8_name);
411 #endif
412         
413         offset = _wapi_search_handle_namespace (WAPI_HANDLE_NAMEDMUTEX,
414                                                 utf8_name);
415         if (offset == -1) {
416                 /* The name has already been used for a different
417                  * object.
418                  */
419                 SetLastError (ERROR_INVALID_HANDLE);
420                 goto cleanup;
421         } else if (offset != 0) {
422                 /* Not an error, but this is how the caller is
423                  * informed that the mutex wasn't freshly created
424                  */
425                 SetLastError (ERROR_ALREADY_EXISTS);
426         }
427         /* Fall through to create the mutex handle. */
428         
429         if (strlen (utf8_name) < MAX_PATH) {
430                 namelen = strlen (utf8_name);
431         } else {
432                 namelen = MAX_PATH;
433         }
434         
435         memcpy (&namedmutex_handle.sharedns.name, utf8_name, namelen);
436
437         if (offset == 0) {
438                 /* A new named mutex, so create both the private and
439                  * shared parts
440                  */
441                 handle = _wapi_handle_new (WAPI_HANDLE_NAMEDMUTEX,
442                                            &namedmutex_handle);
443         } else {
444                 /* A new reference to an existing named mutex, so just
445                  * create the private part
446                  */
447                 handle = _wapi_handle_new_from_offset (WAPI_HANDLE_NAMEDMUTEX,
448                                                        offset);
449         }
450         
451         if (handle == _WAPI_HANDLE_INVALID) {
452                 g_warning ("%s: error creating mutex handle", __func__);
453                 SetLastError (ERROR_GEN_FAILURE);
454                 goto cleanup;
455         }
456         ret = handle;
457
458         if (offset == 0) {
459                 /* Set the initial state, as this is a completely new
460                  * handle
461                  */
462                 thr_ret = _wapi_handle_lock_shared_handles ();
463                 g_assert (thr_ret == 0);
464         
465                 if (owned == TRUE) {
466                         namedmutex_own (handle);
467                 } else {
468                         _wapi_shared_handle_set_signal_state (handle, TRUE);
469                 }
470
471                 _wapi_handle_unlock_shared_handles ();
472         }
473         
474 #ifdef DEBUG
475         g_message ("%s: returning mutex handle %p", __func__, handle);
476 #endif
477
478 cleanup:
479         g_free (utf8_name);
480         /* Releases the timestamp */
481         pthread_cleanup_pop (1);
482         
483         return(ret);
484 }
485
486 /**
487  * CreateMutex:
488  * @security: Ignored for now.
489  * @owned: If %TRUE, the mutex is created with the calling thread
490  * already owning the mutex.
491  * @name:Pointer to a string specifying the name of this mutex, or
492  * %NULL.
493  *
494  * Creates a new mutex handle.  A mutex is signalled when no thread
495  * owns it.  A thread acquires ownership of the mutex by waiting for
496  * it with WaitForSingleObject() or WaitForMultipleObjects().  A
497  * thread relinquishes ownership with ReleaseMutex().
498  *
499  * A thread that owns a mutex can specify the same mutex in repeated
500  * wait function calls without blocking.  The thread must call
501  * ReleaseMutex() an equal number of times to release the mutex.
502  *
503  * Return value: A new handle, or %NULL on error.
504  */
505 gpointer CreateMutex(WapiSecurityAttributes *security G_GNUC_UNUSED, gboolean owned,
506                         const gunichar2 *name)
507 {
508         mono_once (&mutex_ops_once, mutex_ops_init);
509
510         if (name == NULL) {
511                 return(mutex_create (security, owned));
512         } else {
513                 return(namedmutex_create (security, owned, name));
514         }
515 }
516
517 static gboolean mutex_release (gpointer handle)
518 {
519         struct _WapiHandle_mutex *mutex_handle;
520         gboolean ok;
521         pthread_t tid=pthread_self();
522         pid_t pid=getpid ();
523         int thr_ret;
524         gboolean ret = FALSE;
525         
526         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_MUTEX,
527                                   (gpointer *)&mutex_handle);
528         if (ok == FALSE) {
529                 g_warning ("%s: error looking up mutex handle %p", __func__,
530                            handle);
531                 return(FALSE);
532         }
533
534         pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
535                               handle);
536         thr_ret = _wapi_handle_lock_handle (handle);
537         g_assert (thr_ret == 0);
538         
539 #ifdef DEBUG
540         g_message("%s: Releasing mutex handle %p", __func__, handle);
541 #endif
542
543         if(mutex_handle->tid!=tid || mutex_handle->pid!=pid) {
544 #ifdef DEBUG
545                 g_message("%s: We don't own mutex handle %p (owned by %d:%ld, me %d:%ld)", __func__, handle, mutex_handle->pid, mutex_handle->tid, pid, tid);
546 #endif
547
548                 goto cleanup;
549         }
550         ret = TRUE;
551         
552         /* OK, we own this mutex */
553         mutex_handle->recursion--;
554         
555         if(mutex_handle->recursion==0) {
556                 _wapi_thread_disown_mutex (tid, handle);
557
558 #ifdef DEBUG
559                 g_message("%s: Unlocking mutex handle %p", __func__, handle);
560 #endif
561
562                 mutex_handle->pid=0;
563                 mutex_handle->tid=0;
564                 _wapi_handle_set_signal_state (handle, TRUE, FALSE);
565         }
566
567 cleanup:
568         thr_ret = _wapi_handle_unlock_handle (handle);
569         g_assert (thr_ret == 0);
570         pthread_cleanup_pop (0);
571         
572         return(ret);
573 }
574
575 static gboolean namedmutex_release (gpointer handle)
576 {
577         struct _WapiHandle_namedmutex *mutex_handle;
578         gboolean ok;
579         pthread_t tid=pthread_self();
580         pid_t pid=getpid ();
581         int thr_ret;
582         gboolean ret = FALSE;
583         
584         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_NAMEDMUTEX,
585                                 (gpointer *)&mutex_handle);
586         if(ok==FALSE) {
587                 g_warning ("%s: error looking up named mutex handle %p",
588                            __func__, handle);
589                 return(FALSE);
590         }
591
592         thr_ret = _wapi_handle_lock_shared_handles ();
593         g_assert (thr_ret == 0);
594         
595 #ifdef DEBUG
596         g_message("%s: Releasing mutex handle %p", __func__, handle);
597 #endif
598
599         if(mutex_handle->tid!=tid || mutex_handle->pid!=pid) {
600 #ifdef DEBUG
601                 g_message("%s: We don't own mutex handle %p (owned by %d:%ld, me %d:%ld)", __func__, handle, mutex_handle->pid, mutex_handle->tid, pid, tid);
602 #endif
603
604                 goto cleanup;
605         }
606         ret = TRUE;
607         
608         /* OK, we own this mutex */
609         mutex_handle->recursion--;
610         
611         if(mutex_handle->recursion==0) {
612                 _wapi_thread_disown_mutex (tid, handle);
613
614 #ifdef DEBUG
615                 g_message("%s: Unlocking mutex handle %p", __func__, handle);
616 #endif
617
618                 mutex_handle->pid=0;
619                 mutex_handle->tid=0;
620                 _wapi_shared_handle_set_signal_state (handle, TRUE);
621         }
622
623 cleanup:
624         _wapi_handle_unlock_shared_handles ();
625         
626         return(ret);
627 }
628
629 /**
630  * ReleaseMutex:
631  * @handle: The mutex handle.
632  *
633  * Releases ownership if the mutex handle @handle.
634  *
635  * Return value: %TRUE on success, %FALSE otherwise.  This function
636  * fails if the calling thread does not own the mutex @handle.
637  */
638 gboolean ReleaseMutex(gpointer handle)
639 {
640         WapiHandleType type;
641
642         if (handle == NULL) {
643                 SetLastError (ERROR_INVALID_HANDLE);
644                 return(FALSE);
645         }
646         
647         type = _wapi_handle_type (handle);
648         
649         if (mutex_ops[type].release == NULL) {
650                 SetLastError (ERROR_INVALID_HANDLE);
651                 return(FALSE);
652         }
653         
654         return(mutex_ops[type].release (handle));
655 }