Can a running C program access its own symbol table?

前端 未结 3 1414
伪装坚强ぢ
伪装坚强ぢ 2021-02-19 19:06

I have a linux C program that handles request sent to a TCP socket (bound to a particular port). I want to be able to query the internal state of the C program via a request to

3条回答
  •  南旧
    南旧 (楼主)
    2021-02-19 19:52

    file: reflect.c

    #include 
    #include "reflect.h"
    
    struct sym_table_t gbl_sym_table[1] __attribute__((weak)) = {{NULL, NULL}};
    
    void * reflect_query_symbol(const char *name)
    {
        struct sym_table_t *p = &gbl_sym_table[0];
    
        for(; p->name; p++) {
            if(strcmp(p->name, name) == 0) {
                return p->addr;
            }
        }
        return NULL;
    }
    

    file: reflect.h

    #include 
    
    struct sym_table_t {
        char *name;
        void *addr;
    };
    
    void * reflect_query_symbol(const char *name);
    

    file: main.c

    just #include "reflect.h" and call reflect_query_symbol

    example:

    #include 
    #include "reflect.h"
    
    void foo(void)
    {
        printf("bar test\n");
    }
    
    int uninited_data;
    
    int inited_data = 3;
    
    int main(int argc, char *argv[])
    {
        int i;
        void *addr;
    
        for(i=1; i

    file:Makefile

    objs = main.o reflect.o
    
    main: $(objs)
            gcc -o $@ $^
            nm $@ | awk 'BEGIN{ print "#include "; print "#include \"reflect.h\""; print "struct sym_table_t gbl_sym_table[]={" } { if(NF==3){print "{\"" $$3 "\", (void*)0x" $$1 "},"}} END{print "{NULL,NULL} };"}' > .reflect.real.c
            gcc -c .reflect.real.c -o .reflect.real.o
            gcc -o $@ $^ .reflect.real.o
            nm $@ | awk 'BEGIN{ print "#include "; print "#include \"reflect.h\""; print "struct sym_table_t gbl_sym_table[]={" } { if(NF==3){print "{\"" $$3 "\", (void*)0x" $$1 "},"}} END{print "{NULL,NULL} };"}' > .reflect.real.c
            gcc -c .reflect.real.c -o .reflect.real.o
            gcc -o $@ $^ .reflect.real.o
    

提交回复
热议问题