How about this?
How about this?
Posted Dec 14, 2017 1:44 UTC (Thu) by TheJH (subscriber, #101155)In reply to: How about this? by pr1268
Parent article: MAP_FIXED_SAFE
Look at, for example, how glibc allocates memory for threads:
$ cat thread.c
#include <pthread.h>
void *testfn(void *arg) { return (void*)0; }
int main(void) {
pthread_t thread;
pthread_create(&thread, NULL, testfn, (void*)0);
return 0;
}
$ gcc -o thread thread.c -Wall -pthread
$ strace ./thread
[...]
mmap(NULL, 3795360, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f9b24276000
mprotect(0x7f9b2440b000, 2097152, PROT_NONE) = 0
mmap(0x7f9b2460b000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x195000) = 0x7f9b2460b000
mmap(0x7f9b24611000, 14752, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f9b24611000
[...]
MAP_FIXED is perfectly safe as long as you only pass in address ranges that you have allocated yourself - just like other APIs, like munmap() or mprotect(), which you also shouldn't call on address ranges that haven't been allocated to you. Unlike MAP_FIXED, the suggested MAP_FIXED_SAFE is for a very uncommon usecase and actually requires more care to get right. (Which is also why MAP_FIXED_SAFE isn't exactly a good name - it suggests that it is a "safer" alternative to MAP_FIXED, which it simply isn't in what I think is probably the majority of usecases.)