Merge pull request #980 from StephenMcConnel/bug-18638
[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 #include <mono/utils/mono-compiler.h>
13 #include <mono/utils/mono-semaphore.h>
14 #include <mono/utils/mono-threads.h>
15 #include <mono/utils/mono-tls.h>
16 #include <mono/utils/mono-mmap.h>
17 #include <mono/metadata/threads-types.h>
18 #include <limits.h>
19
20 #include <errno.h>
21
22 #if defined(PLATFORM_ANDROID) && !defined(TARGET_ARM64)
23 #define USE_TKILL_ON_ANDROID 1
24 #endif
25
26 #ifdef USE_TKILL_ON_ANDROID
27 extern int tkill (pid_t tid, int signal);
28 #endif
29
30 #if defined(_POSIX_VERSION) || defined(__native_client__)
31 #include <sys/resource.h>
32 #include <signal.h>
33
34 #if defined(__native_client__)
35 void nacl_shutdown_gc_thread(void);
36 #endif
37
38 typedef struct {
39         void *(*start_routine)(void*);
40         void *arg;
41         int flags;
42         MonoSemType registered;
43         HANDLE handle;
44 } StartInfo;
45
46 #ifdef PLATFORM_ANDROID
47 static int no_interrupt_signo;
48 #endif
49
50 static void*
51 inner_start_thread (void *arg)
52 {
53         StartInfo *start_info = arg;
54         void *t_arg = start_info->arg;
55         int res;
56         void *(*start_func)(void*) = start_info->start_routine;
57         guint32 flags = start_info->flags;
58         void *result;
59         HANDLE handle;
60         MonoThreadInfo *info;
61
62         /* Register the thread with the io-layer */
63         handle = wapi_create_thread_handle ();
64         if (!handle) {
65                 res = MONO_SEM_POST (&(start_info->registered));
66                 g_assert (!res);
67                 return NULL;
68         }
69         start_info->handle = handle;
70
71         info = mono_thread_info_attach (&result);
72         info->runtime_thread = TRUE;
73         info->handle = handle;
74
75         if (flags & CREATE_SUSPENDED) {
76                 info->create_suspended = TRUE;
77                 MONO_SEM_INIT (&info->create_suspended_sem, 0);
78         }
79
80         /* start_info is not valid after this */
81         res = MONO_SEM_POST (&(start_info->registered));
82         g_assert (!res);
83         start_info = NULL;
84
85         if (flags & CREATE_SUSPENDED) {
86                 while (MONO_SEM_WAIT (&info->create_suspended_sem) != 0 &&
87                            errno == EINTR);
88                 MONO_SEM_DESTROY (&info->create_suspended_sem);
89         }
90
91         /* Run the actual main function of the thread */
92         result = start_func (t_arg);
93
94         /*
95         mono_thread_info_detach ();
96         */
97
98 #if defined(__native_client__)
99         nacl_shutdown_gc_thread();
100 #endif
101
102         wapi_thread_handle_set_exited (handle, GPOINTER_TO_UINT (result));
103         /* This is needed by mono_threads_core_unregister () which is called later */
104         info->handle = NULL;
105
106         g_assert (mono_threads_get_callbacks ()->thread_exit);
107         mono_threads_get_callbacks ()->thread_exit (NULL);
108         g_assert_not_reached ();
109         return result;
110 }
111
112 HANDLE
113 mono_threads_core_create_thread (LPTHREAD_START_ROUTINE start_routine, gpointer arg, guint32 stack_size, guint32 creation_flags, MonoNativeThreadId *out_tid)
114 {
115         pthread_attr_t attr;
116         int res;
117         pthread_t thread;
118         StartInfo start_info;
119
120         res = pthread_attr_init (&attr);
121         g_assert (!res);
122
123         if (stack_size == 0) {
124 #if HAVE_VALGRIND_MEMCHECK_H
125                 if (RUNNING_ON_VALGRIND)
126                         stack_size = 1 << 20;
127                 else
128                         stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
129 #else
130                 stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
131 #endif
132         }
133
134 #ifdef PTHREAD_STACK_MIN
135         if (stack_size < PTHREAD_STACK_MIN)
136                 stack_size = PTHREAD_STACK_MIN;
137 #endif
138
139 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
140         res = pthread_attr_setstacksize (&attr, stack_size);
141         g_assert (!res);
142 #endif
143
144         memset (&start_info, 0, sizeof (StartInfo));
145         start_info.start_routine = (gpointer)start_routine;
146         start_info.arg = arg;
147         start_info.flags = creation_flags;
148         MONO_SEM_INIT (&(start_info.registered), 0);
149
150         /* Actually start the thread */
151         res = mono_threads_get_callbacks ()->mono_gc_pthread_create (&thread, &attr, inner_start_thread, &start_info);
152         if (res) {
153                 MONO_SEM_DESTROY (&(start_info.registered));
154                 return NULL;
155         }
156
157         /* Wait until the thread register itself in various places */
158         while (MONO_SEM_WAIT (&(start_info.registered)) != 0) {
159                 /*if (EINTR != errno) ABORT("sem_wait failed"); */
160         }
161         MONO_SEM_DESTROY (&(start_info.registered));
162
163         if (out_tid)
164                 *out_tid = thread;
165
166         return start_info.handle;
167 }
168
169 /*
170  * mono_threads_core_resume_created:
171  *
172  *   Resume a newly created thread created using CREATE_SUSPENDED.
173  */
174 void
175 mono_threads_core_resume_created (MonoThreadInfo *info, MonoNativeThreadId tid)
176 {
177         MONO_SEM_POST (&info->create_suspended_sem);
178 }
179
180 gboolean
181 mono_threads_core_yield (void)
182 {
183         return sched_yield () == 0;
184 }
185
186 void
187 mono_threads_core_exit (int exit_code)
188 {
189         MonoThreadInfo *current = mono_thread_info_current ();
190
191 #if defined(__native_client__)
192         nacl_shutdown_gc_thread();
193 #endif
194
195         wapi_thread_handle_set_exited (current->handle, exit_code);
196
197         g_assert (mono_threads_get_callbacks ()->thread_exit);
198         mono_threads_get_callbacks ()->thread_exit (NULL);
199 }
200
201 void
202 mono_threads_core_unregister (MonoThreadInfo *info)
203 {
204         if (info->handle) {
205                 wapi_thread_handle_set_exited (info->handle, 0);
206                 info->handle = NULL;
207         }
208 }
209
210 HANDLE
211 mono_threads_core_open_handle (void)
212 {
213         MonoThreadInfo *info;
214
215         info = mono_thread_info_current ();
216         g_assert (info);
217
218         if (!info->handle)
219                 info->handle = wapi_create_thread_handle ();
220         else
221                 wapi_ref_thread_handle (info->handle);
222         return info->handle;
223 }
224
225 int
226 mono_threads_get_max_stack_size (void)
227 {
228         struct rlimit lim;
229
230         /* If getrlimit fails, we don't enforce any limits. */
231         if (getrlimit (RLIMIT_STACK, &lim))
232                 return INT_MAX;
233         /* rlim_t is an unsigned long long on 64bits OSX but we want an int response. */
234         if (lim.rlim_max > (rlim_t)INT_MAX)
235                 return INT_MAX;
236         return (int)lim.rlim_max;
237 }
238
239 HANDLE
240 mono_threads_core_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
241 {
242         wapi_ref_thread_handle (handle);
243
244         return handle;
245 }
246
247 gpointer
248 mono_threads_core_prepare_interrupt (HANDLE thread_handle)
249 {
250         return wapi_prepare_interrupt_thread (thread_handle);
251 }
252
253 void
254 mono_threads_core_finish_interrupt (gpointer wait_handle)
255 {
256         wapi_finish_interrupt_thread (wait_handle);
257 }
258
259 void
260 mono_threads_core_self_interrupt (void)
261 {
262         wapi_self_interrupt ();
263 }
264
265 void
266 mono_threads_core_clear_interruption (void)
267 {
268         wapi_clear_interruption ();
269 }
270
271 int
272 mono_threads_pthread_kill (MonoThreadInfo *info, int signum)
273 {
274 #ifdef USE_TKILL_ON_ANDROID
275         int result, old_errno = errno;
276         result = tkill (info->native_handle, signum);
277         if (result < 0) {
278                 result = errno;
279                 errno = old_errno;
280         }
281         return result;
282 #elif defined(__native_client__)
283         /* Workaround pthread_kill abort() in NaCl glibc. */
284         return 0;
285 #else
286         return pthread_kill (mono_thread_info_get_tid (info), signum);
287 #endif
288
289 }
290
291 #if !defined (__MACH__)
292
293 #if !defined(__native_client__)
294 static void
295 suspend_signal_handler (int _dummy, siginfo_t *info, void *context)
296 {
297         MonoThreadInfo *current = mono_thread_info_current ();
298         gboolean ret;
299         
300         if (current->syscall_break_signal) {
301                 current->syscall_break_signal = FALSE;
302                 return;
303         }
304
305         ret = mono_threads_get_runtime_callbacks ()->thread_state_init_from_sigctx (&current->suspend_state, context);
306
307         /* thread_state_init_from_sigctx return FALSE if the current thread is detaching and suspend can't continue. */
308         current->suspend_can_continue = ret;
309
310         MONO_SEM_POST (&current->begin_suspend_semaphore);
311
312         /* This thread is doomed, all we can do is give up and let the suspender recover. */
313         if (!ret)
314                 return;
315
316         while (MONO_SEM_WAIT (&current->resume_semaphore) != 0) {
317                 /*if (EINTR != errno) ABORT("sem_wait failed"); */
318         }
319
320         if (current->async_target) {
321 #if MONO_ARCH_HAS_MONO_CONTEXT
322                 MonoContext tmp = current->suspend_state.ctx;
323                 mono_threads_get_runtime_callbacks ()->setup_async_callback (&tmp, current->async_target, current->user_data);
324                 current->async_target = current->user_data = NULL;
325                 mono_monoctx_to_sigctx (&tmp, context);
326 #else
327                 g_error ("The new interruption machinery requires a working mono-context");
328 #endif
329         }
330
331         MONO_SEM_POST (&current->finish_resume_semaphore);
332 }
333 #endif
334
335 static void
336 mono_posix_add_signal_handler (int signo, gpointer handler, int flags)
337 {
338 #if !defined(__native_client__)
339         /*FIXME, move the code from mini to utils and do the right thing!*/
340         struct sigaction sa;
341         struct sigaction previous_sa;
342         int ret;
343
344         sa.sa_sigaction = handler;
345         sigemptyset (&sa.sa_mask);
346         sa.sa_flags = SA_SIGINFO | flags;
347         ret = sigaction (signo, &sa, &previous_sa);
348
349         g_assert (ret != -1);
350 #endif
351 }
352
353 void
354 mono_threads_init_platform (void)
355 {
356 #if !defined(__native_client__)
357         int abort_signo;
358
359         /*
360         FIXME we should use all macros from mini to make this more portable
361         FIXME it would be very sweet if sgen could end up using this too.
362         */
363         if (!mono_thread_info_new_interrupt_enabled ())
364                 return;
365         abort_signo = mono_thread_get_abort_signal ();
366         mono_posix_add_signal_handler (abort_signo, suspend_signal_handler, 0);
367
368 #ifdef PLATFORM_ANDROID
369         /*
370          * Lots of android native code can't handle the EINTR caused by
371          * the normal abort signal, so use a different signal for the
372          * no interruption case, which is used by sdb.
373          * FIXME: Use this on all platforms.
374          * SIGUSR1 is used by dalvik/art.
375          */
376         no_interrupt_signo = SIGWINCH;
377         g_assert (abort_signo != no_interrupt_signo);
378         mono_posix_add_signal_handler (no_interrupt_signo, suspend_signal_handler, SA_RESTART);
379 #endif
380 #endif
381 }
382
383 void
384 mono_threads_core_interrupt (MonoThreadInfo *info)
385 {
386         /* Handled in mono_threads_core_suspend () */
387 }
388
389 void
390 mono_threads_core_abort_syscall (MonoThreadInfo *info)
391 {
392         /*
393         We signal a thread to break it from the urrent syscall.
394         This signal should not be interpreted as a suspend request.
395         */
396         info->syscall_break_signal = TRUE;
397         mono_threads_pthread_kill (info, mono_thread_get_abort_signal ());
398 }
399
400 gboolean
401 mono_threads_core_needs_abort_syscall (void)
402 {
403         return TRUE;
404 }
405
406 gboolean
407 mono_threads_core_suspend (MonoThreadInfo *info, gboolean interrupt_kernel)
408 {
409         /*FIXME, check return value*/
410 #ifdef PLATFORM_ANDROID
411         if (!interrupt_kernel)
412                 mono_threads_pthread_kill (info, no_interrupt_signo);
413         else
414                 mono_threads_pthread_kill (info, mono_thread_get_abort_signal ());
415 #else
416                 mono_threads_pthread_kill (info, mono_thread_get_abort_signal ());
417 #endif
418         while (MONO_SEM_WAIT (&info->begin_suspend_semaphore) != 0) {
419                 /* g_assert (errno == EINTR); */
420         }
421         return info->suspend_can_continue;
422 }
423
424 gboolean
425 mono_threads_core_resume (MonoThreadInfo *info)
426 {
427         MONO_SEM_POST (&info->resume_semaphore);
428         while (MONO_SEM_WAIT (&info->finish_resume_semaphore) != 0) {
429                 /* g_assert (errno == EINTR); */
430         }
431
432         return TRUE;
433 }
434
435 void
436 mono_threads_platform_register (MonoThreadInfo *info)
437 {
438         MONO_SEM_INIT (&info->begin_suspend_semaphore, 0);
439
440 #if defined (PLATFORM_ANDROID)
441         info->native_handle = gettid ();
442 #endif
443 }
444
445 void
446 mono_threads_platform_free (MonoThreadInfo *info)
447 {
448         MONO_SEM_DESTROY (&info->begin_suspend_semaphore);
449 }
450
451 MonoNativeThreadId
452 mono_native_thread_id_get (void)
453 {
454         return pthread_self ();
455 }
456
457 gboolean
458 mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2)
459 {
460         return pthread_equal (id1, id2);
461 }
462
463 /*
464  * mono_native_thread_create:
465  *
466  *   Low level thread creation function without any GC wrappers.
467  */
468 gboolean
469 mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg)
470 {
471         return pthread_create (tid, NULL, func, arg) == 0;
472 }
473
474 void
475 mono_threads_core_set_name (MonoNativeThreadId tid, const char *name)
476 {
477 #ifdef HAVE_PTHREAD_SETNAME_NP
478         if (!name) {
479                 pthread_setname_np (tid, "");
480         } else {
481                 char n [16];
482
483                 strncpy (n, name, 16);
484                 n [15] = '\0';
485                 pthread_setname_np (tid, n);
486         }
487 #endif
488 }
489
490 #endif /*!defined (__MACH__)*/
491
492 #endif