Merge pull request #3686 from lambdageek/dev-format-printf
[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-threads.h>
18 #include <mono/utils/mono-threads-posix-signals.h>
19 #include <mono/utils/mono-coop-semaphore.h>
20 #include <mono/metadata/gc-internals.h>
21 #include <mono/utils/w32handle.h>
22
23 #include <errno.h>
24
25 #if defined(PLATFORM_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
26 #define USE_TKILL_ON_ANDROID 1
27 #endif
28
29 #ifdef USE_TKILL_ON_ANDROID
30 extern int tkill (pid_t tid, int signal);
31 #endif
32
33 #if defined(_POSIX_VERSION) || defined(__native_client__)
34
35 #include <pthread.h>
36
37 #include <sys/resource.h>
38
39 #if defined(__native_client__)
40 void nacl_shutdown_gc_thread(void);
41 #endif
42
43 void
44 mono_threads_platform_register (MonoThreadInfo *info)
45 {
46         gpointer thread_handle;
47
48         thread_handle = mono_w32handle_new (MONO_W32HANDLE_THREAD, NULL);
49         if (thread_handle == INVALID_HANDLE_VALUE)
50                 g_error ("%s: failed to create handle", __func__);
51
52         g_assert (!info->handle);
53         info->handle = thread_handle;
54 }
55
56 int
57 mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize stack_size, MonoNativeThreadId *out_tid)
58 {
59         pthread_attr_t attr;
60         pthread_t thread;
61         int policy;
62         struct sched_param param;
63         gint res;
64
65         res = pthread_attr_init (&attr);
66         g_assert (!res);
67
68 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
69         if (stack_size == 0) {
70 #if HAVE_VALGRIND_MEMCHECK_H
71                 if (RUNNING_ON_VALGRIND)
72                         stack_size = 1 << 20;
73                 else
74                         stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
75 #else
76                 stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
77 #endif
78         }
79
80 #ifdef PTHREAD_STACK_MIN
81         if (stack_size < PTHREAD_STACK_MIN)
82                 stack_size = PTHREAD_STACK_MIN;
83 #endif
84
85         res = pthread_attr_setstacksize (&attr, stack_size);
86         g_assert (!res);
87 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
88
89         memset (&param, 0, sizeof (param));
90
91         res = pthread_attr_getschedpolicy (&attr, &policy);
92         if (res != 0)
93                 g_error ("%s: pthread_attr_getschedpolicy failed, error: \"%s\" (%d)", g_strerror (res), res);
94
95 #ifdef _POSIX_PRIORITY_SCHEDULING
96         int max, min;
97
98         /* Necessary to get valid priority range */
99
100         min = sched_get_priority_min (policy);
101         max = sched_get_priority_max (policy);
102
103         if (max > 0 && min >= 0 && max > min)
104                 param.sched_priority = (max - min) / 2 + min;
105         else
106 #endif
107         {
108                 switch (policy) {
109                 case SCHED_FIFO:
110                 case SCHED_RR:
111                         param.sched_priority = 50;
112                         break;
113 #ifdef SCHED_BATCH
114                 case SCHED_BATCH:
115 #endif
116                 case SCHED_OTHER:
117                         param.sched_priority = 0;
118                         break;
119                 default:
120                         g_error ("%s: unknown policy %d", __func__, policy);
121                 }
122         }
123
124         res = pthread_attr_setschedparam (&attr, &param);
125         if (res != 0)
126                 g_error ("%s: pthread_attr_setschedparam failed, error: \"%s\" (%d)", g_strerror (res), res);
127
128         /* Actually start the thread */
129         res = mono_gc_pthread_create (&thread, &attr, (gpointer (*)(gpointer)) thread_fn, thread_data);
130         if (res)
131                 return -1;
132
133         if (out_tid)
134                 *out_tid = thread;
135
136         return 0;
137 }
138
139 gboolean
140 mono_threads_platform_yield (void)
141 {
142         return sched_yield () == 0;
143 }
144
145 void
146 mono_threads_platform_exit (int exit_code)
147 {
148 #if defined(__native_client__)
149         nacl_shutdown_gc_thread();
150 #endif
151
152         mono_thread_info_detach ();
153
154         pthread_exit (NULL);
155 }
156
157 void
158 mono_threads_platform_unregister (MonoThreadInfo *info)
159 {
160         g_assert (info->handle);
161
162         /* The thread is no longer active, so unref it */
163         mono_w32handle_unref (info->handle);
164         info->handle = NULL;
165 }
166
167 int
168 mono_threads_get_max_stack_size (void)
169 {
170         struct rlimit lim;
171
172         /* If getrlimit fails, we don't enforce any limits. */
173         if (getrlimit (RLIMIT_STACK, &lim))
174                 return INT_MAX;
175         /* rlim_t is an unsigned long long on 64bits OSX but we want an int response. */
176         if (lim.rlim_max > (rlim_t)INT_MAX)
177                 return INT_MAX;
178         return (int)lim.rlim_max;
179 }
180
181 gpointer
182 mono_threads_platform_duplicate_handle (MonoThreadInfo *info)
183 {
184         g_assert (info->handle);
185         mono_w32handle_ref (info->handle);
186         return info->handle;
187 }
188
189 HANDLE
190 mono_threads_platform_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
191 {
192         mono_w32handle_ref (handle);
193
194         return handle;
195 }
196
197 void
198 mono_threads_platform_close_thread_handle (HANDLE handle)
199 {
200         mono_w32handle_unref (handle);
201 }
202
203 int
204 mono_threads_pthread_kill (MonoThreadInfo *info, int signum)
205 {
206         THREADS_SUSPEND_DEBUG ("sending signal %d to %p[%p]\n", signum, info, mono_thread_info_get_tid (info));
207 #ifdef USE_TKILL_ON_ANDROID
208         int result, old_errno = errno;
209         result = tkill (info->native_handle, signum);
210         if (result < 0) {
211                 result = errno;
212                 errno = old_errno;
213         }
214         return result;
215 #elif defined(__native_client__)
216         /* Workaround pthread_kill abort() in NaCl glibc. */
217         return 0;
218 #elif !defined(HAVE_PTHREAD_KILL)
219         g_error ("pthread_kill() is not supported by this platform");
220 #else
221         return pthread_kill (mono_thread_info_get_tid (info), signum);
222 #endif
223 }
224
225 MonoNativeThreadId
226 mono_native_thread_id_get (void)
227 {
228         return pthread_self ();
229 }
230
231 gboolean
232 mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2)
233 {
234         return pthread_equal (id1, id2);
235 }
236
237 /*
238  * mono_native_thread_create:
239  *
240  *   Low level thread creation function without any GC wrappers.
241  */
242 gboolean
243 mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg)
244 {
245         return pthread_create (tid, NULL, (void *(*)(void *)) func, arg) == 0;
246 }
247
248 void
249 mono_native_thread_set_name (MonoNativeThreadId tid, const char *name)
250 {
251 #ifdef __MACH__
252         /*
253          * We can't set the thread name for other threads, but we can at least make
254          * it work for threads that try to change their own name.
255          */
256         if (tid != mono_native_thread_id_get ())
257                 return;
258
259         if (!name) {
260                 pthread_setname_np ("");
261         } else {
262                 char n [63];
263
264                 strncpy (n, name, 63);
265                 n [62] = '\0';
266                 pthread_setname_np (n);
267         }
268 #elif defined (__NetBSD__)
269         if (!name) {
270                 pthread_setname_np (tid, "%s", (void*)"");
271         } else {
272                 char n [PTHREAD_MAX_NAMELEN_NP];
273
274                 strncpy (n, name, PTHREAD_MAX_NAMELEN_NP);
275                 n [PTHREAD_MAX_NAMELEN_NP - 1] = '\0';
276                 pthread_setname_np (tid, "%s", (void*)n);
277         }
278 #elif defined (HAVE_PTHREAD_SETNAME_NP)
279         if (!name) {
280                 pthread_setname_np (tid, "");
281         } else {
282                 char n [16];
283
284                 strncpy (n, name, 16);
285                 n [15] = '\0';
286                 pthread_setname_np (tid, n);
287         }
288 #endif
289 }
290
291 gboolean
292 mono_native_thread_join (MonoNativeThreadId tid)
293 {
294         void *res;
295
296         return !pthread_join (tid, &res);
297 }
298
299 void
300 mono_threads_platform_set_exited (gpointer handle)
301 {
302         int thr_ret;
303
304         g_assert (handle);
305         if (mono_w32handle_issignalled (handle))
306                 g_error ("%s: handle %p thread %p has already exited, it's handle is signalled", __func__, handle, mono_native_thread_id_get ());
307         if (mono_w32handle_get_type (handle) == MONO_W32HANDLE_UNUSED)
308                 g_error ("%s: handle %p thread %p has already exited, it's handle type is 'unused'", __func__, handle, mono_native_thread_id_get ());
309
310         thr_ret = mono_w32handle_lock_handle (handle);
311         g_assert (thr_ret == 0);
312
313         mono_w32handle_set_signal_state (handle, TRUE, TRUE);
314
315         thr_ret = mono_w32handle_unlock_handle (handle);
316         g_assert (thr_ret == 0);
317 }
318
319 static const gchar* thread_typename (void)
320 {
321         return "Thread";
322 }
323
324 static gsize thread_typesize (void)
325 {
326         return 0;
327 }
328
329 static MonoW32HandleOps thread_ops = {
330         NULL,                           /* close */
331         NULL,                           /* signal */
332         NULL,                           /* own */
333         NULL,                           /* is_owned */
334         NULL,                           /* special_wait */
335         NULL,                           /* prewait */
336         NULL,                           /* details */
337         thread_typename,        /* typename */
338         thread_typesize,        /* typesize */
339 };
340
341 void
342 mono_threads_platform_init (void)
343 {
344         mono_w32handle_register_ops (MONO_W32HANDLE_THREAD, &thread_ops);
345
346         mono_w32handle_register_capabilities (MONO_W32HANDLE_THREAD, MONO_W32HANDLE_CAP_WAIT);
347 }
348
349 #endif /* defined(_POSIX_VERSION) || defined(__native_client__) */
350
351 #if defined(USE_POSIX_BACKEND)
352
353 gboolean
354 mono_threads_suspend_begin_async_suspend (MonoThreadInfo *info, gboolean interrupt_kernel)
355 {
356         int sig = interrupt_kernel ? mono_threads_posix_get_abort_signal () :  mono_threads_posix_get_suspend_signal ();
357
358         if (!mono_threads_pthread_kill (info, sig)) {
359                 mono_threads_add_to_pending_operation_set (info);
360                 return TRUE;
361         }
362         return FALSE;
363 }
364
365 gboolean
366 mono_threads_suspend_check_suspend_result (MonoThreadInfo *info)
367 {
368         return info->suspend_can_continue;
369 }
370
371 /*
372 This begins async resume. This function must do the following:
373
374 - Install an async target if one was requested.
375 - Notify the target to resume.
376 */
377 gboolean
378 mono_threads_suspend_begin_async_resume (MonoThreadInfo *info)
379 {
380         mono_threads_add_to_pending_operation_set (info);
381         return mono_threads_pthread_kill (info, mono_threads_posix_get_restart_signal ()) == 0;
382 }
383
384 void
385 mono_threads_suspend_register (MonoThreadInfo *info)
386 {
387 #if defined (PLATFORM_ANDROID)
388         info->native_handle = gettid ();
389 #endif
390 }
391
392 void
393 mono_threads_suspend_free (MonoThreadInfo *info)
394 {
395 }
396
397 void
398 mono_threads_suspend_init (void)
399 {
400         mono_threads_posix_init_signals (MONO_THREADS_POSIX_INIT_SIGNALS_SUSPEND_RESTART);
401 }
402
403 #endif /* defined(USE_POSIX_BACKEND) */