In a kernel module, how to list all the kernel symbols with their addresses? The kernel should not be re-compiled.
I know "cat /proc/kallsyms" in an interface, but how to get them directly from kernel data structures, using functions like kallsyms_lookup_name
.
Example
Working module code:
Explanation
kernel/kallsyms.c implements
/proc/kallsyms
. Some of its functions are available for external usage. They are exported viaEXPORT_SYMBOL_GPL()
macro. Yes, your module should haveGPL
license to use it. Those functions are:kallsyms_lookup_name()
kallsyms_on_each_symbol()
sprint_symbol()
sprint_symbol_no_offset()
To use those functions, include
<linux/kallsyms.h>
in your module. It should be mentioned thatCONFIG_KALLSYMS
must be enabled (=y
) in your kernel configuration.To print all the symbols you obviously have to use
kallsyms_on_each_symbol()
function. The documentation says next about it:where
fn
is your callback function that should be called for each symbol found, anddata
is a pointer to some private data of yours (will be passed as first parameter to your callback function).Callback function must have next signature:
This function will be called for each kernel symbol with next parameters:
data
: will contain pointer to your private data you passed as last argument tokallsyms_on_each_symbol()
namebuf
: will contain name of current kernel symbolmodule
: will always beNULL
, just ignore thataddress
: will contain address of current kernel symbolReturn value should always be
0
(on non-zero return value the iteration through symbols will be interrupted).Supplemental
Answering the questions in your comment.
Yes, you can use
sprint_symbol()
function I mentioned above to do that. It will print symbol information in next format:Example:
Module name part can be omitted if symbol is built-in.
This is most likely because your printk buffer size is insufficient to store all the output of module above.
Let's improve above module a bit, so it provides symbols information via miscdevice. Also let's add function size to the output, as requested. The code as follows:
And here is how to use it:
File
symbols.txt
will contain all kernel symbols (both built-in and from loaded modules) in next format:Yes, you can. If I recall correctly, it's called reflection. Below is an example how to do so: