简体   繁体   中英

Calling buffer as a function in C?

char buf[sizeof(shellcode)];
strcpy(buf, shellcode);
((void(*)())buf)();

I'm having a hard time to understand the syntax of the third line, I think it is making a buffer a function?

You are correct about the third line. It takes buf , decays it to a pointer, and then casts that pointer to a pointer-to-function. Then it calls that function. This works because void(*)() means "pointer to a function accepting no parameters and returning void ", and wrapping it in parentheses turns it into a cast. You now have a pointer-to-function, which you can call as though it were a regular function name.

This is not allowed by the C standard, but based on how compilers work will probably mean that it treats the address of buf as the address of a function in memory and tries to call that function. Usually this wouldn't work because the OS would tell the CPU to mark the region of memory buf is in as not executable, so when you try to pretend it's a function the CPU will throw an error; let's assume that the OS doesn't do this or that you have an old enough CPU that it doesn't support that.

You don't show us the contents of shellcode . Since everything in a computer is just a sequence of bytes, including the compiled binary code your computer runs, shellcode might contain executable binary code. If it does, then this causes that code to start running.

For example, if you compiled

void mycode()
{
    puts("Hello, world!");
}

you could then extract the contents of function mycode from the resulting object file. If you put those contents into shellcode , then the code in your question would (assuming the compiler treats pointers-to-function and pointers-to-data the same, and that the OS or CPU doesn't support noexec memory) print Hello, world! to the screen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM