[runtime] Fix getting main thread's stack size with musl.
[mono.git] / mono / utils / mono-threads-linux.c
1 #include <config.h>
2
3 #if defined(__linux__) && !defined(PLATFORM_ANDROID)
4
5 #include <mono/utils/mono-threads.h>
6 #include <pthread.h>
7 #include <sys/syscall.h>
8 #include <sys/resource.h>
9 #include <sys/types.h>
10 #include <unistd.h>
11
12 void
13 mono_threads_core_get_stack_bounds (guint8 **staddr, size_t *stsize)
14 {
15         pthread_attr_t attr;
16
17         *staddr = NULL;
18         *stsize = (size_t)-1;
19
20         pthread_getattr_np (pthread_self (), &attr);
21         pthread_attr_getstack (&attr, (void**)staddr, stsize);
22         pthread_attr_destroy (&attr);
23
24         /*
25          * The pthread implementation of musl (and possibly others) does not
26          * return a useful stack size value for the main thread. It gives us
27          * a value like 139264 instead of 8388608 because it is reporting
28          * the currently-committed stack's size rather than the size it would
29          * have if the kernel were to commit the entire 8 MB stack.
30          *
31          * This is technically 'correct' in that, in extreme OOM situations,
32          * the kernel is not necessarily able to provide the full 8 MB stack.
33          * Realistically, in such a situation, nothing in Mono would work
34          * anyway...
35          *
36          * We work around this by getting the main thread's stack limit from
37          * getrlimit(2).
38          */
39         if (syscall (SYS_gettid) == getpid ()) {
40                 struct rlimit rlim;
41
42                 if (getrlimit (RLIMIT_STACK, &rlim) != -1 && rlim.rlim_cur != RLIM_INFINITY)
43                         *stsize = (size_t) rlim.rlim_cur;
44         }
45 }
46
47 #endif