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 that port, but I dont want to hard code what global variables can be queried. Thus I want the query to contain the string name of a global and the C code to look that string up in the symbol table to find its address and then send its value back over the TCP socket. Of course the symbol table must not have been stripped. So can the C program even locate its own symbol table, and is there a library interface for looking up symbols given their name? This is an ELF executable C program built with gcc.
相关问题
- Multiple sockets for clients to connect to
- Is shmid returned by shmget() unique across proces
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- how to get running process information in java?
file: reflect.c
file: reflect.h
file: main.c
just #include "reflect.h" and call reflect_query_symbol
example:
file:Makefile
The general term for this sort of feature is "reflection", and it is not part of C.
If this is for debugging purposes, and you want to be able to inspect the entire state of a C program remotely, examine any variable, start and stop its execution, and so on, you might consider GDB remote debugging:
This is actually fairly easy. You use
dlopen
/dlsym
to access symbols. In order for this to work, the symbols have to be present in the dynamic symbol table. There are multiple symbol tables!In order to add all symbols to the dynamic symbol table, use
-Wl,--export-dynamic
. If you want to remove most symbols from the symbol table (recommended), set-fvisibility=hidden
and then explicitly add the symbols you want with__attribute__((visibility("default")))
or one of the other methods.Safety
Notice that there is a lot of room for bad behavior.
If you want this to be safe, you should create a whitelist of permissible symbols.