Merge pull request #1909 from esdrubal/reflection
[mono.git] / mono / utils / mono-threads-posix.c
1 /*
2  * mono-threads-posix.c: Low-level threading, posix version
3  *
4  * Author:
5  *      Rodrigo Kumpera (kumpera@gmail.com)
6  *
7  * (C) 2011 Novell, Inc
8  */
9
10 #include <config.h>
11
12 /* For pthread_main_np, pthread_get_stackaddr_np and pthread_get_stacksize_np */
13 #if defined (__MACH__)
14 #define _DARWIN_C_SOURCE 1
15 #endif
16
17 #include <mono/utils/mono-compiler.h>
18 #include <mono/utils/mono-semaphore.h>
19 #include <mono/utils/mono-threads.h>
20 #include <mono/utils/mono-tls.h>
21 #include <mono/utils/mono-mmap.h>
22 #include <mono/metadata/threads-types.h>
23 #include <mono/metadata/gc-internal.h>
24 #include <limits.h>
25
26 #include <errno.h>
27
28 #if defined(PLATFORM_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
29 #define USE_TKILL_ON_ANDROID 1
30 #endif
31
32 #ifdef USE_TKILL_ON_ANDROID
33 extern int tkill (pid_t tid, int signal);
34 #endif
35
36 #if defined(_POSIX_VERSION) || defined(__native_client__)
37 #include <sys/resource.h>
38 #include <signal.h>
39
40 #if defined(__native_client__)
41 void nacl_shutdown_gc_thread(void);
42 #endif
43
44 typedef struct {
45         void *(*start_routine)(void*);
46         void *arg;
47         int flags;
48         MonoSemType registered;
49         HANDLE handle;
50 } StartInfo;
51
52 static void*
53 inner_start_thread (void *arg)
54 {
55         StartInfo *start_info = (StartInfo *) arg;
56         void *t_arg = start_info->arg;
57         int res;
58         void *(*start_func)(void*) = start_info->start_routine;
59         guint32 flags = start_info->flags;
60         void *result;
61         HANDLE handle;
62         MonoThreadInfo *info;
63
64         /* Register the thread with the io-layer */
65         handle = wapi_create_thread_handle ();
66         if (!handle) {
67                 res = MONO_SEM_POST (&(start_info->registered));
68                 g_assert (!res);
69                 return NULL;
70         }
71         start_info->handle = handle;
72
73         info = mono_thread_info_attach (&result);
74         MONO_PREPARE_BLOCKING
75
76         info->runtime_thread = TRUE;
77         info->handle = handle;
78
79         if (flags & CREATE_SUSPENDED) {
80                 info->create_suspended = TRUE;
81                 MONO_SEM_INIT (&info->create_suspended_sem, 0);
82         }
83
84         /* start_info is not valid after this */
85         res = MONO_SEM_POST (&(start_info->registered));
86         g_assert (!res);
87         start_info = NULL;
88
89         if (flags & CREATE_SUSPENDED) {
90                 while (MONO_SEM_WAIT (&info->create_suspended_sem) != 0 &&
91                            errno == EINTR);
92                 MONO_SEM_DESTROY (&info->create_suspended_sem);
93         }
94
95         MONO_FINISH_BLOCKING
96         /* Run the actual main function of the thread */
97         result = start_func (t_arg);
98
99         mono_threads_core_exit (GPOINTER_TO_UINT (result));
100         g_assert_not_reached ();
101 }
102
103 HANDLE
104 mono_threads_core_create_thread (LPTHREAD_START_ROUTINE start_routine, gpointer arg, guint32 stack_size, guint32 creation_flags, MonoNativeThreadId *out_tid)
105 {
106         pthread_attr_t attr;
107         int res;
108         pthread_t thread;
109         StartInfo start_info;
110
111         res = pthread_attr_init (&attr);
112         g_assert (!res);
113
114         if (stack_size == 0) {
115 #if HAVE_VALGRIND_MEMCHECK_H
116                 if (RUNNING_ON_VALGRIND)
117                         stack_size = 1 << 20;
118                 else
119                         stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
120 #else
121                 stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
122 #endif
123         }
124
125 #ifdef PTHREAD_STACK_MIN
126         if (stack_size < PTHREAD_STACK_MIN)
127                 stack_size = PTHREAD_STACK_MIN;
128 #endif
129
130 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
131         res = pthread_attr_setstacksize (&attr, stack_size);
132         g_assert (!res);
133 #endif
134
135         memset (&start_info, 0, sizeof (StartInfo));
136         start_info.start_routine = (void *(*)(void *)) start_routine;
137         start_info.arg = arg;
138         start_info.flags = creation_flags;
139         MONO_SEM_INIT (&(start_info.registered), 0);
140
141         /* Actually start the thread */
142         res = mono_gc_pthread_create (&thread, &attr, inner_start_thread, &start_info);
143         if (res) {
144                 MONO_SEM_DESTROY (&(start_info.registered));
145                 return NULL;
146         }
147
148         /* Wait until the thread register itself in various places */
149         while (MONO_SEM_WAIT (&(start_info.registered)) != 0) {
150                 /*if (EINTR != errno) ABORT("sem_wait failed"); */
151         }
152         MONO_SEM_DESTROY (&(start_info.registered));
153
154         if (out_tid)
155                 *out_tid = thread;
156
157         return start_info.handle;
158 }
159
160 /*
161  * mono_threads_core_resume_created:
162  *
163  *   Resume a newly created thread created using CREATE_SUSPENDED.
164  */
165 void
166 mono_threads_core_resume_created (MonoThreadInfo *info, MonoNativeThreadId tid)
167 {
168         MONO_SEM_POST (&info->create_suspended_sem);
169 }
170
171 gboolean
172 mono_threads_core_yield (void)
173 {
174         return sched_yield () == 0;
175 }
176
177 void
178 mono_threads_core_exit (int exit_code)
179 {
180         MonoThreadInfo *current = mono_thread_info_current ();
181
182 #if defined(__native_client__)
183         nacl_shutdown_gc_thread();
184 #endif
185
186         wapi_thread_handle_set_exited (current->handle, exit_code);
187
188         mono_thread_info_detach ();
189
190         pthread_exit (NULL);
191 }
192
193 void
194 mono_threads_core_unregister (MonoThreadInfo *info)
195 {
196         if (info->handle) {
197                 wapi_thread_handle_set_exited (info->handle, 0);
198                 info->handle = NULL;
199         }
200 }
201
202 HANDLE
203 mono_threads_core_open_handle (void)
204 {
205         MonoThreadInfo *info;
206
207         info = mono_thread_info_current ();
208         g_assert (info);
209
210         if (!info->handle)
211                 info->handle = wapi_create_thread_handle ();
212         else
213                 wapi_ref_thread_handle (info->handle);
214         return info->handle;
215 }
216
217 int
218 mono_threads_get_max_stack_size (void)
219 {
220         struct rlimit lim;
221
222         /* If getrlimit fails, we don't enforce any limits. */
223         if (getrlimit (RLIMIT_STACK, &lim))
224                 return INT_MAX;
225         /* rlim_t is an unsigned long long on 64bits OSX but we want an int response. */
226         if (lim.rlim_max > (rlim_t)INT_MAX)
227                 return INT_MAX;
228         return (int)lim.rlim_max;
229 }
230
231 HANDLE
232 mono_threads_core_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
233 {
234         wapi_ref_thread_handle (handle);
235
236         return handle;
237 }
238
239 gpointer
240 mono_threads_core_prepare_interrupt (HANDLE thread_handle)
241 {
242         return wapi_prepare_interrupt_thread (thread_handle);
243 }
244
245 void
246 mono_threads_core_finish_interrupt (gpointer wait_handle)
247 {
248         wapi_finish_interrupt_thread (wait_handle);
249 }
250
251 void
252 mono_threads_core_self_interrupt (void)
253 {
254         wapi_self_interrupt ();
255 }
256
257 void
258 mono_threads_core_clear_interruption (void)
259 {
260         wapi_clear_interruption ();
261 }
262
263 int
264 mono_threads_pthread_kill (MonoThreadInfo *info, int signum)
265 {
266         THREADS_SUSPEND_DEBUG ("sending signal %d to %p[%p]\n", signum, info, mono_thread_info_get_tid (info));
267 #ifdef USE_TKILL_ON_ANDROID
268         int result, old_errno = errno;
269         result = tkill (info->native_handle, signum);
270         if (result < 0) {
271                 result = errno;
272                 errno = old_errno;
273         }
274         return result;
275 #elif defined(__native_client__)
276         /* Workaround pthread_kill abort() in NaCl glibc. */
277         return 0;
278 #elif !defined(HAVE_PTHREAD_KILL)
279         g_error ("pthread_kill() is not supported by this platform");
280 #else
281         return pthread_kill (mono_thread_info_get_tid (info), signum);
282 #endif
283 }
284
285 MonoNativeThreadId
286 mono_native_thread_id_get (void)
287 {
288         return pthread_self ();
289 }
290
291 gboolean
292 mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2)
293 {
294         return pthread_equal (id1, id2);
295 }
296
297 /*
298  * mono_native_thread_create:
299  *
300  *   Low level thread creation function without any GC wrappers.
301  */
302 gboolean
303 mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg)
304 {
305         return pthread_create (tid, NULL, (void *(*)(void *)) func, arg) == 0;
306 }
307
308 void
309 mono_threads_core_set_name (MonoNativeThreadId tid, const char *name)
310 {
311 #if defined (HAVE_PTHREAD_SETNAME_NP) && !defined (__MACH__)
312         if (!name) {
313                 pthread_setname_np (tid, "");
314         } else {
315                 char n [16];
316
317                 strncpy (n, name, 16);
318                 n [15] = '\0';
319                 pthread_setname_np (tid, n);
320         }
321 #endif
322 }
323
324
325 #if defined (USE_POSIX_BACKEND) && !defined (USE_COOP_GC)
326
327 static int suspend_signal_num;
328 static int restart_signal_num;
329 static int abort_signal_num;
330 static sigset_t suspend_signal_mask;
331 static sigset_t suspend_ack_signal_mask;
332
333
334 #if defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
335 #define DEFAULT_SUSPEND_SIGNAL SIGXFSZ
336 #else
337 #define DEFAULT_SUSPEND_SIGNAL SIGPWR
338 #endif
339 #define DEFAULT_RESTART_SIGNAL SIGXCPU
340
341 static int
342 mono_thread_search_alt_signal (int min_signal)
343 {
344 #if !defined (SIGRTMIN)
345         g_error ("signal search only works with RTMIN");
346 #else
347         int i;
348         /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
349         for (i = MAX (min_signal, SIGRTMIN) + 1; i < SIGRTMAX; ++i) {
350                 struct sigaction sinfo;
351                 sigaction (i, NULL, &sinfo);
352                 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
353                         return i;
354                 }
355         }
356         g_error ("Could not find an available signal");
357 #endif
358 }
359
360 static int
361 mono_thread_get_alt_suspend_signal (void)
362 {
363 #if defined(PLATFORM_ANDROID)
364         return SIGUNUSED;
365 #elif !defined (SIGRTMIN)
366 #ifdef SIGUSR1
367         return SIGUSR1;
368 #else
369         return -1;
370 #endif /* SIGUSR1 */
371 #else
372         static int suspend_signum = -1;
373         if (suspend_signum == -1)
374                 suspend_signum = mono_thread_search_alt_signal (-1);
375         return suspend_signum;
376 #endif /* SIGRTMIN */
377 }
378
379 static int
380 mono_thread_get_alt_resume_signal (void)
381 {
382 #if defined(PLATFORM_ANDROID)
383         return SIGTTOU;
384 #elif !defined (SIGRTMIN)
385 #ifdef SIGUSR2
386         return SIGUSR2;
387 #else
388         return -1;
389 #endif /* SIGUSR1 */
390 #else
391         static int resume_signum = -1;
392         if (resume_signum == -1)
393                 resume_signum = mono_thread_search_alt_signal (mono_thread_get_alt_suspend_signal () + 1);
394         return resume_signum;
395 #endif /* SIGRTMIN */
396 }
397
398
399 static int
400 mono_threads_get_abort_signal (void)
401 {
402 #if defined(PLATFORM_ANDROID)
403         return SIGTTIN;
404 #elif !defined (SIGRTMIN)
405 #ifdef SIGTTIN
406         return SIGTTIN;
407 #else
408         return -1;
409 #endif /* SIGRTMIN */
410 #else
411         static int abort_signum = -1;
412         if (abort_signum == -1)
413                 abort_signum = mono_thread_search_alt_signal (mono_thread_get_alt_resume_signal () + 1);
414         return abort_signum;
415 #endif /* SIGRTMIN */
416 }
417
418
419 #if !defined(__native_client__)
420 static void
421 restart_signal_handler (int _dummy, siginfo_t *_info, void *context)
422 {
423         MonoThreadInfo *info;
424         int old_errno = errno;
425
426         info = mono_thread_info_current ();
427         info->signal = restart_signal_num;
428         errno = old_errno;
429 }
430
431 static void
432 suspend_signal_handler (int _dummy, siginfo_t *info, void *context)
433 {
434         int old_errno = errno;
435         int hp_save_index = mono_hazard_pointer_save_for_signal_handler ();
436
437
438         MonoThreadInfo *current = mono_thread_info_current ();
439         gboolean ret;
440
441         THREADS_SUSPEND_DEBUG ("SIGNAL HANDLER FOR %p [%p]\n", current, (void*)current->native_handle);
442         if (current->syscall_break_signal) {
443                 current->syscall_break_signal = FALSE;
444                 THREADS_SUSPEND_DEBUG ("\tsyscall break for %p\n", current);
445                 mono_threads_notify_initiator_of_abort (current);
446                 goto done;
447         }
448
449         /* Have we raced with self suspend? */
450         if (!mono_threads_transition_finish_async_suspend (current)) {
451                 current->suspend_can_continue = TRUE;
452                 THREADS_SUSPEND_DEBUG ("\tlost race with self suspend %p\n", current);
453                 goto done;
454         }
455
456         ret = mono_threads_get_runtime_callbacks ()->thread_state_init_from_sigctx (&current->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX], context);
457
458         /* thread_state_init_from_sigctx return FALSE if the current thread is detaching and suspend can't continue. */
459         current->suspend_can_continue = ret;
460
461
462         /*
463         Block the restart signal.
464         We need to block the restart signal while posting to the suspend_ack semaphore or we race to sigsuspend,
465         which might miss the signal and get stuck.
466         */
467         pthread_sigmask (SIG_BLOCK, &suspend_ack_signal_mask, NULL);
468
469         /* We're done suspending */
470         mono_threads_notify_initiator_of_suspend (current);
471
472         /* This thread is doomed, all we can do is give up and let the suspender recover. */
473         if (!ret) {
474                 THREADS_SUSPEND_DEBUG ("\tThread is dying, failed to capture state %p\n", current);
475                 mono_threads_transition_async_suspend_compensation (current);
476                 /* Unblock the restart signal. */
477                 pthread_sigmask (SIG_UNBLOCK, &suspend_ack_signal_mask, NULL);
478
479                 goto done;
480         }
481
482         do {
483                 current->signal = 0;
484                 sigsuspend (&suspend_signal_mask);
485         } while (current->signal != restart_signal_num);
486
487         /* Unblock the restart signal. */
488         pthread_sigmask (SIG_UNBLOCK, &suspend_ack_signal_mask, NULL);
489
490         if (current->async_target) {
491 #if MONO_ARCH_HAS_MONO_CONTEXT
492                 MonoContext tmp = current->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX].ctx;
493                 mono_threads_get_runtime_callbacks ()->setup_async_callback (&tmp, current->async_target, current->user_data);
494                 current->async_target = current->user_data = NULL;
495                 mono_monoctx_to_sigctx (&tmp, context);
496 #else
497                 g_error ("The new interruption machinery requires a working mono-context");
498 #endif
499         }
500
501         /* We're done resuming */
502         mono_threads_notify_initiator_of_resume (current);
503
504 done:
505         mono_hazard_pointer_restore_for_signal_handler (hp_save_index);
506         errno = old_errno;
507 }
508
509 static void
510 abort_signal_handler (int _dummy, siginfo_t *info, void *context)
511 {
512         suspend_signal_handler (_dummy, info, context);
513 }
514
515 #endif
516
517 static void
518 mono_posix_add_signal_handler (int signo, gpointer handler, int flags)
519 {
520 #if !defined(__native_client__)
521         /*FIXME, move the code from mini to utils and do the right thing!*/
522         struct sigaction sa;
523         struct sigaction previous_sa;
524         int ret;
525
526         sa.sa_sigaction = handler;
527         sigfillset (&sa.sa_mask);
528
529         sa.sa_flags = SA_SIGINFO | flags;
530         ret = sigaction (signo, &sa, &previous_sa);
531
532         g_assert (ret != -1);
533 #endif
534 }
535
536 void
537 mono_threads_init_platform (void)
538 {
539         sigset_t signal_set;
540
541         abort_signal_num = mono_threads_get_abort_signal ();
542         if (mono_thread_info_unified_management_enabled ()) {
543                 suspend_signal_num = DEFAULT_SUSPEND_SIGNAL;
544                 restart_signal_num = DEFAULT_RESTART_SIGNAL;
545         } else {
546                 suspend_signal_num = mono_thread_get_alt_suspend_signal ();
547                 restart_signal_num = mono_thread_get_alt_resume_signal ();
548         }
549
550         sigfillset (&suspend_signal_mask);
551         sigdelset (&suspend_signal_mask, restart_signal_num);
552
553         sigemptyset (&suspend_ack_signal_mask);
554         sigaddset (&suspend_ack_signal_mask, restart_signal_num);
555
556         mono_posix_add_signal_handler (suspend_signal_num, suspend_signal_handler, SA_RESTART);
557         mono_posix_add_signal_handler (restart_signal_num, restart_signal_handler, SA_RESTART);
558         mono_posix_add_signal_handler (abort_signal_num, abort_signal_handler, 0);
559
560         /* ensure all the new signals are unblocked */
561         sigemptyset (&signal_set);
562         sigaddset (&signal_set, suspend_signal_num);
563         sigaddset (&signal_set, restart_signal_num);
564         sigaddset (&signal_set, abort_signal_num);
565         sigprocmask (SIG_UNBLOCK, &signal_set, NULL);
566 }
567
568 void
569 mono_threads_core_abort_syscall (MonoThreadInfo *info)
570 {
571         /*
572         We signal a thread to break it from the urrent syscall.
573         This signal should not be interpreted as a suspend request.
574         */
575         info->syscall_break_signal = TRUE;
576         if (!mono_threads_pthread_kill (info, abort_signal_num))
577                 mono_threads_add_to_pending_operation_set (info);
578 }
579
580 gboolean
581 mono_threads_core_needs_abort_syscall (void)
582 {
583         return TRUE;
584 }
585
586 gboolean
587 mono_threads_core_begin_async_suspend (MonoThreadInfo *info, gboolean interrupt_kernel)
588 {
589         int sig = interrupt_kernel ? abort_signal_num :  suspend_signal_num;
590
591         if (!mono_threads_pthread_kill (info, sig)) {
592                 mono_threads_add_to_pending_operation_set (info);
593                 return TRUE;
594         }
595         return FALSE;
596 }
597
598 gboolean
599 mono_threads_core_check_suspend_result (MonoThreadInfo *info)
600 {
601         return info->suspend_can_continue;
602 }
603
604 /*
605 This begins async resume. This function must do the following:
606
607 - Install an async target if one was requested.
608 - Notify the target to resume.
609 */
610 gboolean
611 mono_threads_core_begin_async_resume (MonoThreadInfo *info)
612 {
613         mono_threads_add_to_pending_operation_set (info);
614         return mono_threads_pthread_kill (info, restart_signal_num) == 0;
615 }
616
617 void
618 mono_threads_platform_register (MonoThreadInfo *info)
619 {
620 #if defined (PLATFORM_ANDROID)
621         info->native_handle = gettid ();
622 #endif
623 }
624
625 void
626 mono_threads_platform_free (MonoThreadInfo *info)
627 {
628 }
629
630 void
631 mono_threads_core_begin_global_suspend (void)
632 {
633 }
634
635 void
636 mono_threads_core_end_global_suspend (void)
637 {
638 }
639
640 #endif /*defined (USE_POSIX_BACKEND)*/
641
642 #endif