int eax = ((int(*)())("\xc3 <- This returns the value of the EAX register"))();
How this works ? String is casted to function pointer
Yes, it can. This is purpose of casting function pointers, just like usual pointers. We can cast a function pointer to another function pointer type but cannot call a function using casted pointer if the function pointer is not compatible with the function to be called.
In the C language, casting is a construct to view a data object temporarily as another data type. When you cast pointers, especially for non-data object pointers, consider the following characteristics and constraints: You can cast a pointer to another pointer of the same IBM® i pointer type.
There are no rules on casting pointers in C! The language lets you cast any pointer to any other pointer without comment.
c3
is the RET
instruction. When an x86 machine jumps to this string interpreted as code, it will execute RET
and therefore jump right back without having done anything (the rest of the string is therefore ignored). Since standard calling convention on x86 is to put your return value in eax
, but the code didn't do anything before returning, whatever was already in eax
will still be there, and in a position for the C code to interpret it as having been "returned".
This is highly dependent on your machine being x86 and that you're allowed to cast between data and function pointers (and execute the result) - a very system-specific hack. This is not standard compliant or portable C by any stretch!
(\xXX
is C's escape syntax for inserting single nonreadable characters into strings via their ASCII code in hex, if you didn't know that part.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With