What does this piece of cast code do?


code taken from Linux x86_64 execve Shellcode


unsigned char code[] = \
    "\x48\x89\xc6"                 // mov    %rax,%rsi
    "\x48\x89\xf2"                 // mov    %rsi,%rdx
    "\x49\xbc\x2f\x62\x69\x6e\x2f" // movabs $0x68732f6e69622f,%r12
    "\x41\x54"                     // push   %r12
    "\x54"                         // push   %rsp
    "\x5f"                         // pop    %rdi
    "\xb0\x3b"                     // mov    $0x3b,%al
    "\x0f\x05"                     // syscall 


    printf("Shellcode Length:  %d\n", (int)strlen(code));

    int (*ret)() = (int(*)())code;



What is this line of code doing?

int (*ret)() = (int(*)())code;
asked by anonymous 21.06.2016 / 22:08

2 answers


This is a technique to execute the function written in machine code or another way where the name of the function is not known, but if it knows where it is.

Note that code is a variable with machine code mounted from that Assembly code in the comments. How to call this through C? Calls can only be through functions. So we have to interpret this array of bytes as if it were a function. C has a way of referencing functions anonymously.

In this case you will have a variable called ret which is of type "function that returns an integer". The final parentheses in the variable name and pointer (after all function is a pointer to a code) is what indicates that the background is a function.

(int(*)()) is a cast to cause this array to be converted to a function. Not that a conversion is done, it will only be interpreted like this by the compiler. This is done to match what is expected in the variable.

So you can execute arbitrary code. It could come from outside sources, which can be a danger. In some cases the operating system may prevent the execution of arbitrary code.

21.06.2016 / 22:24

A statement of a pointer function called ret is made, the function takes unspecified arguments and returns an integer.


Converts the array code to a pointer of a function of that type.

So it converts the address of the code array to a pointer of a function, which then allows you to call it and execute the code.

Translation of: What does int ( ret) () = (int () ()) code mean?

21.06.2016 / 22:22