/* FILE: nonox.c * PURPOSE: set memory executable * MODS: mckeeman@dartmouth.edu -- Mar 2007 -- original * Andrew Scott Parker -- fixed mac section * METHOD: Use OS primitives * On Windows, compile with 'mex -DMSWIND nonox.c' */ typedef unsigned char byte; #include "mex.h" #if defined(_WIN32) || defined(_WIN64) #include #define HOT PAGE_EXECUTE_READWRITE #define COLD PAGE_READWRITE static int setProt(int prot, byte *code, int len) { bool res; DWORD old; res = VirtualProtect(code, len, prot, &old); return res; } #elif defined(__linux__) /* linux */ #include #include #define HOT (PROT_EXEC|PROT_READ|PROT_WRITE) #define COLD (PROT_READ|PROT_WRITE) static int setProt(int prot, byte *code, int len) { bool res; void *page = (void*) ((unsigned long)code & PAGE_MASK); uint32_T os = ((unsigned long)code & (PAGE_SIZE-1)); res = (mprotect(page, os+len, prot)==0); return res; } #elif defined(__APPLE__) /* the Mac */ #include #include #define HOT (PROT_EXEC|PROT_READ|PROT_WRITE) #define COLD (PROT_READ|PROT_WRITE) static int setProt(int prot, byte *code, int len) { int res; int psize = getpagesize(); void *page = (void*)((unsigned long)code & ~(psize-1)); uint32_T os = ((unsigned long)code & (psize-1)); res = (mprotect(page, os+len, prot) == 0); return res; } #endif /* platform defines */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { int len; unsigned char *code; unsigned int res; const int dims[] = {1,1}; mxAssert(nrhs == 1, "bad call: use nonox(code)"); len = (mxGetM(prhs[0]) * mxGetN(prhs[0])); code = (unsigned char*)mxGetData(prhs[0]); res = setProt(HOT, code, len); mxAssert(nlhs<=1, "bad call: use rc = nonox(code)"); plhs[0] = mxCreateNumericArray(2, dims, mxUINT32_CLASS, mxREAL); *(uint32_T*)mxGetData(plhs[0]) = res; }