如何从Linux内核中的函数指针获取函数名? [英] How to get function's name from function's pointer in Linux kernel?

查看:58
本文介绍了如何从Linux内核中的函数指针获取函数名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 C 中的函数指针获取函数名称?

How to get function's name from function's pointer in C?

实际情况是:我正在编写一个 linux 内核模块并且我正在调用内核函数.其中一些函数是指针,我想检查内核源代码中该函数的代码.但我不知道它指向哪个函数.我认为可以这样做,因为当系统出现故障(内核恐慌)时,它会在屏幕上打印出带有函数名称的当前调用堆栈.但是,我想我错了……是吗?

The real case is: I'm writing a linux kernel module and I'm calling kernel functions. Some of these functions are pointers and I want to inspect the code of that function in the kernel source. But I don't know which function it is pointing to. I thought it could be done because, when the system fails (kernel panic) it prints out in the screen the current callstack with function's names. But, I guess I was wrong... am I?

推荐答案

如果没有额外的帮助,这是不可能直接实现的.

That's not directly possible without additional assistance.

你可以:

  1. 在你的程序中维护一个表,映射函数指向名称的指针

  1. maintain a table in your program mapping function pointers to names

检查可执行文件的符号表,如果有的话.

examine the executable's symbol table, if it has one.

然而,后者很难,而且不便携.该方法将取决于操作系统的二进制格式(ELF、a.out、.exe 等),以及链接器完成的任何重定位.

The latter, however, is hard, and is not portable. The method will depend on the operating system's binary format (ELF, a.out, .exe, etc), and also on any relocation done by the linker.

既然您现在已经解释了您的实际用例是什么,那么答案实际上并不难.内核符号表在 /proc/kallsyms 中可用,并且有一个用于访问它的 API:

Since you've now explained what your real use case is, the answer is actually not that hard. The kernel symbol table is available in /proc/kallsyms, and there's an API for accessing it:

#include <linux/kallsyms.h>

const char *kallsyms_lookup(unsigned long addr, unsigned long *symbolsize,
                            unsigned long *ofset, char **modname, char *namebuf)

void print_symbol(const char *fmt, unsigned long addr)

出于简单的调试目的,后者可能会完全满足您的需要 - 它获取地址,对其进行格式化,然后将其发送到 printk,或者您可以使用 printk使用 %pF 格式说明符.

For simple debug purposes the latter will probably do exactly what you need - it takes the address, formats it, and sends it to printk, or you can use printk with the %pF format specifier.

这篇关于如何从Linux内核中的函数指针获取函数名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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