Reputation: 321
I attempt to call mprotect
on the main thread's stack, but it always fails. Every time I try, it yields an ENOMEM
error. And I have checked in /proc/[pid]/maps the whole stack is mapped in the address space. However, I can successfully call mprotect
on a child thread's stack from the main stack. There must be something special about the main thread's stack that prevents itself from being changed by mprotect
. But I can't find any document for this. Anyone has an idea?
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/mman.h>
#include <assert.h>
#include <pthread.h>
#include <stdio.h>
void * addr;
size_t size;
void * thread(void * tls) {
sleep(1);
if (mprotect(addr, size, PROT_NONE) == -1) perror(NULL);
return NULL;
}
int main(int argc, const char *argv[]) {
pthread_attr_t attr;
pthread_getattr_np(pthread_self(), &attr);
pthread_attr_getstack(&attr, &addr, &size);
pthread_t th;
pthread_create(&th, NULL, thread, NULL);
sleep(2);
pthread_join(th, NULL);
return 0;
}
Upvotes: 2
Views: 413
Reputation: 715
I have used this code to protect meory. It's working fine with your code. Call the method like this->
39 pthread_attr_getstack(&attr, &addr, &size);
40 __enable_execute_stack(&addr);
and compile : gcc your_code.c __enable_execute_stack_code.h -lpthread -fbuilding-libgcc
Upvotes: 0
Reputation: 715
You trying to mprotect the pages which are not mapped. If you check the source of pthread_attr_getstack, you will find that there is no mmap.Stack pages are mapped on demand. this might help you
Upvotes: 3