is it possible to make a function execute code from a string on the stack?

前端 未结 3 1523
感情败类
感情败类 2021-01-04 21:01
#include 

int main(int argc, char** argv)
{
    void (*p) (void);
    /* this obviously won\'t work, but what string could I put in 
       here (if          


        
3条回答
  •  醉酒成梦
    2021-01-04 21:43

    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:

    1. You can only compile libtcc on a supported architecture.
    2. You need to have a main function.

提交回复
热议问题