以下均針對於內核2.6.18
在module.h 中 THIS_MODULE的定義如下:
extern struct module __this_module; #define THIS_MODULE (&__this_module)
即是保存了__this_module這個對象的地址,那這個__this_module在哪里定義呢?這就要從module的編譯說起啦,如果編譯過模塊就會發現,會生成*.mod.c這樣的一個文件,打開這個文件,就會發現,類似下面的定義:
struct module __this_module __attribute__((section(".gnu.linkonce.this_module"))) = { .name = KBUILD_MODNAME, .init = init_module, #ifdef CONFIG_MODULE_UNLOAD .exit = cleanup_module, #endif };
這個文件是調用modpost生成的,modpost的main中有這樣一段代碼:
for (mod = modules; mod; mod = mod->next) { if (mod->skip) continue; buf.pos = 0; add_header(&buf, mod); add_versions(&buf, mod); add_depends(&buf, mod, modules); add_moddevtable(&buf, mod); add_srcversion(&buf, mod); sprintf(fname, "%s.mod.c", mod->name); write_if_changed(&buf, fname); }
其中的add_header就偷偷添加了__this_module 的定義
static void add_header(struct buffer *b, struct module *mod) { buf_printf(b, "#include <linux/module.h>\n"); buf_printf(b, "#include <linux/vermagic.h>\n"); buf_printf(b, "#include <linux/compiler.h>\n"); buf_printf(b, "\n"); buf_printf(b, "MODULE_INFO(vermagic, VERMAGIC_STRING);\n"); buf_printf(b, "\n"); buf_printf(b, "struct module __this_module\n"); buf_printf(b, "__attribute__((section(\".gnu.linkonce.this_module\"))) = {\n"); buf_printf(b, " .name = KBUILD_MODNAME,\n"); if (mod->has_init) buf_printf(b, " .init = init_module,\n"); if (mod->has_cleanup) buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n" " .exit = cleanup_module,\n" "#endif\n"); buf_printf(b, "};\n"); }