how does compiler/linker resolves kernel API like 'printk' called from a module on linux

ぐ巨炮叔叔 提交于 2019-12-01 06:50:23

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/10946081/how-does-compiler-linker-resolves-kernel-api-like-printk-called-from-a-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!