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