正在运行的C程序能够访问自己的符号表? [英] Can a running C program access its own symbol table?

查看:191
本文介绍了正在运行的C程序能够访问自己的符号表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个处理的请求发送到TCP套接字(绑定到特定端口)的Linux下C程序。我希望能够通过该端口的请求来查询C程序的内部状态,但我不想硬code可以查询哪些全局变量。因此,我希望查询包含全局的字符串名称以及C code查找该字符串了在符号表中找到它的地址,然后发送它的价值又回到了TCP套接字。当然,符号表一定不能被剥夺。因此,可以在C程序甚至找到了自己的符号表,是否有库接口用于查找给予他们的名字的符号?这是gcc构建一个ELF可执行的C程序。

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.

推荐答案

这其实是相当容易的。您可以使用的dlopen / 则dlsym 访问符号。为了使这一工作,符号必须在动态符号表present。有多种符号表!

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!

#include <dlfcn.h>
#include <stdio.h>

__attribute__((visibility("default")))
const char A[] = "Value of A";

__attribute__((visibility("hidden")))
const char B[] = "Value of B";

const char C[] = "Value of C";

int main(int argc, char *argv[])
{
    void *hdl;
    const char *ptr;
    int i;

    hdl = dlopen(NULL, 0);
    for (i = 1; i < argc; ++i) {
        ptr = dlsym(hdl, argv[i]);
        printf("%s = %s\n", argv[i], ptr);
    }
    return 0;
}

为了给所有符号添加到动态符号表,使用轮候册, - 出口动态。如果要删除从符号表的大多数符号(推荐),请将 -fvisibility =隐藏,然后明确地添加具有你想要的符号__属性__( (能见度(默认)))或其他方法之一。

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.


~ $ gcc dlopentest.c -Wall -Wextra -ldl
~ $ ./a.out A B C
A = (null)
B = (null)
C = (null)
~ $ gcc dlopentest.c -Wall -Wextra -ldl -Wl,--export-dynamic
~ $ ./a.out A B C
A = Value of A
B = (null)
C = Value of C
~ $ gcc dlopentest.c -Wall -Wextra -ldl -Wl,--export-dynamic -fvisibility=hidden
~ $ ./a.out A B C
A = Value of A
B = (null)
C = (null)

安全

请注意,有很多的空间的不良行为。

Safety

Notice that there is a lot of room for bad behavior.


$ ./a.out printf
printf = ▯▯▯▯ (garbage)

如果你想这是安全的,你应该创建允许符号的白名单中。

If you want this to be safe, you should create a whitelist of permissible symbols.

这篇关于正在运行的C程序能够访问自己的符号表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆