Merge pull request #1843 from info-lvsys/patch-1
[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         MONO_TRY_BLOCKING;
149         /* Wait until the thread register itself in various places */
150         while (MONO_SEM_WAIT (&(start_info.registered)) != 0) {
151                 /*if (EINTR != errno) ABORT("sem_wait failed"); */
152         }
153         MONO_FINISH_TRY_BLOCKING;
154
155         MONO_SEM_DESTROY (&(start_info.registered));
156
157         if (out_tid)
158                 *out_tid = thread;
159
160         return start_info.handle;
161 }
162
163 /*
164  * mono_threads_core_resume_created:
165  *
166  *   Resume a newly created thread created using CREATE_SUSPENDED.
167  */
168 void
169 mono_threads_core_resume_created (MonoThreadInfo *info, MonoNativeThreadId tid)
170 {
171         MONO_SEM_POST (&info->create_suspended_sem);
172 }
173
174 gboolean
175 mono_threads_core_yield (void)
176 {
177         return sched_yield () == 0;
178 }
179
180 void
181 mono_threads_core_exit (int exit_code)
182 {
183         MonoThreadInfo *current = mono_thread_info_current ();
184
185 #if defined(__native_client__)
186         nacl_shutdown_gc_thread();
187 #endif
188
189         wapi_thread_handle_set_exited (current->handle, exit_code);
190
191         mono_thread_info_detach ();
192
193         pthread_exit (NULL);
194 }
195
196 void
197 mono_threads_core_unregister (MonoThreadInfo *info)
198 {
199         if (info->handle) {
200                 wapi_thread_handle_set_exited (info->handle, 0);
201                 info->handle = NULL;
202         }
203 }
204
205 HANDLE
206 mono_threads_core_open_handle (void)
207 {
208         MonoThreadInfo *info;
209
210         info = mono_thread_info_current ();
211         g_assert (info);
212
213         if (!info->handle)
214                 info->handle = wapi_create_thread_handle ();
215         else
216                 wapi_ref_thread_handle (info->handle);
217         return info->handle;
218 }
219
220 int
221 mono_threads_get_max_stack_size (void)
222 {
223         struct rlimit lim;
224
225         /* If getrlimit fails, we don't enforce any limits. */
226         if (getrlimit (RLIMIT_STACK, &lim))
227                 return INT_MAX;
228         /* rlim_t is an unsigned long long on 64bits OSX but we want an int response. */
229         if (lim.rlim_max > (rlim_t)INT_MAX)
230                 return INT_MAX;
231         return (int)lim.rlim_max;
232 }
233
234 HANDLE
235 mono_threads_core_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
236 {
237         wapi_ref_thread_handle (handle);
238
239         return handle;
240 }
241
242 int
243 mono_threads_pthread_kill (MonoThreadInfo *info, int signum)
244 {
245         THREADS_SUSPEND_DEBUG ("sending signal %d to %p[%p]\n", signum, info, mono_thread_info_get_tid (info));
246 #ifdef USE_TKILL_ON_ANDROID
247         int result, old_errno = errno;
248         result = tkill (info->native_handle, signum);
249         if (result < 0) {
250                 result = errno;
251                 errno = old_errno;
252         }
253         return result;
254 #elif defined(__native_client__)
255         /* Workaround pthread_kill abort() in NaCl glibc. */
256         return 0;
257 #elif !defined(HAVE_PTHREAD_KILL)
258         g_error ("pthread_kill() is not supported by this platform");
259 #else
260         return pthread_kill (mono_thread_info_get_tid (info), signum);
261 #endif
262 }
263
264 MonoNativeThreadId
265 mono_native_thread_id_get (void)
266 {
267         return pthread_self ();
268 }
269
270 gboolean
271 mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2)
272 {
273         return pthread_equal (id1, id2);
274 }
275
276 /*
277  * mono_native_thread_create:
278  *
279  *   Low level thread creation function without any GC wrappers.
280  */
281 gboolean
282 mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg)
283 {
284         return pthread_create (tid, NULL, (void *(*)(void *)) func, arg) == 0;
285 }
286
287 void
288 mono_threads_core_set_name (MonoNativeThreadId tid, const char *name)
289 {
290 #if defined (HAVE_PTHREAD_SETNAME_NP) && !defined (__MACH__)
291         if (!name) {
292                 pthread_setname_np (tid, "");
293         } else {
294                 char n [16];
295
296                 strncpy (n, name, 16);
297                 n [15] = '\0';
298                 pthread_setname_np (tid, n);
299         }
300 #endif
301 }
302
303
304 #if defined (USE_POSIX_BACKEND) && !defined (USE_COOP_GC)
305
306 static int suspend_signal_num;
307 static int restart_signal_num;
308 static int abort_signal_num;
309 static sigset_t suspend_signal_mask;
310 static sigset_t suspend_ack_signal_mask;
311
312
313 #if defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
314 #define DEFAULT_SUSPEND_SIGNAL SIGXFSZ
315 #else
316 #define DEFAULT_SUSPEND_SIGNAL SIGPWR
317 #endif
318 #define DEFAULT_RESTART_SIGNAL SIGXCPU
319
320 static int
321 mono_thread_search_alt_signal (int min_signal)
322 {
323 #if !defined (SIGRTMIN)
324         g_error ("signal search only works with RTMIN");
325 #else
326         int i;
327         /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
328         for (i = MAX (min_signal, SIGRTMIN) + 1; i < SIGRTMAX; ++i) {
329                 struct sigaction sinfo;
330                 sigaction (i, NULL, &sinfo);
331                 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
332                         return i;
333                 }
334         }
335         g_error ("Could not find an available signal");
336 #endif
337 }
338
339 static int
340 mono_thread_get_alt_suspend_signal (void)
341 {
342 #if defined(PLATFORM_ANDROID)
343         return SIGUNUSED;
344 #elif !defined (SIGRTMIN)
345 #ifdef SIGUSR1
346         return SIGUSR1;
347 #else
348         return -1;
349 #endif /* SIGUSR1 */
350 #else
351         static int suspend_signum = -1;
352         if (suspend_signum == -1)
353                 suspend_signum = mono_thread_search_alt_signal (-1);
354         return suspend_signum;
355 #endif /* SIGRTMIN */
356 }
357
358 static int
359 mono_thread_get_alt_resume_signal (void)
360 {
361 #if defined(PLATFORM_ANDROID)
362         return SIGTTOU;
363 #elif !defined (SIGRTMIN)
364 #ifdef SIGUSR2
365         return SIGUSR2;
366 #else
367         return -1;
368 #endif /* SIGUSR1 */
369 #else
370         static int resume_signum = -1;
371         if (resume_signum == -1)
372                 resume_signum = mono_thread_search_alt_signal (mono_thread_get_alt_suspend_signal () + 1);
373         return resume_signum;
374 #endif /* SIGRTMIN */
375 }
376
377
378 static int
379 mono_threads_get_abort_signal (void)
380 {
381 #if defined(PLATFORM_ANDROID)
382         return SIGTTIN;
383 #elif !defined (SIGRTMIN)
384 #ifdef SIGTTIN
385         return SIGTTIN;
386 #else
387         return -1;
388 #endif /* SIGRTMIN */
389 #else
390         static int abort_signum = -1;
391         if (abort_signum == -1)
392                 abort_signum = mono_thread_search_alt_signal (mono_thread_get_alt_resume_signal () + 1);
393         return abort_signum;
394 #endif /* SIGRTMIN */
395 }
396
397
398 #if !defined(__native_client__)
399 static void
400 restart_signal_handler (int _dummy, siginfo_t *_info, void *context)
401 {
402         MonoThreadInfo *info;
403         int old_errno = errno;
404
405         info = mono_thread_info_current ();
406         info->signal = restart_signal_num;
407         errno = old_errno;
408 }
409
410 static void
411 suspend_signal_handler (int _dummy, siginfo_t *info, void *context)
412 {
413         int old_errno = errno;
414         int hp_save_index = mono_hazard_pointer_save_for_signal_handler ();
415
416
417         MonoThreadInfo *current = mono_thread_info_current ();
418         gboolean ret;
419
420         THREADS_SUSPEND_DEBUG ("SIGNAL HANDLER FOR %p [%p]\n", current, (void*)current->native_handle);
421         if (current->syscall_break_signal) {
422                 current->syscall_break_signal = FALSE;
423                 THREADS_SUSPEND_DEBUG ("\tsyscall break for %p\n", current);
424                 mono_threads_notify_initiator_of_abort (current);
425                 goto done;
426         }
427
428         /* Have we raced with self suspend? */
429         if (!mono_threads_transition_finish_async_suspend (current)) {
430                 current->suspend_can_continue = TRUE;
431                 THREADS_SUSPEND_DEBUG ("\tlost race with self suspend %p\n", current);
432                 goto done;
433         }
434
435         ret = mono_threads_get_runtime_callbacks ()->thread_state_init_from_sigctx (&current->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX], context);
436
437         /* thread_state_init_from_sigctx return FALSE if the current thread is detaching and suspend can't continue. */
438         current->suspend_can_continue = ret;
439
440
441         /*
442         Block the restart signal.
443         We need to block the restart signal while posting to the suspend_ack semaphore or we race to sigsuspend,
444         which might miss the signal and get stuck.
445         */
446         pthread_sigmask (SIG_BLOCK, &suspend_ack_signal_mask, NULL);
447
448         /* We're done suspending */
449         mono_threads_notify_initiator_of_suspend (current);
450
451         /* This thread is doomed, all we can do is give up and let the suspender recover. */
452         if (!ret) {
453                 THREADS_SUSPEND_DEBUG ("\tThread is dying, failed to capture state %p\n", current);
454                 mono_threads_transition_async_suspend_compensation (current);
455                 /* Unblock the restart signal. */
456                 pthread_sigmask (SIG_UNBLOCK, &suspend_ack_signal_mask, NULL);
457
458                 goto done;
459         }
460
461         do {
462                 current->signal = 0;
463                 sigsuspend (&suspend_signal_mask);
464         } while (current->signal != restart_signal_num);
465
466         /* Unblock the restart signal. */
467         pthread_sigmask (SIG_UNBLOCK, &suspend_ack_signal_mask, NULL);
468
469         if (current->async_target) {
470 #if MONO_ARCH_HAS_MONO_CONTEXT
471                 MonoContext tmp = current->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX].ctx;
472                 mono_threads_get_runtime_callbacks ()->setup_async_callback (&tmp, current->async_target, current->user_data);
473                 current->async_target = current->user_data = NULL;
474                 mono_monoctx_to_sigctx (&tmp, context);
475 #else
476                 g_error ("The new interruption machinery requires a working mono-context");
477 #endif
478         }
479
480         /* We're done resuming */
481         mono_threads_notify_initiator_of_resume (current);
482
483 done:
484         mono_hazard_pointer_restore_for_signal_handler (hp_save_index);
485         errno = old_errno;
486 }
487
488 static void
489 abort_signal_handler (int _dummy, siginfo_t *info, void *context)
490 {
491         suspend_signal_handler (_dummy, info, context);
492 }
493
494 #endif
495
496 static void
497 mono_posix_add_signal_handler (int signo, gpointer handler, int flags)
498 {
499 #if !defined(__native_client__)
500         /*FIXME, move the code from mini to utils and do the right thing!*/
501         struct sigaction sa;
502         struct sigaction previous_sa;
503         int ret;
504
505         sa.sa_sigaction = handler;
506         sigfillset (&sa.sa_mask);
507
508         sa.sa_flags = SA_SIGINFO | flags;
509         ret = sigaction (signo, &sa, &previous_sa);
510
511         g_assert (ret != -1);
512 #endif
513 }
514
515 void
516 mono_threads_init_platform (void)
517 {
518         sigset_t signal_set;
519
520         abort_signal_num = mono_threads_get_abort_signal ();
521         if (mono_thread_info_unified_management_enabled ()) {
522                 suspend_signal_num = DEFAULT_SUSPEND_SIGNAL;
523                 restart_signal_num = DEFAULT_RESTART_SIGNAL;
524         } else {
525                 suspend_signal_num = mono_thread_get_alt_suspend_signal ();
526                 restart_signal_num = mono_thread_get_alt_resume_signal ();
527         }
528
529         sigfillset (&suspend_signal_mask);
530         sigdelset (&suspend_signal_mask, restart_signal_num);
531
532         sigemptyset (&suspend_ack_signal_mask);
533         sigaddset (&suspend_ack_signal_mask, restart_signal_num);
534
535         mono_posix_add_signal_handler (suspend_signal_num, suspend_signal_handler, SA_RESTART);
536         mono_posix_add_signal_handler (restart_signal_num, restart_signal_handler, SA_RESTART);
537         mono_posix_add_signal_handler (abort_signal_num, abort_signal_handler, 0);
538
539         /* ensure all the new signals are unblocked */
540         sigemptyset (&signal_set);
541         sigaddset (&signal_set, suspend_signal_num);
542         sigaddset (&signal_set, restart_signal_num);
543         sigaddset (&signal_set, abort_signal_num);
544         sigprocmask (SIG_UNBLOCK, &signal_set, NULL);
545 }
546
547 void
548 mono_threads_core_abort_syscall (MonoThreadInfo *info)
549 {
550         /*
551         We signal a thread to break it from the urrent syscall.
552         This signal should not be interpreted as a suspend request.
553         */
554         info->syscall_break_signal = TRUE;
555         if (!mono_threads_pthread_kill (info, abort_signal_num))
556                 mono_threads_add_to_pending_operation_set (info);
557 }
558
559 gboolean
560 mono_threads_core_needs_abort_syscall (void)
561 {
562         return TRUE;
563 }
564
565 gboolean
566 mono_threads_core_begin_async_suspend (MonoThreadInfo *info, gboolean interrupt_kernel)
567 {
568         int sig = interrupt_kernel ? abort_signal_num :  suspend_signal_num;
569
570         if (!mono_threads_pthread_kill (info, sig)) {
571                 mono_threads_add_to_pending_operation_set (info);
572                 return TRUE;
573         }
574         return FALSE;
575 }
576
577 gboolean
578 mono_threads_core_check_suspend_result (MonoThreadInfo *info)
579 {
580         return info->suspend_can_continue;
581 }
582
583 /*
584 This begins async resume. This function must do the following:
585
586 - Install an async target if one was requested.
587 - Notify the target to resume.
588 */
589 gboolean
590 mono_threads_core_begin_async_resume (MonoThreadInfo *info)
591 {
592         mono_threads_add_to_pending_operation_set (info);
593         return mono_threads_pthread_kill (info, restart_signal_num) == 0;
594 }
595
596 void
597 mono_threads_platform_register (MonoThreadInfo *info)
598 {
599 #if defined (PLATFORM_ANDROID)
600         info->native_handle = gettid ();
601 #endif
602 }
603
604 void
605 mono_threads_platform_free (MonoThreadInfo *info)
606 {
607 }
608
609 void
610 mono_threads_core_begin_global_suspend (void)
611 {
612 }
613
614 void
615 mono_threads_core_end_global_suspend (void)
616 {
617 }
618
619 #endif /*defined (USE_POSIX_BACKEND)*/
620
621 #endif