Вопрос

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.

Это было полезно?

Решение

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.

Другие советы

(I'll assume that "pagesize" is the platform's page size, and it's a power of two - e.g. on x86 it's 0x1000. Also I'll assume the "func" is a pointer to a function, i.e. the code you want to change).

"offset" contains the offset of the page of the code, while "pthr" contains the virtual address at which the memory page containing the code is mapped. My guess is that somewhere in your program a new virtual view (with different access rights, in particular write permission) of the code's page is created. Let's say that this new address is stored in "unsigned char *page2". So, the code may be changed by writing to *(page2 + offset).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top