Search code examples
c++cvoidshellcode

What does void(*)() mean in code


I saw this code today in some fb profile, and was not able to understand what is and how this is working:-

(*(void(*)()) shellcode)()

Can someone please explain me, what does above code mean ?

Full Code Snippet Below :-

#include <stdio.h>
#include <string.h>

char *shellcode = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69"
          "\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80";

int main(void)
{
fprintf(stdout,"Length: %d\n",strlen(shellcode));
(*(void(*)()) shellcode)();
return 0;
}

Solution

  • It is a cast to a function pointer (with no returned result and no arguments). I prefer using typedef to define signature of such functions:

     typedef void plainsig_t(void);
    

    then simply code

     (*(plainsig_t*)shellcode) ();
    

    For function pointers, you don't need to dereference them, so it is shorter to just code:

     ((plainsig_t*) shellcode) ();
    

    which basically calls the function whose machine code is located inside shellcode memory zone.

    BTW, this is not strictly portable C. In principle, there is no guarantee that you can cast a data pointer to a function pointer. (On some weird processors -e.g. embedded microcontrollers, DSP, 1970s era computers-, code and data sit in different address spaces, or have different pointer sizes, etc....). But most common processors and ABI (x86-64/Linux, ARM/Android, ....) have the same address space for code and for data and accept casting function pointers to data pointers and vice versa.