c++cmemory-alignmentmprotect

What is the difference between these alignment functions?


I am writing a self-modifying program; already got it working. I found these two functions, but not sure what EXACTLY they do and I like to comment my code proper.

pagesize is got using getpagesize

/*
 * Defining variables:
 * func - function in memory I'm using mprotect on
 * offset - the offset in memory
 * ptr - the pointer to the memory
 */

unsigned int offset = (unsigned int)( ((long)func) & (pagesize-1) );
unsigned char * ptr = (unsigned char *) ((long)func & (~(pagesize-1) ) );

I have found offset's function being used for memory alignment checks. I know vaguely what they do, but not the difference?

Thanks.


Solution

  • Assuming pagesize is the size of a page, they use bit masks to calculate the pointer (ptr) to the start of the page containing func, and the offset (offset) within that page in bytes.

    As pagesize will always be a power of two, (pagesize-1) has all ones set. The offset within the page is the last 12 (for instance) bits (12 corresponds with pagesize is 4k=2^12), so the first statement clears all the bits except the last 12 by using & with an all ones bitmask of 12 least significant bits.

    The second line calculates the pointer to the page itself by clearing the last 4 bits; by using the logical inverse (~) of the previous bitmask, then an &, it clears all the other bits.