The values of mod->init
and mod->exit
come from the struct module __this_module
variable contained in the .gnu.linkonce.this_module
section of the module's .ko file. The kernel assumes that this variable is at the start of the section, and in fact it is the only variable in the section.
The __this_module
variable is initialized by a C initializer within the modulename.mod.c file that is generated during the MODPOST phase of the kernel build process. A typical definition of the __this_module
variable in a modulename.mod.c file looks like this for current kernels:
__visible struct module __this_module
__section(.gnu.linkonce.this_module) = {
.name = KBUILD_MODNAME,
.init = init_module,
#ifdef CONFIG_MODULE_UNLOAD
.exit = cleanup_module,
#endif
.arch = MODULE_ARCH_INIT,
};
The finit_module
and init_module
syscall handling functions call load_module
to do most of the work. load_module
calls setup_load_info
, which amongst other things, looks for the .gnu.linkonce.this_module
section that contains only the __this_module
variable. A temporary pointer to this is placed in info->mod
(where info
points to the struct load_info
used to hold information for loading the module). load_module
later calls layout_and_allocate
which returns a pointer to the __this_module
variable (actually, a pointer to the .gnu.linkonce.this_module
section) after it has been copied to its final place in kernel memory by move_module
. After load_module
calls apply_relocations
to perform dynamic linking, mod->init
and mod->exit
will have their final values (ignoring modifications by CONFIG_CFI_CLANG
in kernel 5.13 onwards).
Note that the __this_module.init
function pointer is always either a pointer to init_module
or is defaulted to null, and the __this_module.exit
function pointer is always either a pointer to cleanup_module
or is defaulted to null. (Most module source codes use the module_init(initfn)
and module_exit(exitfn)
macros to create those functions, but they can be defined explicitly.)