Linux modules:
簡介:
linux 2.0版本以後都支援模組化,因為核心中的一部分常駐在記憶體中,(如最常使用的進程,如scheduler等),但是其它的進程只是在需要的時候才被載入。如MS-DOS檔案系統只有當mount此類系統的時候才需要,這種按需載入,就是模組。它能使核心保持較小的體積,雖然可以把所有的東東都放在核心中,這樣的話,我們就不需要模組了,但是這樣通常是有特殊的用途(所有要啟動並執行進程都預Crowdsourced Security Testing道的情況)。
模組另一個優點是核心可以動態載入、卸載它們(或者自動地由kerneld精靈完成)。
Writing, Installing, and Removing Modules
WRiting Modules:
除了它們運行在核心空間中之外,模組與其它程式類似。所以,必須定義MODULE並且包含標頭檔module.h以及其它的一些核心標頭檔。模組即可以很簡單也可以很複雜。
一般的模組格式如下:
#define MODULE
#include <linux/module.h>
/*... other required header files... */
/*
* ... module declarations and functions ...
*/
int
init_module()
{
/* code kernel will call when installing module */
}
void
cleanup_module()
{
/* code kernel will call when removing module */
}
使用核心源碼的模組在用gcc編譯時間,必須使用如下的選項:
-I/usr/src/linux/include
注意並不是所有核心中的變數都被匯出供模組使用的,即使代碼中用extern聲明了。在/proc/ksyms檔案或者程式ksyms中顯示了被匯出的符號。現在的linux核心使用使用EXPORT_SYMBOL(x)宏來不僅匯出符號,而且也匯出版本號碼(version number)。如果是使用者自己定義的變數,使用EXPORT_SYMBOL_NOVERS(x)宏。否則的話linker不會在kernel symbol table中保留此變數。可以使用EXPORT_NO_SYMBOLS宏不匯出變數,預設情況是模組匯出所有的變數。
Installing and Removing Modules:
必須是超級使用者才可以的。使用insmod來安裝一個模組:
/sbin/insmod module_name
rmmod命令移除一個已經安裝了的模組,以及任何此模組所匯出的引用。
/sbin/rmmod module_name
使用lsmod列出所有安裝了的模組。
Example:
simple_module.c
/* simple_module.c
*
* This program provides an example of how to install a trivial module
* into the Linux kernel. All the module does is put a message into
* the log file when it is installed and removed.
*
*/
#define MODULE
#include <linux/module.h>
/* kernel.h contains the printk function */
#include <linux/kernel.h>
/* init_module
* kernel calls this function when it loads the module
*/
int
init_module()
{
printk("<1>The simple module installed itself properly./n");
return 0;
} /* init_module */
/* cleanup_module
* the kernel calls this function when it removes the module
*/
void
cleanup_moudle()
{
printk("<1>The simple module is now uninstalled./n");
} /* cleanup_module */
This is the Makefile:
# Makefile for simple_module
CC=gcc -I/usr/src/linux/include/config
CFLAGS=-O2 -D__KERNEL__ -Wall
simple_module.o : simple_module.c
install:
/sbin/insmod simple_module
remove:
/sbin/rmmod simple_module