[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Tinycc-devel] TinyCC REPL

From: Joey Payne
Subject: [Tinycc-devel] TinyCC REPL
Date: Tue, 12 May 2015 19:33:18 -0600


I was wondering if there was a way to implement a REPL without having to recompile a long string of code every time using tcc_compile_string. I modified some of the source code to somewhat allow for this, but the symbols from previous code seem to need to be updated, since calling one results in a segfault. That's where I need some help. I'd like to be able to overwrite symbols from the REPL, as well as keep the old ones and use them where appropriate.

I'm using tcc 0.9.26 and my modification to the library is this:

tccelf.c (from line 247):

                //tcc_error_noabort("'%s' defined twice", name);
                sym_index = put_elf_sym(s, value, size,
                                ELFW(ST_INFO)(sym_bind, sym_type), other,
                                sh_num, name);
                esym->st_info = ELFW(ST_INFO)(sym_bind, sym_type);
                esym->st_shndx = sh_num;
                new_undef_sym = 1;
                esym->st_value = value;
                esym->st_size = size;
                esym->st_other = other;

My c code that I want to work is here:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "libtcc.h"

char my_program[] =
"int sub(int a, int b){return a-b;}\n"
"int foo(int n)\n"
"    printf(\"Hello World!\\n\");\n"
"    printf(\"sub(%d, %d) = %d\\n\", 2*n, n, sub(2*n, n));\n"
"    return 0;\n"

char program_mod_foo[] =
"int foo(int n){\n"
"    printf(\"Hello world!\n\");\n"
"    printf(\"%d\", sub(15,10));\n"

int main(int argc, char **argv)
    TCCState *s;
    int (*func)(int);

    s = tcc_new();
    if (!s) {
        fprintf(stderr, "Could not create tcc state\n");

    /* if tcclib.h and libtcc1.a are not installed, where can we find them */
    if (argc == 2 && !memcmp(argv[1], "lib_path=",9))
        tcc_set_lib_path(s, argv[1]+9);

    /* MUST BE CALLED before any compilation */
    tcc_set_output_type(s, TCC_OUTPUT_MEMORY);

    if (tcc_compile_string(s, my_program) == -1)
        return 1;

    /* relocate the code */
    if (tcc_relocate(s, TCC_RELOCATE_AUTO) < 0)
        return 1;

    /* run the code */

    if (tcc_compile_string(s, program_mod_foo) == -1)
        return 1;

    /* relocate the code */
    if (tcc_relocate(s, TCC_RELOCATE_AUTO) < 0)
        return 1;

    /* get entry symbol */
    func = tcc_get_symbol(s, "foo");

    // should print "Hello World" then 5
    func(32); // segfaults here due to calling sub() again.

    /* delete the state */

    return 0;

Any help or pointers in the right direction would be of great value to me :)


reply via email to

[Prev in Thread] Current Thread [Next in Thread]