Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please help me understand this bit-wise manipulation of pointer values

I am not able to understand why is addr being typecasted to long, and then complemented with expression.. basically the whole line involving the calculation of peekAddr

void *addr;
char *peekAddr ;
peekAddr = (char *) ((long)addr & ~(sizeof(long) - 1 ) ) ;
peekWord = ptrace( PTRACE_PEEKDATA, pid, peekAddr, NULL ) ;
like image 281
paseena Avatar asked Jan 27 '26 22:01

paseena


2 Answers

sizeof (long)     = (0)00000100
sizeof(long)-1    = (0)00000011
~(sizeof(long)-1) = (1)11111100

so 2 bits set to 0 make the address aligned to 4 bytes. additionally it's mostly used when the address was already incremented by sizeof(long)-1

like image 114
fazo Avatar answered Jan 29 '26 11:01

fazo


It's cast to long because (1) you can't do any operations on a void* except cast it and (2) on the author's platform, a void* value just so happens to fit in a long. He should really have used uintptr_t or size_t instead.

What the piece of code does:

sizeof(long) - 1

is most likely either 3 or 7, depending on the platform.

~(sizeof(long) - 1)

is a bitmask that selects all but the last few bits.

((long)addr & ~(sizeof(long) - 1))

is addr rounded down/aligned to address a long-sized chunk. Rounding occurs because the last lg(3) or lg(7) bits are zeros while the rest is copied from addr (where lg is integer binary logarithm).

like image 35
Fred Foo Avatar answered Jan 29 '26 13:01

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!