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