#include <stdio.h>
int main(int argc, char** argv)
{
void (*p) (void);
/* t开发者_开发百科his obviously won't work, but what string could I put in
here (if anything) to make this execute something meaningful?
Does any OS allow instructions to be read from
the stack rather than text area of the process image? */
char *c = "void f() { printf(\"Hello, world!\"); }";
p = ( void (*)() )c;
p();
return 0;
}
Sort of, but not really, there is no eval()
in c, like in many scripting languages.
However, what you are describing is sort of like a Buffer Overflow exploit.
Where, you use a string to write "code" (not c syntax, but machine code) into the address space after the buffer. Here's a nice little tutorial of the topic.
Don't use this information to write a virus :(
You could use libtcc
to compile and run C source code:
const char *code = "int main(int argc, char**argv) { printf(\"Hello, world!\"); return 0; }";
TCCState *tcc = tcc_new();
if (tcc_compile_string(tcc, code))
{
// an error occurred compiling the string (syntax errors perhaps?)
}
int argc = 1;
char *argv[] = { "test" };
int result = tcc_run (tcc, argc, argv);
// result should be the return value of the compiled "main" function.
// be sure to delete the memory used by libtcc
tcc_delete(tcc);
A coouple of issues:
- You can only compile
libtcc
on a supported architecture. - You need to have a
main
function.
Sure it is possible. Buffer Overflow exploits use it.
See Shellcode for what kind of strings you can place.
Basically what you can do it put machine code on the stack and jump to the address. This will cause execution (if the OS/machine allows it, see NX bit).
You could perhaps even try to do a memcpy from some function address onto a string on the stack and then try jumping to the address on the stack.
精彩评论