On an x86 system, I have a Linux kernel module (“watcher module”) that gets notified by the kernel each time a particular kernel module (“target”) is loaded. Almost any kernel module can be a target. I use this in an instrumentation system I am working on.
When the watcher module handles such notification, it could be convenient for some reason, if the watcher knew the addresses of ELF sections of the loaded target module. Any ideas how this information could be obtained in kernel space?
Of course I could probably get the contents of the appropriate files in /sys/module/<target_name>/sections/ in user space as soon as the target is loaded and then somehow pass this data to the watcher module but this is too clumsy. I would like to find a way to obtain this information directly in the kernel space.
As far as I have seen in the sources of the module loader, it does not store section addresses in struct module, just creates sysfs files for the sections. May be it is possible to somehow find the kernel objects corresponding to those files and read the needed data from these objects? Or probably use some other approach?
After digging into how the information about the sections of a module gets into sysfs, I found no way to retrieve it without using the structure definitions internal to the kernel. Using such stuff is not an option in my project, so I have finally implemented another approach, which is, hopefully, more reliable.
In short, the idea is as follows. My kernel module uses the user-mode helper API to start a user-space process (a shell executing my script, actually). That process gets the name of the “target” kernel module as a parameter and collects the information about its sections from sysfs (
/sys/module/<target_name>/sections/). From the user space, this information can be obtained easily. After that, it passes the collected data to my kernel module as a string via a file in debugfs. The module parses the string and validates its contents. If everything is OK, the names and start addresses of ELF sections will be available.I admit, the trick with the user-mode helper is quite clumsy but it gets the job done.
I have prepared a sample implementation of the approach described above – see “Sections” example.
For details on the user-mode helper API, see the code in
<linux/kmod.c>and<linux/kmod.h>in the kernel sources, namely the definition ofcall_usermodehelper(). The examples as well as the explanation of typical usage of the API are available in this article.Note that the examples from that article are a bit inaccurate: the init function of the module returns the result of
call_usermodehelper()there. The latter, however, returns 2-byte status code (at least when called withUMH_WAIT_PROC) rather than 0 or negative error code that init function is expected to return. This may result in runtime warnings. Whatcall_usermodehelper()actually returns, is explained here.