Remove the use of G_GNUC_PRETTY_FUNCTION with the proper pattern which
[mono.git] / mono / metadata / monitor.c
1 /*
2  * monitor.c:  Monitor locking functions
3  *
4  * Author:
5  *      Dick Porter (dick@ximian.com)
6  *
7  * Copyright 2003 Ximian, Inc (http://www.ximian.com)
8  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
9  */
10
11 #include <config.h>
12 #include <glib.h>
13 #include <string.h>
14
15 #include <mono/metadata/monitor.h>
16 #include <mono/metadata/threads-types.h>
17 #include <mono/metadata/exception.h>
18 #include <mono/metadata/threads.h>
19 #include <mono/io-layer/io-layer.h>
20 #include <mono/metadata/object-internals.h>
21 #include <mono/metadata/class-internals.h>
22 #include <mono/metadata/gc-internal.h>
23 #include <mono/metadata/method-builder.h>
24 #include <mono/metadata/debug-helpers.h>
25 #include <mono/metadata/tabledefs.h>
26 #include <mono/metadata/marshal.h>
27 #include <mono/metadata/profiler-private.h>
28 #include <mono/utils/mono-time.h>
29
30 /*
31  * Pull the list of opcodes
32  */
33 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
34         a = i,
35
36 enum {
37 #include "mono/cil/opcode.def"
38         LAST = 0xff
39 };
40 #undef OPDEF
41
42 /*#define LOCK_DEBUG(a) do { a; } while (0)*/
43 #define LOCK_DEBUG(a)
44
45 /*
46  * The monitor implementation here is based on
47  * http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf and
48  * http://www.research.ibm.com/people/d/dfb/papers/Bacon98Thin.ps
49  *
50  * The Dice paper describes a technique for saving lock record space
51  * by returning records to a free list when they become unused.  That
52  * sounds like unnecessary complexity to me, though if it becomes
53  * clear that unused lock records are taking up lots of space or we
54  * need to shave more time off by avoiding a malloc then we can always
55  * implement the free list idea later.  The timeout parameter to
56  * try_enter voids some of the assumptions about the reference count
57  * field in Dice's implementation too.  In his version, the thread
58  * attempting to lock a contended object will block until it succeeds,
59  * so the reference count will never be decremented while an object is
60  * locked.
61  *
62  * Bacon's thin locks have a fast path that doesn't need a lock record
63  * for the common case of locking an unlocked or shallow-nested
64  * object, but the technique relies on encoding the thread ID in 15
65  * bits (to avoid too much per-object space overhead.)  Unfortunately
66  * I don't think it's possible to reliably encode a pthread_t into 15
67  * bits. (The JVM implementation used seems to have a 15-bit
68  * per-thread identifier available.)
69  *
70  * This implementation then combines Dice's basic lock model with
71  * Bacon's simplification of keeping a lock record for the lifetime of
72  * an object.
73  */
74
75 struct _MonoThreadsSync
76 {
77         gsize owner;                    /* thread ID */
78         guint32 nest;
79 #ifdef HAVE_MOVING_COLLECTOR
80         gint32 hash_code;
81 #endif
82         volatile gint32 entry_count;
83         HANDLE entry_sem;
84         GSList *wait_list;
85         void *data;
86 };
87
88 typedef struct _MonitorArray MonitorArray;
89
90 struct _MonitorArray {
91         MonitorArray *next;
92         int num_monitors;
93         MonoThreadsSync monitors [MONO_ZERO_LEN_ARRAY];
94 };
95
96 #define mono_monitor_allocator_lock() EnterCriticalSection (&monitor_mutex)
97 #define mono_monitor_allocator_unlock() LeaveCriticalSection (&monitor_mutex)
98 static CRITICAL_SECTION monitor_mutex;
99 static MonoThreadsSync *monitor_freelist;
100 static MonitorArray *monitor_allocated;
101 static int array_size = 16;
102
103 #ifdef HAVE_KW_THREAD
104 static __thread gsize tls_pthread_self MONO_TLS_FAST;
105 #endif
106
107 #ifndef PLATFORM_WIN32
108 #ifdef HAVE_KW_THREAD
109 #define GetCurrentThreadId() tls_pthread_self
110 #else
111 /* 
112  * The usual problem: we can't replace GetCurrentThreadId () with a macro because
113  * it is in a public header.
114  */
115 #define GetCurrentThreadId() ((gsize)pthread_self ())
116 #endif
117 #endif
118
119 void
120 mono_monitor_init (void)
121 {
122         InitializeCriticalSection (&monitor_mutex);
123 }
124  
125 void
126 mono_monitor_cleanup (void)
127 {
128         /*DeleteCriticalSection (&monitor_mutex);*/
129 }
130
131 /*
132  * mono_monitor_init_tls:
133  *
134  *   Setup TLS variables used by the monitor code for the current thread.
135  */
136 void
137 mono_monitor_init_tls (void)
138 {
139 #if !defined(PLATFORM_WIN32) && defined(HAVE_KW_THREAD)
140         tls_pthread_self = pthread_self ();
141 #endif
142 }
143
144 static int
145 monitor_is_on_freelist (MonoThreadsSync *mon)
146 {
147         MonitorArray *marray;
148         for (marray = monitor_allocated; marray; marray = marray->next) {
149                 if (mon >= marray->monitors && mon < &marray->monitors [marray->num_monitors])
150                         return TRUE;
151         }
152         return FALSE;
153 }
154
155 /**
156  * mono_locks_dump:
157  * @include_untaken:
158  *
159  * Print a report on stdout of the managed locks currently held by
160  * threads. If @include_untaken is specified, list also inflated locks
161  * which are unheld.
162  * This is supposed to be used in debuggers like gdb.
163  */
164 void
165 mono_locks_dump (gboolean include_untaken)
166 {
167         int i;
168         int used = 0, on_freelist = 0, to_recycle = 0, total = 0, num_arrays = 0;
169         MonoThreadsSync *mon;
170         MonitorArray *marray;
171         for (mon = monitor_freelist; mon; mon = mon->data)
172                 on_freelist++;
173         for (marray = monitor_allocated; marray; marray = marray->next) {
174                 total += marray->num_monitors;
175                 num_arrays++;
176                 for (i = 0; i < marray->num_monitors; ++i) {
177                         mon = &marray->monitors [i];
178                         if (mon->data == NULL) {
179                                 if (i < marray->num_monitors - 1)
180                                         to_recycle++;
181                         } else {
182                                 if (!monitor_is_on_freelist (mon->data)) {
183                                         MonoObject *holder = mono_gc_weak_link_get (&mon->data);
184                                         if (mon->owner) {
185                                                 g_print ("Lock %p in object %p held by thread %p, nest level: %d\n",
186                                                         mon, holder, (void*)mon->owner, mon->nest);
187                                                 if (mon->entry_sem)
188                                                         g_print ("\tWaiting on semaphore %p: %d\n", mon->entry_sem, mon->entry_count);
189                                         } else if (include_untaken) {
190                                                 g_print ("Lock %p in object %p untaken\n", mon, holder);
191                                         }
192                                         used++;
193                                 }
194                         }
195                 }
196         }
197         g_print ("Total locks (in %d array(s)): %d, used: %d, on freelist: %d, to recycle: %d\n",
198                 num_arrays, total, used, on_freelist, to_recycle);
199 }
200
201 /* LOCKING: this is called with monitor_mutex held */
202 static void 
203 mon_finalize (MonoThreadsSync *mon)
204 {
205         LOCK_DEBUG (g_message ("%s: Finalizing sync %p", __func__, mon));
206
207         if (mon->entry_sem != NULL) {
208                 CloseHandle (mon->entry_sem);
209                 mon->entry_sem = NULL;
210         }
211         /* If this isn't empty then something is seriously broken - it
212          * means a thread is still waiting on the object that owned
213          * this lock, but the object has been finalized.
214          */
215         g_assert (mon->wait_list == NULL);
216
217         mon->entry_count = 0;
218         /* owner and nest are set in mon_new, no need to zero them out */
219
220         mon->data = monitor_freelist;
221         monitor_freelist = mon;
222         mono_perfcounters->gc_sync_blocks--;
223 }
224
225 /* LOCKING: this is called with monitor_mutex held */
226 static MonoThreadsSync *
227 mon_new (gsize id)
228 {
229         MonoThreadsSync *new;
230
231         if (!monitor_freelist) {
232                 MonitorArray *marray;
233                 int i;
234                 /* see if any sync block has been collected */
235                 new = NULL;
236                 for (marray = monitor_allocated; marray; marray = marray->next) {
237                         for (i = 0; i < marray->num_monitors; ++i) {
238                                 if (marray->monitors [i].data == NULL) {
239                                         new = &marray->monitors [i];
240                                         new->data = monitor_freelist;
241                                         monitor_freelist = new;
242                                 }
243                         }
244                         /* small perf tweak to avoid scanning all the blocks */
245                         if (new)
246                                 break;
247                 }
248                 /* need to allocate a new array of monitors */
249                 if (!monitor_freelist) {
250                         MonitorArray *last;
251                         LOCK_DEBUG (g_message ("%s: allocating more monitors: %d", __func__, array_size));
252                         marray = g_malloc0 (sizeof (MonoArray) + array_size * sizeof (MonoThreadsSync));
253                         marray->num_monitors = array_size;
254                         array_size *= 2;
255                         /* link into the freelist */
256                         for (i = 0; i < marray->num_monitors - 1; ++i) {
257                                 marray->monitors [i].data = &marray->monitors [i + 1];
258                         }
259                         marray->monitors [i].data = NULL; /* the last one */
260                         monitor_freelist = &marray->monitors [0];
261                         /* we happend the marray instead of prepending so that
262                          * the collecting loop above will need to scan smaller arrays first
263                          */
264                         if (!monitor_allocated) {
265                                 monitor_allocated = marray;
266                         } else {
267                                 last = monitor_allocated;
268                                 while (last->next)
269                                         last = last->next;
270                                 last->next = marray;
271                         }
272                 }
273         }
274
275         new = monitor_freelist;
276         monitor_freelist = new->data;
277
278         new->owner = id;
279         new->nest = 1;
280         
281         mono_perfcounters->gc_sync_blocks++;
282         return new;
283 }
284
285 /*
286  * Format of the lock word:
287  * thinhash | fathash | data
288  *
289  * thinhash is the lower bit: if set data is the shifted hashcode of the object.
290  * fathash is another bit: if set the hash code is stored in the MonoThreadsSync
291  *   struct pointed to by data
292  * if neither bit is set and data is non-NULL, data is a MonoThreadsSync
293  */
294 typedef union {
295         gsize lock_word;
296         MonoThreadsSync *sync;
297 } LockWord;
298
299 enum {
300         LOCK_WORD_THIN_HASH = 1,
301         LOCK_WORD_FAT_HASH = 1 << 1,
302         LOCK_WORD_BITS_MASK = 0x3,
303         LOCK_WORD_HASH_SHIFT = 2
304 };
305
306 #define MONO_OBJECT_ALIGNMENT_SHIFT     3
307
308 /*
309  * mono_object_hash:
310  * @obj: an object
311  *
312  * Calculate a hash code for @obj that is constant while @obj is alive.
313  */
314 int
315 mono_object_hash (MonoObject* obj)
316 {
317 #ifdef HAVE_MOVING_COLLECTOR
318         LockWord lw;
319         unsigned int hash;
320         if (!obj)
321                 return 0;
322         lw.sync = obj->synchronisation;
323         if (lw.lock_word & LOCK_WORD_THIN_HASH) {
324                 /*g_print ("fast thin hash %d for obj %p store\n", (unsigned int)lw.lock_word >> LOCK_WORD_HASH_SHIFT, obj);*/
325                 return (unsigned int)lw.lock_word >> LOCK_WORD_HASH_SHIFT;
326         }
327         if (lw.lock_word & LOCK_WORD_FAT_HASH) {
328                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
329                 /*g_print ("fast fat hash %d for obj %p store\n", lw.sync->hash_code, obj);*/
330                 return lw.sync->hash_code;
331         }
332         /*
333          * while we are inside this function, the GC will keep this object pinned,
334          * since we are in the unmanaged stack. Thanks to this and to the hash
335          * function that depends only on the address, we can ignore the races if
336          * another thread computes the hash at the same time, because it'll end up
337          * with the same value.
338          */
339         hash = (GPOINTER_TO_UINT (obj) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
340         /* clear the top bits as they can be discarded */
341         hash &= ~(LOCK_WORD_BITS_MASK << 30);
342         /* no hash flags were set, so it must be a MonoThreadsSync pointer if not NULL */
343         if (lw.sync) {
344                 lw.sync->hash_code = hash;
345                 /*g_print ("storing hash code %d for obj %p in sync %p\n", hash, obj, lw.sync);*/
346                 lw.lock_word |= LOCK_WORD_FAT_HASH;
347                 /* this is safe since we don't deflate locks */
348                 obj->synchronisation = lw.sync;
349         } else {
350                 /*g_print ("storing thin hash code %d for obj %p\n", hash, obj);*/
351                 lw.lock_word = LOCK_WORD_THIN_HASH | (hash << LOCK_WORD_HASH_SHIFT);
352                 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, NULL) == NULL)
353                         return hash;
354                 /*g_print ("failed store\n");*/
355                 /* someone set the hash flag or someone inflated the object */
356                 lw.sync = obj->synchronisation;
357                 if (lw.lock_word & LOCK_WORD_THIN_HASH)
358                         return hash;
359                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
360                 lw.sync->hash_code = hash;
361                 lw.lock_word |= LOCK_WORD_FAT_HASH;
362                 /* this is safe since we don't deflate locks */
363                 obj->synchronisation = lw.sync;
364         }
365         return hash;
366 #else
367 /*
368  * Wang's address-based hash function:
369  *   http://www.concentric.net/~Ttwang/tech/addrhash.htm
370  */
371         return (GPOINTER_TO_UINT (obj) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
372 #endif
373 }
374
375 /* If allow_interruption==TRUE, the method will be interrumped if abort or suspend
376  * is requested. In this case it returns -1.
377  */ 
378 static inline gint32 
379 mono_monitor_try_enter_internal (MonoObject *obj, guint32 ms, gboolean allow_interruption)
380 {
381         MonoThreadsSync *mon;
382         gsize id = GetCurrentThreadId ();
383         HANDLE sem;
384         guint32 then = 0, now, delta;
385         guint32 waitms;
386         guint32 ret;
387         MonoThread *thread;
388
389         LOCK_DEBUG (g_message("%s: (%d) Trying to lock object %p (%d ms)", __func__, id, obj, ms));
390
391         if (G_UNLIKELY (!obj)) {
392                 mono_raise_exception (mono_get_exception_argument_null ("obj"));
393                 return FALSE;
394         }
395
396 retry:
397         mon = obj->synchronisation;
398
399         /* If the object has never been locked... */
400         if (G_UNLIKELY (mon == NULL)) {
401                 mono_monitor_allocator_lock ();
402                 mon = mon_new (id);
403                 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, mon, NULL) == NULL) {
404                         mono_gc_weak_link_add (&mon->data, obj, FALSE);
405                         mono_monitor_allocator_unlock ();
406                         /* Successfully locked */
407                         return 1;
408                 } else {
409 #ifdef HAVE_MOVING_COLLECTOR
410                         LockWord lw;
411                         lw.sync = obj->synchronisation;
412                         if (lw.lock_word & LOCK_WORD_THIN_HASH) {
413                                 MonoThreadsSync *oldlw = lw.sync;
414                                 /* move the already calculated hash */
415                                 mon->hash_code = lw.lock_word >> LOCK_WORD_HASH_SHIFT;
416                                 lw.sync = mon;
417                                 lw.lock_word |= LOCK_WORD_FAT_HASH;
418                                 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, oldlw) == oldlw) {
419                                         mono_gc_weak_link_add (&mon->data, obj, FALSE);
420                                         mono_monitor_allocator_unlock ();
421                                         /* Successfully locked */
422                                         return 1;
423                                 } else {
424                                         mon_finalize (mon);
425                                         mono_monitor_allocator_unlock ();
426                                         goto retry;
427                                 }
428                         } else if (lw.lock_word & LOCK_WORD_FAT_HASH) {
429                                 mon_finalize (mon);
430                                 mono_monitor_allocator_unlock ();
431                                 /* get the old lock without the fat hash bit */
432                                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
433                                 mon = lw.sync;
434                         } else {
435                                 mon_finalize (mon);
436                                 mono_monitor_allocator_unlock ();
437                                 mon = obj->synchronisation;
438                         }
439 #else
440                         mon_finalize (mon);
441                         mono_monitor_allocator_unlock ();
442                         mon = obj->synchronisation;
443 #endif
444                 }
445         } else {
446 #ifdef HAVE_MOVING_COLLECTOR
447                 LockWord lw;
448                 lw.sync = mon;
449                 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
450                         MonoThreadsSync *oldlw = lw.sync;
451                         mono_monitor_allocator_lock ();
452                         mon = mon_new (id);
453                         /* move the already calculated hash */
454                         mon->hash_code = lw.lock_word >> LOCK_WORD_HASH_SHIFT;
455                         lw.sync = mon;
456                         lw.lock_word |= LOCK_WORD_FAT_HASH;
457                         if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, oldlw) == oldlw) {
458                                 mono_gc_weak_link_add (&mon->data, obj, TRUE);
459                                 mono_monitor_allocator_unlock ();
460                                 /* Successfully locked */
461                                 return 1;
462                         } else {
463                                 mon_finalize (mon);
464                                 mono_monitor_allocator_unlock ();
465                                 goto retry;
466                         }
467                 }
468 #endif
469         }
470
471 #ifdef HAVE_MOVING_COLLECTOR
472         {
473                 LockWord lw;
474                 lw.sync = mon;
475                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
476                 mon = lw.sync;
477         }
478 #endif
479
480         /* If the object has previously been locked but isn't now... */
481
482         /* This case differs from Dice's case 3 because we don't
483          * deflate locks or cache unused lock records
484          */
485         if (G_LIKELY (mon->owner == 0)) {
486                 /* Try to install our ID in the owner field, nest
487                  * should have been left at 1 by the previous unlock
488                  * operation
489                  */
490                 if (G_LIKELY (InterlockedCompareExchangePointer ((gpointer *)&mon->owner, (gpointer)id, 0) == 0)) {
491                         /* Success */
492                         g_assert (mon->nest == 1);
493                         return 1;
494                 } else {
495                         /* Trumped again! */
496                         goto retry;
497                 }
498         }
499
500         /* If the object is currently locked by this thread... */
501         if (mon->owner == id) {
502                 mon->nest++;
503                 return 1;
504         }
505
506         /* The object must be locked by someone else... */
507         mono_perfcounters->thread_contentions++;
508
509         /* If ms is 0 we don't block, but just fail straight away */
510         if (ms == 0) {
511                 LOCK_DEBUG (g_message ("%s: (%d) timed out, returning FALSE", __func__, id));
512                 return 0;
513         }
514
515         mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_CONTENTION);
516
517         /* The slow path begins here. */
518 retry_contended:
519         /* a small amount of duplicated code, but it allows us to insert the profiler
520          * callbacks without impacting the fast path: from here on we don't need to go back to the
521          * retry label, but to retry_contended. At this point mon is already installed in the object
522          * header.
523          */
524         /* This case differs from Dice's case 3 because we don't
525          * deflate locks or cache unused lock records
526          */
527         if (G_LIKELY (mon->owner == 0)) {
528                 /* Try to install our ID in the owner field, nest
529                 * should have been left at 1 by the previous unlock
530                 * operation
531                 */
532                 if (G_LIKELY (InterlockedCompareExchangePointer ((gpointer *)&mon->owner, (gpointer)id, 0) == 0)) {
533                         /* Success */
534                         g_assert (mon->nest == 1);
535                         mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_DONE);
536                         return 1;
537                 }
538         }
539
540         /* If the object is currently locked by this thread... */
541         if (mon->owner == id) {
542                 mon->nest++;
543                 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_DONE);
544                 return 1;
545         }
546
547         /* We need to make sure there's a semaphore handle (creating it if
548          * necessary), and block on it
549          */
550         if (mon->entry_sem == NULL) {
551                 /* Create the semaphore */
552                 sem = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
553                 g_assert (sem != NULL);
554                 if (InterlockedCompareExchangePointer ((gpointer*)&mon->entry_sem, sem, NULL) != NULL) {
555                         /* Someone else just put a handle here */
556                         CloseHandle (sem);
557                 }
558         }
559         
560         /* If we need to time out, record a timestamp and adjust ms,
561          * because WaitForSingleObject doesn't tell us how long it
562          * waited for.
563          *
564          * Don't block forever here, because theres a chance the owner
565          * thread released the lock while we were creating the
566          * semaphore: we would not get the wakeup.  Using the event
567          * handle technique from pulse/wait would involve locking the
568          * lock struct and therefore slowing down the fast path.
569          */
570         if (ms != INFINITE) {
571                 then = mono_msec_ticks ();
572                 if (ms < 100) {
573                         waitms = ms;
574                 } else {
575                         waitms = 100;
576                 }
577         } else {
578                 waitms = 100;
579         }
580         
581         InterlockedIncrement (&mon->entry_count);
582
583         mono_perfcounters->thread_queue_len++;
584         mono_perfcounters->thread_queue_max++;
585         thread = mono_thread_current ();
586
587         mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
588
589         /*
590          * We pass TRUE instead of allow_interruption since we have to check for the
591          * StopRequested case below.
592          */
593         ret = WaitForSingleObjectEx (mon->entry_sem, waitms, TRUE);
594
595         mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
596         
597         InterlockedDecrement (&mon->entry_count);
598         mono_perfcounters->thread_queue_len--;
599
600         if (ms != INFINITE) {
601                 now = mono_msec_ticks ();
602                 
603                 if (now < then) {
604                         /* The counter must have wrapped around */
605                         LOCK_DEBUG (g_message ("%s: wrapped around! now=0x%x then=0x%x", __func__, now, then));
606                         
607                         now += (0xffffffff - then);
608                         then = 0;
609
610                         LOCK_DEBUG (g_message ("%s: wrap rejig: now=0x%x then=0x%x delta=0x%x", __func__, now, then, now-then));
611                 }
612                 
613                 delta = now - then;
614                 if (delta >= ms) {
615                         ms = 0;
616                 } else {
617                         ms -= delta;
618                 }
619
620                 if ((ret == WAIT_TIMEOUT || (ret == WAIT_IO_COMPLETION && !allow_interruption)) && ms > 0) {
621                         /* More time left */
622                         goto retry_contended;
623                 }
624         } else {
625                 if (ret == WAIT_TIMEOUT || (ret == WAIT_IO_COMPLETION && !allow_interruption)) {
626                         if (ret == WAIT_IO_COMPLETION && (mono_thread_test_state (mono_thread_current (), (ThreadState_StopRequested|ThreadState_SuspendRequested)))) {
627                                 /* 
628                                  * We have to obey a stop/suspend request even if 
629                                  * allow_interruption is FALSE to avoid hangs at shutdown.
630                                  */
631                                 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_FAIL);
632                                 return -1;
633                         }
634                         /* Infinite wait, so just try again */
635                         goto retry_contended;
636                 }
637         }
638         
639         if (ret == WAIT_OBJECT_0) {
640                 /* retry from the top */
641                 goto retry_contended;
642         }
643
644         /* We must have timed out */
645         LOCK_DEBUG (g_message ("%s: (%d) timed out waiting, returning FALSE", __func__, id));
646
647         mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_FAIL);
648
649         if (ret == WAIT_IO_COMPLETION)
650                 return -1;
651         else 
652                 return 0;
653 }
654
655 gboolean 
656 mono_monitor_enter (MonoObject *obj)
657 {
658         return mono_monitor_try_enter_internal (obj, INFINITE, FALSE) == 1;
659 }
660
661 gboolean 
662 mono_monitor_try_enter (MonoObject *obj, guint32 ms)
663 {
664         return mono_monitor_try_enter_internal (obj, ms, FALSE) == 1;
665 }
666
667 void
668 mono_monitor_exit (MonoObject *obj)
669 {
670         MonoThreadsSync *mon;
671         guint32 nest;
672         
673         LOCK_DEBUG (g_message ("%s: (%d) Unlocking %p", __func__, GetCurrentThreadId (), obj));
674
675         if (G_UNLIKELY (!obj)) {
676                 mono_raise_exception (mono_get_exception_argument_null ("obj"));
677                 return;
678         }
679
680         mon = obj->synchronisation;
681
682 #ifdef HAVE_MOVING_COLLECTOR
683         {
684                 LockWord lw;
685                 lw.sync = mon;
686                 if (lw.lock_word & LOCK_WORD_THIN_HASH)
687                         return;
688                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
689                 mon = lw.sync;
690         }
691 #endif
692         if (G_UNLIKELY (mon == NULL)) {
693                 /* No one ever used Enter. Just ignore the Exit request as MS does */
694                 return;
695         }
696         if (G_UNLIKELY (mon->owner != GetCurrentThreadId ())) {
697                 return;
698         }
699         
700         nest = mon->nest - 1;
701         if (nest == 0) {
702                 LOCK_DEBUG (g_message ("%s: (%d) Object %p is now unlocked", __func__, GetCurrentThreadId (), obj));
703         
704                 /* object is now unlocked, leave nest==1 so we don't
705                  * need to set it when the lock is reacquired
706                  */
707                 mon->owner = 0;
708
709                 /* Do the wakeup stuff.  It's possible that the last
710                  * blocking thread gave up waiting just before we
711                  * release the semaphore resulting in a futile wakeup
712                  * next time there's contention for this object, but
713                  * it means we don't have to waste time locking the
714                  * struct.
715                  */
716                 if (mon->entry_count > 0) {
717                         ReleaseSemaphore (mon->entry_sem, 1, NULL);
718                 }
719         } else {
720                 LOCK_DEBUG (g_message ("%s: (%d) Object %p is now locked %d times", __func__, GetCurrentThreadId (), obj, nest));
721                 mon->nest = nest;
722         }
723 }
724
725 void**
726 mono_monitor_get_object_monitor_weak_link (MonoObject *object)
727 {
728         LockWord lw;
729         MonoThreadsSync *sync = NULL;
730
731         lw.sync = object->synchronisation;
732         if (lw.lock_word & LOCK_WORD_FAT_HASH) {
733                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
734                 sync = lw.sync;
735         } else if (!(lw.lock_word & LOCK_WORD_THIN_HASH)) {
736                 sync = lw.sync;
737         }
738
739         if (sync && sync->data)
740                 return &sync->data;
741         return NULL;
742 }
743
744 static void
745 emit_obj_syncp_check (MonoMethodBuilder *mb, int syncp_loc, int *obj_null_branch, int *syncp_true_false_branch,
746         gboolean branch_on_true)
747 {
748         /*
749           ldarg         0                                                       obj
750           brfalse.s     obj_null
751         */
752
753         mono_mb_emit_byte (mb, CEE_LDARG_0);
754         *obj_null_branch = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
755
756         /*
757           ldarg         0                                                       obj
758           conv.i                                                                objp
759           ldc.i4        G_STRUCT_OFFSET(MonoObject, synchronisation)            objp off
760           add                                                                   &syncp
761           ldind.i                                                               syncp
762           stloc         syncp
763           ldloc         syncp                                                   syncp
764           brtrue/false.s        syncp_true_false
765         */
766
767         mono_mb_emit_byte (mb, CEE_LDARG_0);
768         mono_mb_emit_byte (mb, CEE_CONV_I);
769         mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoObject, synchronisation));
770         mono_mb_emit_byte (mb, CEE_ADD);
771         mono_mb_emit_byte (mb, CEE_LDIND_I);
772         mono_mb_emit_stloc (mb, syncp_loc);
773         mono_mb_emit_ldloc (mb, syncp_loc);
774         *syncp_true_false_branch = mono_mb_emit_short_branch (mb, branch_on_true ? CEE_BRTRUE_S : CEE_BRFALSE_S);
775 }
776
777 static MonoMethod*
778 mono_monitor_get_fast_enter_method (MonoMethod *monitor_enter_method)
779 {
780         static MonoMethod *fast_monitor_enter;
781         static MonoMethod *compare_exchange_method;
782
783         MonoMethodBuilder *mb;
784         int obj_null_branch, syncp_null_branch, has_owner_branch, other_owner_branch, tid_branch;
785         int tid_loc, syncp_loc, owner_loc;
786         int thread_tls_offset;
787
788 #ifdef HAVE_MOVING_COLLECTOR
789         return NULL;
790 #endif
791
792         thread_tls_offset = mono_thread_get_tls_offset ();
793         if (thread_tls_offset == -1)
794                 return NULL;
795
796         if (fast_monitor_enter)
797                 return fast_monitor_enter;
798
799         if (!compare_exchange_method) {
800                 MonoMethodDesc *desc;
801                 MonoClass *class;
802
803                 desc = mono_method_desc_new ("Interlocked:CompareExchange(intptr&,intptr,intptr)", FALSE);
804                 class = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
805                 compare_exchange_method = mono_method_desc_search_in_class (desc, class);
806                 mono_method_desc_free (desc);
807
808                 if (!compare_exchange_method)
809                         return NULL;
810         }
811
812         mb = mono_mb_new (mono_defaults.monitor_class, "FastMonitorEnter", MONO_WRAPPER_UNKNOWN);
813
814         mb->method->slot = -1;
815         mb->method->flags = METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_STATIC |
816                 METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
817
818         tid_loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
819         syncp_loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
820         owner_loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
821
822         emit_obj_syncp_check (mb, syncp_loc, &obj_null_branch, &syncp_null_branch, FALSE);
823
824         /*
825           mono. tls     thread_tls_offset                                       threadp
826           ldc.i4        G_STRUCT_OFFSET(MonoThread, tid)                        threadp off
827           add                                                                   &tid
828           ldind.i                                                               tid
829           stloc         tid
830           ldloc         syncp                                                   syncp
831           ldc.i4        G_STRUCT_OFFSET(MonoThreadsSync, owner)                 syncp off
832           add                                                                   &owner
833           ldind.i                                                               owner
834           stloc         owner
835           ldloc         owner                                                   owner
836           brtrue.s      tid
837         */
838
839         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
840         mono_mb_emit_byte (mb, CEE_MONO_TLS);
841         mono_mb_emit_i4 (mb, thread_tls_offset);
842         mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThread, tid));
843         mono_mb_emit_byte (mb, CEE_ADD);
844         mono_mb_emit_byte (mb, CEE_LDIND_I);
845         mono_mb_emit_stloc (mb, tid_loc);
846         mono_mb_emit_ldloc (mb, syncp_loc);
847         mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, owner));
848         mono_mb_emit_byte (mb, CEE_ADD);
849         mono_mb_emit_byte (mb, CEE_LDIND_I);
850         mono_mb_emit_stloc (mb, owner_loc);
851         mono_mb_emit_ldloc (mb, owner_loc);
852         tid_branch = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S);
853
854         /*
855           ldloc         syncp                                                   syncp
856           ldc.i4        G_STRUCT_OFFSET(MonoThreadsSync, owner)                 syncp off
857           add                                                                   &owner
858           ldloc         tid                                                     &owner tid
859           ldc.i4        0                                                       &owner tid 0
860           call          System.Threading.Interlocked.CompareExchange            oldowner
861           brtrue.s      has_owner
862           ret
863         */
864
865         mono_mb_emit_ldloc (mb, syncp_loc);
866         mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, owner));
867         mono_mb_emit_byte (mb, CEE_ADD);
868         mono_mb_emit_ldloc (mb, tid_loc);
869         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
870         mono_mb_emit_managed_call (mb, compare_exchange_method, NULL);
871         has_owner_branch = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S);
872         mono_mb_emit_byte (mb, CEE_RET);
873
874         /*
875          tid:
876           ldloc         owner                                                   owner
877           ldloc         tid                                                     owner tid
878           brne.s        other_owner
879           ldloc         syncp                                                   syncp
880           ldc.i4        G_STRUCT_OFFSET(MonoThreadsSync, nest)                  syncp off
881           add                                                                   &nest
882           dup                                                                   &nest &nest
883           ldind.i4                                                              &nest nest
884           ldc.i4        1                                                       &nest nest 1
885           add                                                                   &nest nest+
886           stind.i4
887           ret
888         */
889
890         mono_mb_patch_short_branch (mb, tid_branch);
891         mono_mb_emit_ldloc (mb, owner_loc);
892         mono_mb_emit_ldloc (mb, tid_loc);
893         other_owner_branch = mono_mb_emit_short_branch (mb, CEE_BNE_UN_S);
894         mono_mb_emit_ldloc (mb, syncp_loc);
895         mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, nest));
896         mono_mb_emit_byte (mb, CEE_ADD);
897         mono_mb_emit_byte (mb, CEE_DUP);
898         mono_mb_emit_byte (mb, CEE_LDIND_I4);
899         mono_mb_emit_byte (mb, CEE_LDC_I4_1);
900         mono_mb_emit_byte (mb, CEE_ADD);
901         mono_mb_emit_byte (mb, CEE_STIND_I4);
902         mono_mb_emit_byte (mb, CEE_RET);
903
904         /*
905          obj_null, syncp_null, has_owner, other_owner:
906           ldarg         0                                                       obj
907           call          System.Threading.Monitor.Enter
908           ret
909         */
910
911         mono_mb_patch_short_branch (mb, obj_null_branch);
912         mono_mb_patch_short_branch (mb, syncp_null_branch);
913         mono_mb_patch_short_branch (mb, has_owner_branch);
914         mono_mb_patch_short_branch (mb, other_owner_branch);
915         mono_mb_emit_byte (mb, CEE_LDARG_0);
916         mono_mb_emit_managed_call (mb, monitor_enter_method, NULL);
917         mono_mb_emit_byte (mb, CEE_RET);
918
919         fast_monitor_enter = mono_mb_create_method (mb, mono_signature_no_pinvoke (monitor_enter_method), 5);
920         mono_mb_free (mb);
921
922         return fast_monitor_enter;
923 }
924
925 static MonoMethod*
926 mono_monitor_get_fast_exit_method (MonoMethod *monitor_exit_method)
927 {
928         static MonoMethod *fast_monitor_exit;
929
930         MonoMethodBuilder *mb;
931         int obj_null_branch, has_waiting_branch, has_syncp_branch, owned_branch, nested_branch;
932         int thread_tls_offset;
933         int syncp_loc;
934
935 #ifdef HAVE_MOVING_COLLECTOR
936         return NULL;
937 #endif
938
939         thread_tls_offset = mono_thread_get_tls_offset ();
940         if (thread_tls_offset == -1)
941                 return NULL;
942
943         if (fast_monitor_exit)
944                 return fast_monitor_exit;
945
946         mb = mono_mb_new (mono_defaults.monitor_class, "FastMonitorExit", MONO_WRAPPER_UNKNOWN);
947
948         mb->method->slot = -1;
949         mb->method->flags = METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_STATIC |
950                 METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
951
952         syncp_loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
953
954         emit_obj_syncp_check (mb, syncp_loc, &obj_null_branch, &has_syncp_branch, TRUE);
955
956         /*
957           ret
958         */
959
960         mono_mb_emit_byte (mb, CEE_RET);
961
962         /*
963          has_syncp:
964           ldloc         syncp                                                   syncp
965           ldc.i4        G_STRUCT_OFFSET(MonoThreadsSync, owner)                 syncp off
966           add                                                                   &owner
967           ldind.i                                                               owner
968           mono. tls     thread_tls_offset                                       owner threadp
969           ldc.i4        G_STRUCT_OFFSET(MonoThread, tid)                        owner threadp off
970           add                                                                   owner &tid
971           ldind.i                                                               owner tid
972           beq.s         owned
973         */
974
975         mono_mb_patch_short_branch (mb, has_syncp_branch);
976         mono_mb_emit_ldloc (mb, syncp_loc);
977         mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, owner));
978         mono_mb_emit_byte (mb, CEE_ADD);
979         mono_mb_emit_byte (mb, CEE_LDIND_I);
980         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
981         mono_mb_emit_byte (mb, CEE_MONO_TLS);
982         mono_mb_emit_i4 (mb, thread_tls_offset);
983         mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThread, tid));
984         mono_mb_emit_byte (mb, CEE_ADD);
985         mono_mb_emit_byte (mb, CEE_LDIND_I);
986         owned_branch = mono_mb_emit_short_branch (mb, CEE_BEQ_S);
987
988         /*
989           ret
990         */
991
992         mono_mb_emit_byte (mb, CEE_RET);
993
994         /*
995          owned:
996           ldloc         syncp                                                   syncp
997           ldc.i4        G_STRUCT_OFFSET(MonoThreadsSync, nest)                  syncp off
998           add                                                                   &nest
999           dup                                                                   &nest &nest
1000           ldind.i4                                                              &nest nest
1001           dup                                                                   &nest nest nest
1002           ldc.i4        1                                                       &nest nest nest 1
1003           bgt.un.s      nested                                                  &nest nest
1004         */
1005
1006         mono_mb_patch_short_branch (mb, owned_branch);
1007         mono_mb_emit_ldloc (mb, syncp_loc);
1008         mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, nest));
1009         mono_mb_emit_byte (mb, CEE_ADD);
1010         mono_mb_emit_byte (mb, CEE_DUP);
1011         mono_mb_emit_byte (mb, CEE_LDIND_I4);
1012         mono_mb_emit_byte (mb, CEE_DUP);
1013         mono_mb_emit_byte (mb, CEE_LDC_I4_1);
1014         nested_branch = mono_mb_emit_short_branch (mb, CEE_BGT_UN_S);
1015
1016         /*
1017           pop                                                                   &nest
1018           pop
1019           ldloc         syncp                                                   syncp
1020           ldc.i4        G_STRUCT_OFFSET(MonoThreadsSync, entry_count)           syncp off
1021           add                                                                   &count
1022           ldind.i4                                                              count
1023           brtrue.s      has_waiting
1024         */
1025
1026         mono_mb_emit_byte (mb, CEE_POP);
1027         mono_mb_emit_byte (mb, CEE_POP);
1028         mono_mb_emit_ldloc (mb, syncp_loc);
1029         mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, entry_count));
1030         mono_mb_emit_byte (mb, CEE_ADD);
1031         mono_mb_emit_byte (mb, CEE_LDIND_I4);
1032         has_waiting_branch = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S);
1033
1034         /*
1035           ldloc         syncp                                                   syncp
1036           ldc.i4        G_STRUCT_OFFSET(MonoThreadsSync, owner)                 syncp off
1037           add                                                                   &owner
1038           ldnull                                                                &owner 0
1039           stind.i
1040           ret
1041         */
1042
1043         mono_mb_emit_ldloc (mb, syncp_loc);
1044         mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, owner));
1045         mono_mb_emit_byte (mb, CEE_ADD);
1046         mono_mb_emit_byte (mb, CEE_LDNULL);
1047         mono_mb_emit_byte (mb, CEE_STIND_I);
1048         mono_mb_emit_byte (mb, CEE_RET);
1049
1050         /*
1051          nested:
1052           ldc.i4        1                                                       &nest nest 1
1053           sub                                                                   &nest nest-
1054           stind.i4
1055           ret
1056         */
1057
1058         mono_mb_patch_short_branch (mb, nested_branch);
1059         mono_mb_emit_byte (mb, CEE_LDC_I4_1);
1060         mono_mb_emit_byte (mb, CEE_SUB);
1061         mono_mb_emit_byte (mb, CEE_STIND_I4);
1062         mono_mb_emit_byte (mb, CEE_RET);
1063
1064         /*
1065          obj_null, has_waiting:
1066           ldarg         0                                                       obj
1067           call          System.Threading.Monitor.Exit
1068           ret
1069          */
1070
1071         mono_mb_patch_short_branch (mb, obj_null_branch);
1072         mono_mb_patch_short_branch (mb, has_waiting_branch);
1073         mono_mb_emit_byte (mb, CEE_LDARG_0);
1074         mono_mb_emit_managed_call (mb, monitor_exit_method, NULL);
1075         mono_mb_emit_byte (mb, CEE_RET);
1076
1077         fast_monitor_exit = mono_mb_create_method (mb, mono_signature_no_pinvoke (monitor_exit_method), 5);
1078         mono_mb_free (mb);
1079
1080         return fast_monitor_exit;
1081 }
1082
1083 MonoMethod*
1084 mono_monitor_get_fast_path (MonoMethod *enter_or_exit)
1085 {
1086         if (strcmp (enter_or_exit->name, "Enter") == 0)
1087                 return mono_monitor_get_fast_enter_method (enter_or_exit);
1088         if (strcmp (enter_or_exit->name, "Exit") == 0)
1089                 return mono_monitor_get_fast_exit_method (enter_or_exit);
1090         g_assert_not_reached ();
1091         return NULL;
1092 }
1093
1094 /*
1095  * mono_monitor_threads_sync_member_offset:
1096  * @owner_offset: returns size and offset of the "owner" member
1097  * @nest_offset: returns size and offset of the "nest" member
1098  * @entry_count_offset: returns size and offset of the "entry_count" member
1099  *
1100  * Returns the offsets and sizes of three members of the
1101  * MonoThreadsSync struct.  The Monitor ASM fastpaths need this.
1102  */
1103 void
1104 mono_monitor_threads_sync_members_offset (int *owner_offset, int *nest_offset, int *entry_count_offset)
1105 {
1106         MonoThreadsSync ts;
1107
1108 #define ENCODE_OFF_SIZE(o,s)    (((o) << 8) | ((s) & 0xff))
1109
1110         *owner_offset = ENCODE_OFF_SIZE (G_STRUCT_OFFSET (MonoThreadsSync, owner), sizeof (ts.owner));
1111         *nest_offset = ENCODE_OFF_SIZE (G_STRUCT_OFFSET (MonoThreadsSync, nest), sizeof (ts.nest));
1112         *entry_count_offset = ENCODE_OFF_SIZE (G_STRUCT_OFFSET (MonoThreadsSync, entry_count), sizeof (ts.entry_count));
1113 }
1114
1115 gboolean 
1116 ves_icall_System_Threading_Monitor_Monitor_try_enter (MonoObject *obj, guint32 ms)
1117 {
1118         gint32 res;
1119
1120         do {
1121                 res = mono_monitor_try_enter_internal (obj, ms, TRUE);
1122                 if (res == -1)
1123                         mono_thread_interruption_checkpoint ();
1124         } while (res == -1);
1125         
1126         return res == 1;
1127 }
1128
1129 gboolean 
1130 ves_icall_System_Threading_Monitor_Monitor_test_owner (MonoObject *obj)
1131 {
1132         MonoThreadsSync *mon;
1133         
1134         LOCK_DEBUG (g_message ("%s: Testing if %p is owned by thread %d", __func__, obj, GetCurrentThreadId()));
1135
1136         mon = obj->synchronisation;
1137 #ifdef HAVE_MOVING_COLLECTOR
1138         {
1139                 LockWord lw;
1140                 lw.sync = mon;
1141                 if (lw.lock_word & LOCK_WORD_THIN_HASH)
1142                         return FALSE;
1143                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1144                 mon = lw.sync;
1145         }
1146 #endif
1147         if (mon == NULL) {
1148                 return FALSE;
1149         }
1150         
1151         if(mon->owner==GetCurrentThreadId ()) {
1152                 return(TRUE);
1153         }
1154         
1155         return(FALSE);
1156 }
1157
1158 gboolean 
1159 ves_icall_System_Threading_Monitor_Monitor_test_synchronised (MonoObject *obj)
1160 {
1161         MonoThreadsSync *mon;
1162
1163         LOCK_DEBUG (g_message("%s: (%d) Testing if %p is owned by any thread", __func__, GetCurrentThreadId (), obj));
1164         
1165         mon = obj->synchronisation;
1166 #ifdef HAVE_MOVING_COLLECTOR
1167         {
1168                 LockWord lw;
1169                 lw.sync = mon;
1170                 if (lw.lock_word & LOCK_WORD_THIN_HASH)
1171                         return FALSE;
1172                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1173                 mon = lw.sync;
1174         }
1175 #endif
1176         if (mon == NULL) {
1177                 return FALSE;
1178         }
1179         
1180         if (mon->owner != 0) {
1181                 return TRUE;
1182         }
1183         
1184         return FALSE;
1185 }
1186
1187 /* All wait list manipulation in the pulse, pulseall and wait
1188  * functions happens while the monitor lock is held, so we don't need
1189  * any extra struct locking
1190  */
1191
1192 void
1193 ves_icall_System_Threading_Monitor_Monitor_pulse (MonoObject *obj)
1194 {
1195         MonoThreadsSync *mon;
1196         
1197         LOCK_DEBUG (g_message ("%s: (%d) Pulsing %p", __func__, GetCurrentThreadId (), obj));
1198         
1199         mon = obj->synchronisation;
1200 #ifdef HAVE_MOVING_COLLECTOR
1201         {
1202                 LockWord lw;
1203                 lw.sync = mon;
1204                 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
1205                         mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1206                         return;
1207                 }
1208                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1209                 mon = lw.sync;
1210         }
1211 #endif
1212         if (mon == NULL) {
1213                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1214                 return;
1215         }
1216         if (mon->owner != GetCurrentThreadId ()) {
1217                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
1218                 return;
1219         }
1220
1221         LOCK_DEBUG (g_message ("%s: (%d) %d threads waiting", __func__, GetCurrentThreadId (), g_slist_length (mon->wait_list)));
1222         
1223         if (mon->wait_list != NULL) {
1224                 LOCK_DEBUG (g_message ("%s: (%d) signalling and dequeuing handle %p", __func__, GetCurrentThreadId (), mon->wait_list->data));
1225         
1226                 SetEvent (mon->wait_list->data);
1227                 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
1228         }
1229 }
1230
1231 void
1232 ves_icall_System_Threading_Monitor_Monitor_pulse_all (MonoObject *obj)
1233 {
1234         MonoThreadsSync *mon;
1235         
1236         LOCK_DEBUG (g_message("%s: (%d) Pulsing all %p", __func__, GetCurrentThreadId (), obj));
1237
1238         mon = obj->synchronisation;
1239 #ifdef HAVE_MOVING_COLLECTOR
1240         {
1241                 LockWord lw;
1242                 lw.sync = mon;
1243                 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
1244                         mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1245                         return;
1246                 }
1247                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1248                 mon = lw.sync;
1249         }
1250 #endif
1251         if (mon == NULL) {
1252                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1253                 return;
1254         }
1255         if (mon->owner != GetCurrentThreadId ()) {
1256                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
1257                 return;
1258         }
1259
1260         LOCK_DEBUG (g_message ("%s: (%d) %d threads waiting", __func__, GetCurrentThreadId (), g_slist_length (mon->wait_list)));
1261
1262         while (mon->wait_list != NULL) {
1263                 LOCK_DEBUG (g_message ("%s: (%d) signalling and dequeuing handle %p", __func__, GetCurrentThreadId (), mon->wait_list->data));
1264         
1265                 SetEvent (mon->wait_list->data);
1266                 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
1267         }
1268 }
1269
1270 gboolean
1271 ves_icall_System_Threading_Monitor_Monitor_wait (MonoObject *obj, guint32 ms)
1272 {
1273         MonoThreadsSync *mon;
1274         HANDLE event;
1275         guint32 nest;
1276         guint32 ret;
1277         gboolean success = FALSE;
1278         gint32 regain;
1279         MonoThread *thread = mono_thread_current ();
1280
1281         LOCK_DEBUG (g_message ("%s: (%d) Trying to wait for %p with timeout %dms", __func__, GetCurrentThreadId (), obj, ms));
1282         
1283         mon = obj->synchronisation;
1284 #ifdef HAVE_MOVING_COLLECTOR
1285         {
1286                 LockWord lw;
1287                 lw.sync = mon;
1288                 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
1289                         mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1290                         return FALSE;
1291                 }
1292                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1293                 mon = lw.sync;
1294         }
1295 #endif
1296         if (mon == NULL) {
1297                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1298                 return FALSE;
1299         }
1300         if (mon->owner != GetCurrentThreadId ()) {
1301                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
1302                 return FALSE;
1303         }
1304
1305         /* Do this WaitSleepJoin check before creating the event handle */
1306         mono_thread_current_check_pending_interrupt ();
1307         
1308         event = CreateEvent (NULL, FALSE, FALSE, NULL);
1309         if (event == NULL) {
1310                 mono_raise_exception (mono_get_exception_synchronization_lock ("Failed to set up wait event"));
1311                 return FALSE;
1312         }
1313         
1314         LOCK_DEBUG (g_message ("%s: (%d) queuing handle %p", __func__, GetCurrentThreadId (), event));
1315
1316         mono_thread_current_check_pending_interrupt ();
1317         
1318         mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1319
1320         mon->wait_list = g_slist_append (mon->wait_list, event);
1321         
1322         /* Save the nest count, and release the lock */
1323         nest = mon->nest;
1324         mon->nest = 1;
1325         mono_monitor_exit (obj);
1326
1327         LOCK_DEBUG (g_message ("%s: (%d) Unlocked %p lock %p", __func__, GetCurrentThreadId (), obj, mon));
1328
1329         /* There's no race between unlocking mon and waiting for the
1330          * event, because auto reset events are sticky, and this event
1331          * is private to this thread.  Therefore even if the event was
1332          * signalled before we wait, we still succeed.
1333          */
1334         ret = WaitForSingleObjectEx (event, ms, TRUE);
1335
1336         /* Reset the thread state fairly early, so we don't have to worry
1337          * about the monitor error checking
1338          */
1339         mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1340         
1341         if (mono_thread_interruption_requested ()) {
1342                 CloseHandle (event);
1343                 return FALSE;
1344         }
1345
1346         /* Regain the lock with the previous nest count */
1347         do {
1348                 regain = mono_monitor_try_enter_internal (obj, INFINITE, TRUE);
1349                 if (regain == -1) 
1350                         mono_thread_interruption_checkpoint ();
1351         } while (regain == -1);
1352
1353         if (regain == 0) {
1354                 /* Something went wrong, so throw a
1355                  * SynchronizationLockException
1356                  */
1357                 CloseHandle (event);
1358                 mono_raise_exception (mono_get_exception_synchronization_lock ("Failed to regain lock"));
1359                 return FALSE;
1360         }
1361
1362         mon->nest = nest;
1363
1364         LOCK_DEBUG (g_message ("%s: (%d) Regained %p lock %p", __func__, GetCurrentThreadId (), obj, mon));
1365
1366         if (ret == WAIT_TIMEOUT) {
1367                 /* Poll the event again, just in case it was signalled
1368                  * while we were trying to regain the monitor lock
1369                  */
1370                 ret = WaitForSingleObjectEx (event, 0, FALSE);
1371         }
1372
1373         /* Pulse will have popped our event from the queue if it signalled
1374          * us, so we only do it here if the wait timed out.
1375          *
1376          * This avoids a race condition where the thread holding the
1377          * lock can Pulse several times before the WaitForSingleObject
1378          * returns.  If we popped the queue here then this event might
1379          * be signalled more than once, thereby starving another
1380          * thread.
1381          */
1382         
1383         if (ret == WAIT_OBJECT_0) {
1384                 LOCK_DEBUG (g_message ("%s: (%d) Success", __func__, GetCurrentThreadId ()));
1385                 success = TRUE;
1386         } else {
1387                 LOCK_DEBUG (g_message ("%s: (%d) Wait failed, dequeuing handle %p", __func__, GetCurrentThreadId (), event));
1388                 /* No pulse, so we have to remove ourself from the
1389                  * wait queue
1390                  */
1391                 mon->wait_list = g_slist_remove (mon->wait_list, event);
1392         }
1393         CloseHandle (event);
1394         
1395         return success;
1396 }
1397