diff --git a/ext/ffi_c/ClosurePool.c b/ext/ffi_c/ClosurePool.c index 5499b40..66d31d9 100644 --- a/ext/ffi_c/ClosurePool.c +++ b/ext/ffi_c/ClosurePool.c @@ -57,6 +57,7 @@ #include #include "rbffi.h" #include "compat.h" +#include "emutramp.h" #include "Function.h" #include "Types.h" @@ -271,7 +272,10 @@ protectPage(void* page) DWORD oldProtect; return VirtualProtect(page, pageSize, PAGE_EXECUTE_READ, &oldProtect); #else - return mprotect(page, pageSize, PROT_READ | PROT_EXEC) == 0; + int prot = PROT_READ | PROT_EXEC; + if (is_emutramp_enabled ()) + prot &= ~PROT_EXEC; + return mprotect(page, pageSize, prot) == 0; #endif } diff --git a/ext/ffi_c/emutramp.h b/ext/ffi_c/emutramp.h new file mode 100644 index 0000000..a38efee --- /dev/null +++ b/ext/ffi_c/emutramp.h @@ -0,0 +1,46 @@ +/* On PaX enable kernels that have MPROTECT enable we can't use PROT_EXEC. + + This is, apparently, an undocumented change to ffi_prep_closure(): + depending on the Linux kernel we're running on, we must give it a + mmap that is either PROT_READ|PROT_WRITE|PROT_EXEC or only + PROT_READ|PROT_WRITE. In the latter case, just trying to obtain a + mmap with PROT_READ|PROT_WRITE|PROT_EXEC would kill our process(!), + but in that situation libffi is fine with only PROT_READ|PROT_WRITE. + There is nothing in the libffi API to know that, though, so we have + to guess by parsing /proc/self/status. "Meh." + */ +#ifdef __linux__ +#include + +static int emutramp_enabled = -1; + +static int +emutramp_enabled_check (void) +{ + char *buf = NULL; + size_t len = 0; + FILE *f; + int ret; + f = fopen ("/proc/self/status", "r"); + if (f == NULL) + return 0; + ret = 0; + + while (getline (&buf, &len, f) != -1) + if (!strncmp (buf, "PaX:", 4)) + { + char emutramp; + if (sscanf (buf, "%*s %*c%c", &emutramp) == 1) + ret = (emutramp == 'E'); + break; + } + free (buf); + fclose (f); + return ret; +} + +#define is_emutramp_enabled() (emutramp_enabled >= 0 ? emutramp_enabled \ + : (emutramp_enabled = emutramp_enabled_check ())) +#else +#define is_emutramp_enabled() 0 +#endif