Jit: Don't use a second stack

This second stack leads to JNI problems on Android, because ART fetches
the address and size of the original stack using pthread functions
(see GetThreadStack in art/runtime/thread.cc), and (presumably) treats
stack addresses outside of the original stack as invalid. (What I don't
understand is why some JNI operations on the CPU thread work fine
despite this but others don't.)

Instead of creating a second stack, let's borrow the approach ART uses:
Use pthread functions to find out the stack's address and size, then
install guard pages at an appropriate location. This lets us get rid
of a workaround we had in the MsgAlert function.

Because we're no longer choosing the stack size ourselves, I've made some
tweaks to where the put the guard pages. Previously we had a stack of
2 MiB and a safe zone of 512 KiB. We now accept stacks as small as 512 KiB
(used on macOS) and use a safe zone of 256 KiB. I feel like this should
be fine, but haven't done much testing beyond "it seems to work".

By the way, on Windows it was already the case that we didn't create
a second stack... But there was a bug in the implementation!
The code for protecting the stack has to run on the CPU thread, since
it's the CPU thread's stack we want to protect, but it was actually
running on EmuThread. This commit fixes that, since now this bug
matters on other operating systems too.
This commit is contained in:
JosJuice
2023-01-01 20:18:03 +01:00
parent 0cdae98181
commit 86c1f6e1e7
10 changed files with 203 additions and 121 deletions

View File

@ -7,6 +7,7 @@
#include <Windows.h>
#include <processthreadsapi.h>
#else
#include <pthread.h>
#include <unistd.h>
#endif
@ -185,6 +186,41 @@ void SetCurrentThreadName(const char* name)
#endif
}
std::tuple<void*, size_t> GetCurrentThreadStack()
{
void* stack_addr;
size_t stack_size;
pthread_t self = pthread_self();
#ifdef __APPLE__
stack_size = pthread_get_stacksize_np(self);
stack_addr = reinterpret_cast<u8*>(pthread_get_stackaddr_np(self)) - stack_size;
#elif defined __OpenBSD__
stack_t stack;
pthread_stackseg_np(self, &stack);
stack_addr = reinterpret_cast<u8*>(stack->ss_sp) - stack->ss_size;
stack_size = stack->ss_size;
#else
pthread_attr_t attr;
#ifdef __FreeBSD__
pthread_attr_init(&attr);
pthread_attr_get_np(self, &attr);
#else
// Linux and NetBSD
pthread_getattr_np(self, &attr);
#endif
pthread_attr_getstack(&attr, &stack_addr, &stack_size);
pthread_attr_destroy(&attr);
#endif
return std::make_tuple(stack_addr, stack_size);
}
#endif
} // namespace Common