-2

What does this code mean?

char code[] = "bytecode will go here!";
int main(int argc, char **argv) {
    int (*func)(); /* This is pointer to function */
    func = (int (*)())code; /* What does this line mean? */
    (int)(*func)(); /* Calling function by pointer */
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189

3 Answers3

3
func = (int (*)()) code;

code, being an array, is implicitly converted to a pointer to its first element (it decays to such a pointer). This pointer is then cast to a pointer to a function.

This cast causes undefined behaviour. But "most of the time", it will probably result in a function pointer pointing to the address of the array. When you call it, then control jumps to this array. If it contains string data, you'll most likely get an invalid opcode or a segmentation fault. But if that array contains some user input a malicious user could've put (compiled) code into it, doing all sorts of funny (or less funny) stuff.

As an example, consider the above code running in some sort of server, being fed user input over some website. Then one could replace the program with, for example /bin/sh and thus gain shell access on that server.

Daniel Jour
  • 15,896
  • 2
  • 36
  • 63
  • Daniel Jour, thanks, it's clear, but how could be the code from code[] array executed if the array is stored in the data segment but not in the code segment? And could you explain how functions are stored in the memory what makes this trick possible? – Sebastian Rockefeller Mar 03 '16 at 10:22
1

What you're seeing there is an example of type punning.

void print_hello()
{
    printf("hello");
}

int main()
{
    void (*hello_func_ptr)() = &print_hello;

    //we convert what the function points to to a string of "byte code"
    char *func_byte_code = (char *)hello_func_ptr; 

    // prints out byte code of the function
    printf(func_byte_code); 

    // we cast the string byte code to a function pointer
    void (*func_from_byte_code)() = (void (*)())func_byte_code;

    // we call the function we got from casting the byte code to a function pointer  
    (*func_from_byte_code)(); // prints "hello"!
    return 0;
}

What your function does is taking the byte code string and convert it back to a function pointer like we've done above. You can then call the function by dereferencing the pointer and calling it by adding the parentheses and any parameters the function takes.

Now of course, you shouldn't need to do things like that in regular programming but seldom in peculiar cases.

Aiman Al-Eryani
  • 709
  • 4
  • 19
-1

This is a sample of shell code. here:https://en.wikipedia.org/wiki/Shellcode

func = (int (*)()) code; /* What does this line mean? */                           

func is a function point,it point to the address of "code array".

when the func be called,program will be jump to the address of array.

Rakesh
  • 756
  • 1
  • 9
  • 19
fei han
  • 62
  • 7