Reputation: 173
I have written a sample hello.ko kernel module:
#include <linux/module.h> /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */
int init_module(void)
{
printk(KERN_INFO "Hello world.\n");
return 0;
}
void cleanup_module(void)
{
printk(KERN_INFO "Goodbye world 1.\n");
}
Here, I have used "printk" method which is a Kernel API exposed by Linux. I can see the Linux exported symbols in "/proc/kallsyms". I am curious to know how do gcc/ld links the called Kernel APIs? Does gcc/ld gets address of kernel method from "/proc/kallsyms" or some other file and perform linking? If yes, how do gcc/ld get to know that? I could not any option which tells that.
Upvotes: 3
Views: 1921
Reputation: 23438
The Linux kernel's module loader basically contains a special-purpose runtime linker. The .ko file is really an object file like any other, and as such it comes with a symbol table. If you run nm
on it (nm <path/to/some_module.ko>
), you'll see a lot of symbols marked "U", that is, "undefined". This includes symbols for core kernel functions that are used by the module, such as printk
, __kmalloc
, kfree
, etc. but in many cases also symbols implemented by other modules.
When the module is loaded, the kernel runs through the module's undefined symbols and looks them up in the (run-time) symbol table, patching the relevant memory locations, much like any other linker. If any undefined symbols aren't already in the symbol table, loading will fail (easy to demo by using insmod
instead of modprobe
as it won't load dependencies). It also adds any symbols exported by the module to the symbol table for other modules to use, tracking dependencies so you can't yank out a module used by another. Ilya Matveychikov has linked to the relevant code in the module loader in the comments, which will help if you want to know all the gory details.
Upvotes: 8