0
votes

I want to allocate 4096 Bytes with posix_memalign in the array "page", and then protect it with PROT_NONE via mprotect(). The allocation seems to work, but protect() returns 1 instead of 0. The given error code is "Invalid argument".

I think it's only a small mistake, I am not able to detect. Thanks in advance for any help or suggestions.

uint8_t *page;
size_t page_size = 4096;
size_t alignment = 8;

int main(int argc, char* argv[]) {
    if (posix_memalign((void **) &page, alignment, page_size) != 0) perror("Allocation failed!");
    if (mprotect(page, page_size, PROT_NONE) != 0) perror("mprotect() failed!");
}
1
Just nitpicking, but I think that mprotect returns -1, not 1.Some programmer dude
Sorry, but I can't affirm that... Test it for yourself, if you don't believe ;-) int main() { if (posix_memalign((void **) &page, alignment, page_size) != 0) perror("Allocation failed!"); int n; if (n = mprotect(page, page_size, PROT_NONE) != 0) perror("mprotect() failed!"); printf("n: %d\n",n); }J. Doe
As for your problem, the mprotect specification says that "The implementation may require that addr be a multiple of the page size as returned by sysconf()". And that EINVAL (the error you get) is for "The addr argument is not a multiple of the page size as returned by sysconf()" On your system, are you sure the page-size is 4k?Some programmer dude
By the way n = mprotect(page, page_size, PROT_NONE) != 0 does not do what you think it does. It first evaluates mprotect(page, page_size, PROT_NONE) != 0 and then assign the boolean 1 or 0 result to n. Try instead (n = mprotect(page, page_size, PROT_NONE)) != 0.Some programmer dude
Very good comment! I changed it like you said, and now it shows me correctly the -1 instead of 1. My pagesize is indeed 4096, I retrieved it with both possibilities: long t1 = sysconf(_SC_PAGE_SIZE); long t2 = sysconf(_SC_PAGESIZE);J. Doe

1 Answers

0
votes

Try the way in the code below ... and read better the man-pages:

man -S3 posix_memalign

man -S2 mprotect

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/mman.h>
#include <stdint.h>
#include <inttypes.h>
#include <unistd.h>

uint8_t *page=NULL;
size_t page_size;
size_t alignment = 8;

int main(int argc, char* argv[]) {
    int blen;

    // page_size=getpagesize();
    page_size = sysconf(_SC_PAGE_SIZE);

    blen=page_size * 2;

    if (posix_memalign((void **) &page, page_size, blen) != 0)
        perror("Allocation failed!");

    if (mprotect(page, page_size, PROT_READ | PROT_WRITE) != 0)
        perror("mprotect() failed!");
}