Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming (Functions pointer casting)

int eax = ((int(*)())("\xc3 <- This returns the value of the EAX register"))();

How this works ? String is casted to function pointer

like image 893
YashM Avatar asked Jul 20 '14 19:07

YashM


People also ask

Can you cast a 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.

Can you cast a pointer in C?

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.

What is the rule for casting pointers in C?

There are no rules on casting pointers in C! The language lets you cast any pointer to any other pointer without comment.


1 Answers

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.)

like image 155
Leushenko Avatar answered Oct 21 '22 15:10

Leushenko