I have this piece of code to test a shellcode but I don’t understand it so can anyone explain it to me?
Forget about the assembly shellcode, what I want to understand is the C code,
char shellcode[] = "...";
int main(int argc, char **argv)
{
int (*func)();
func = (int (*)()) shellcode;
(int)(*func)();
}
I mean everything, what are the empty (), please explain it as if you are explaining it to a beginner.
This is a declaration of a function pointer. A function pointer is essentially a variable that holds the address of a function. In this case, the type of function that
funcpoints to is a one that takes no arguments and returns anint. You can assign the address of a function to this variable like so:Where
foois a function with the prototypeint foo();.Once a function has been assigned to this variable, you can call the function that
funcpoints to like so:There is an alternate syntax (which is equivalent), which I think is more clear:
So if
foowas assigned tofunc, then both examples above would actually call the functionfoo.You can also cast values to function pointers. In the code example
is a cast to a function pointer that takes no arguments and returns an
int. This is so the compiler won’t complain about assigning what is essentially achar*to the function pointerfunc.In the code you gave above, there is one last thing. After
funcis called, the result is (for some reason) cast to anint. As far as I can tell, this cast is totally unnecessary. So the last linecould be replaced with