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