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.
Share
This is actually fairly easy. You use
dlopen/dlsymto 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=hiddenand 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.