Here are some issues I found with your code:
(a). Your initialization and termination functions should be declared static and properly identified. For example, in m1.c —
static int __init hello_start(void)
{
printk(KERN_INFO "Loading m1 module ...n");
func_m2();
return 0;
}
static void __exit hello_end(void)
{
printk(KERN_INFO "Unloading m1 ...n");
}
Repeat this for m2.c
(b). Build both of your modules together, using the same Makefile. I bet if you look closely at the output from your existing Makefile for m1.c, you will see a warning indicating that func_m2() is undefined. Anyhow, the consolidated Makefile should look like —
SRCS = m1.c m2.c
OBJS = $(SRCS:.c=.o)
obj-m += $(OBJS)
EXTRA_CFLAGS = -O2
all:
$(MAKE) -C /lib/modules/`uname -r`/build M=$(PWD) modules
clean:
$(MAKE) -C /lib/modules/`uname -r`/build M=$(PWD) clean
$(RM) Module.markers modules.order
After both modules are built, run insmod on ‘m2.ko’ before issuing the insmod for ‘m1.ko’. Check results via dmesg.
Also, over here I am assuming that both m1.c and m2.c are in the same directory. Even if they are in different directories, this technique will work, but it will be messy. If they are in different directories, do the following.
I did little research and found a way to build modules in separate directories. The example I used is much simpler than what you have, but perhaps it is adaptable.
I have following manifest of files in a directory called ExportSymbol…
$ ls -CFR
.:
include/ Makefile mod1/ mod2/
./include:
m2_func.h
./mod1:
Makefile module1.c
./mod2:
Makefile module2.c
The m2_func.h appears as:
#ifndef M2_FUNC_H
#define M2_FUNC_H
void m2_func(void);
#endif
The top-level Makefile appears as:
obj-y := mod1/ mod2/
all:
$(MAKE) -C /lib/modules/`uname -r`/build M=$(PWD) modules
clean:
$(MAKE) -C /lib/modules/`uname -r`/build M=$(PWD) clean
$(RM) Module.markers modules.order
The Makefile and module1.c, which are in mod1/, appear as:
SRCS = module1.c
OBJS = $(SRCS:.c=.o)
obj-m += $(OBJS)
EXTRA_CFLAGS += -I${PWD}/include
all:
$(MAKE) -C /lib/modules/`uname -r`/build M=$(PWD) modules
clean:
$(MAKE) -C /lib/modules/`uname -r`/build M=$(PWD) clean
$(RM) Module.markers modules.order
#include <linux/module.h>
#include <linux/kernel.h>
static int __init hello_start(void)
{
printk(KERN_INFO "Loading m1 module ...n");
m2_func();
return 0;
}
static void __exit hello_end(void)
{
printk(KERN_INFO "Unloading m1 ...n");
}
module_init(hello_start);
module_exit(hello_end);
MODULE_LICENSE("GPL");
The Makefile and module2.c, which are in mod2/, appear as:
SRCS = module2.c
OBJS = $(SRCS:.c=.o)
obj-m += $(OBJS)
EXTRA_CFLAGS += -I${PWD}/include
all:
$(MAKE) -C /lib/modules/`uname -r`/build M=$(PWD) modules
clean:
$(MAKE) -C /lib/modules/`uname -r`/build M=$(PWD) clean
$(RM) Module.markers modules.order
#include "m2_func.h"
#include <linux/module.h>
#include <linux/kernel.h>
static int __init hello_start(void)
{
printk(KERN_INFO "Loading m2 module ...n");
return 0;
}
static void __exit hello_end(void)
{
printk(KERN_INFO "Unloading m2 ...n");
}
void m2_func(void)
{
printk(KERN_INFO "This a function in m2n");
}
module_init(hello_start);
module_exit(hello_end);
MODULE_LICENSE("GPL");
EXPORT_SYMBOL(m2_func);
NOTE: I can’t use your makefile as it generates *.ko per each c file. The Makefile is doing its job. A ‘ko’ file is a kernel object file; you will have one for each .c source file. There’s no way around this. If you do not want multiple ko-files, then put all of your code in one source file.
Время прочтения
11 мин
Просмотры 28K
Состояние дел
Это обсуждение относится к ядру операционной системы Linux, и представляет интерес для разработчиков модулей ядра, драйверов под эту операционную систему. Для всех прочих эти заметки вряд ли представляют интерес.
Каждый, кто написал свой самый простейший модуль ядра Linux знает, и это написано во всех существующих книгах по технике написания драйверов Linux, что использовать в собственном коде модуля можно только те имена (главным образом это функции API ядра), которые экспортируются ядром. Это одно из самых путанных понятие из области ядра Linux — экспорт символов ядра. Для того, чтобы имя из пространства ядра было доступно для связывания в другом модуле, для этого имени должны выполняться два условия: а). имя должно иметь глобальную область видимости (в вашем модуле такие имена не должны объявляться static) и б). имя должно быть явно объявлено экспортируемым, оно должно быть явно записано параметром макроса EXPORT_SYMBOL (или EXPORT_SYMBOL_GPL, что далеко не одно и то же по последствиям).
Все имена, известные в ядре, динамически отображаются в псевдо-файле /proc/kallsyms, и число их огромно:
$ uname -r
3.13.0-37-generic
$ cat /proc/kallsyms | wc -l
108960
Число же экспортируемых ядром имён (предоставляемых для использования в программном коде модулей) значительно меньше:
$ cat /lib/modules/`uname -r`/build/Module.symvers | wc -l
17533
Как легко видеть, в ядре определено несколько сот тысяч имён (в зависимости от версии ядра). Но только малая часть (порядка 10%) этих имён объявлены как экспортируемые, и доступны для использования (связывания) в коде модулей ядра.
Вспомним, что вызовы API ядра осуществляются по абсолютному адресу размещения имени. Каждому экспортированному ядром (или любым модулем) имени соотносится адрес, он и используется для связывания при загрузке модуля, использующего это имя. Это основной механизм взаимодействия модуля с ядром. При выполнении системы модуль динамически загружается и становится неотъемлемой частью кода ядра. Этим объясняется то, что модуль ядра в Linux может быть скомпилирован только под конкретное ядро (обычно по месту установки), а попытка загрузить такой бинарный модуль с другим ядром приведёт к краху операционной системы.
Как итог этого краткого экскурса, мы можем сформулировать, что разработчики ядра Linux предоставляют для разработчиков расширений (модулей ядра) весьма ограниченный (и крайне плохо документированный) набор API, который, по их мнению, достаточен для написания расширений ядра. Но это мнение может не совпадать с мнением самих разработчиков драйверов, которые хотели бы иметь в руках весь арсенал ядра. И воспользоваться ним вполне возможно, обсуждением чего мы и займёмся в оставшейся части текста.
Поиск адреса по имени
Взглянем на структуру строки-записи любого (из 108960 ) имени ядра в /proc/kallsyms:
$ sudo cat /proc/kallsyms | grep ' T ' | grep sys_close
c1176ff0 T sys_close
Это экспортируемое имя обработчика системного вызова (POSIX) close(). (В некоторых дистрибутивах Linux адреса в строке будут заполнены только если считывание выполняется с правами root, для других пользователей в поле адреса будет показано нулевое значение.)
Мы вполне могли бы использовать вызов функции sys_close() в коде своего модуля. Но мы не сможем сделать это с совершенно симметричным ему вызовом sys_open(), потому что это имя не экспортируется ядром. При сборке такого модуля мы получим предупреждение подобно следующему:
$ make
...
MODPOST 2 modules
WARNING: "sys_open" [/home/olej/2011_WORK/LINUX-books/examples.DRAFT/sys_call_table/md_0o.ko]
undefined!
...
Но попытка загрузить такой модуль закончится неудачей:
$ sudo insmod md_0o.ko
insmod: error inserting 'md_0o.ko': -1 Unknown symbol in module
$ dmesg
md_0o: Unknown symbol sys_open
Такой модуль не может быть загружен, потому как он противоречит правилам целостности ядра: содержит не разрешённый внешний символ — этот символ не экспортируется ядром для связывания (то-есть предупреждение с точки зрения компилятора выглядит как критическая ошибка с точки зрения разработчика).
Означает ли показанное выше, что только экспортируемые символы ядра доступны в коде нашего модуля. Нет, это означает только, что рекомендуемый способ связывания по имени (по абсолютному адресу имени) применим только к экспортируемым именам. Экспортирование обеспечивает ещё один дополнительный рубеж контроля для обеспечения целостности ядра — минимальная некорректность приводит к полному краху операционной системы, иногда при этом она даже не успевает сделать сообщение: Oops…
Раз в псевдо-файле /proc/kallsyms отображаются все символы ядра, то код модуля мог бы взять их оттуда. Более того, это значит, что в API ядра есть методы локализации всех имён, и эти методы можно использовать в своём коде для этих же целей. Опуская путь промежуточных решений, рассмотрим только 2 варианта, 2 экспортируемых вызова (все определения в <linux/kallsyms.h> в ядре, или см. lxr.free-electrons.com/source/include/linux/kallsyms.h):
Вызов:
unsigned long kallsyms_lookup_name( const char *name );
Здесь name — имя которое мы ищем, а возвращается его абсолютный адрес. Недостаток этого варианта в том, что он появляется в ядре где-то между версиями ядра 2.6.32 и 2.6.35 (или примерно между пакетными дистрибутивами издания лета 2010г. и весны 2011г.), точнее он присутствовал и ранее, но не экспортировался. Для встраиваемых и малых систем это может стать серьёзным препятствием.
Более общий вызов:
int kallsyms_on_each_symbol( int (*fn)(void*, const char*, struct module*, unsigned long), void *data );
Этот вызов сложнее, и здесь нужны краткие пояснения. Первым параметром (fn) он получает указатель на вашу пользовательскую функцию, которая и будет последовательно (в цикле) вызываться для всех символов в таблице ядра, а вторым (data) — указатель на произвольный блок данных (параметров), который будет передаваться в каждый вызов этой функции fn().
Прототип пользовательской функции fn, которая циклически вызывается для каждого имени:
int func( void *data, const char *symb, struct module *mod, unsigned long addr );
Здесь:
data — блок параметров, заполненный в вызывающей единице, и переданный из вызова функции kallsyms_on_each_symbol() (2-й параметр вызова), как это описано выше, здесь, как раз, и хорошо передать имя того символа, который мы разыскиваем;
symb — символьное изображение (строка) имени из таблицы имён ядра, которое обрабатывается на текущем вызове func;
mod — модуль ядра, к которому относится обрабатываемый символ;
addr — адрес символа в адресном пространстве ядра (это, собственно, и есть то, что мы и ищем);
Перебор имён таблицы ядра можно прервать на текущем шаге и дальше уже не продолжать (из соображений эффективности, если мы уже обработали требуемые нам символы), если пользовательская функция func возвратит ненулевое значение.
Для пользования вызовом kallsyms_on_each_symbol() мы подготовим собственную функцию обёртку, аналогичную по смыслу kallsyms_lookup_name():
static void* find_sym( const char *sym ) { // find address kernel symbol sym
static unsigned long faddr = 0; // static !!!
// ----------- nested functions are a GCC extension ---------
int symb_fn( void* data, const char* sym, struct module* mod, unsigned long addr ) {
if( 0 == strcmp( (char*)data, sym ) ) {
faddr = addr;
return 1;
}
else return 0;
};
// --------------------------------------------------------
kallsyms_on_each_symbol( symb_fn, (void*)sym );
return (void*)faddr;
}
Здесь использован трюк с вложенным определением функции symb_fn(), что является совершенно легальным использованием расширения компилятора GCC (относительно стандарта языка C), но для компиляции модулей ядра мы используем исключительно GCC. Такой код позволяет избежать объявления глобальной промежуточной переменной, препятствует засорению пространства имён и способствует локализации кода.
Пример использования
Одним из самых сакральных мест в операционной системе Linux является селекторная таблица sys_call_table, через которую происходит любой системный вызов: подготовив предварительно соответствующим образом параметры, записав 1-м параметром номер (селектор) системного вызова, система выполняет команду перехода в ядро: int 80h (в старых версиях) или sysenter, что по существу одно и то же. Номер системного вызова (селектор, 1-й параметр) и является индексом в таблице sys_call_table (массиве) указателей на функции обработки системных вызовов ядром. Номера всех системных вызовов мы можем посмотреть, например, для архитектуры i386:
$ cat /usr/include/i386-linux-gnu/asm/unistd_32.h
...
#define __NR_restart_syscall 0
#define __NR_exit 1
#define __NR_fork 2
#define __NR_read 3
#define __NR_write 4
#define __NR_open 5
#define __NR_close 6
#define __NR_waitpid 7
#define __NR_creat 8
...
Здесь изображена таблица индексов (номеров) системных вызовов, используемая в адресном пространстве пользователя, реализуемая стандартной библиотекой C libc.so. Точный аналог этой таблицы присутствует и в заголовочных файлах ядра, в адресном пространстве ядра. И аналогичные таблицы индексов системных вызовов наличествуют для всех архитектур, поддерживаемых Linux (таблицы для разных архитектур различаются и размерностью, и составом, и численными значениями индексов для аналогичных вызовов!).
Начиная с версий 2.6 ядра символ sys_call_table был исключён из числа экспортируемых, исходя из весьма своеобразно понимаемых командой разработчиков ядра соображений защищённости (могу предположить, что защищённость здесь предполагалось толковать в смысле: защищённость куска хлеба разработчиков ядра от сторонних программистов). Все книги по написанию драйверов Linux утверждают, что использовать sys_call_table в коде драйвера невозможно. Сейчас, а ещё больше в последующих частях обсуждения, мы будем показывать что это не так!
Достаточно продолжительное время (с 2011 года) работая с обсуждаемой тематикой я перечитал множество публикаций на этот предмет. Вирусописатели и всякая прочая шваль, пугающие самих себя страшным словом хакер, чего только не выдумывали для поиска sys_cal_table — даже динамически декодируют дампы двоичных фрагментов памяти, занимаемых ядром, проделывая сканирование участков памяти ядра (в поисках, например, позиции sys_close(), которй экспортируется всегда). Как будет сейчас показано, всё это делается куда как проще. Только секрет устойчивости Linux состоит не в том. что пакостники не могут чего-то там найти, а в том, что регламентация прав доступа не позволит (без root прав) сделать никакие гадости за пределами этого регламента … а root права никто пакостникам не даёт.
Но вернёмся к задаче разрешения не экспортируемых символов ядра. Первый вариант (файл mod_kct.c) демонстрирует использование kallsyms_lookup_name() (для простоты и укорочения не показаны включение заголовочных файлов, необходимые макросы вида MODULE_*() … — всё это есть в файлах архива):
static int __init ksys_call_tbl_init( void ) {
void** sct = (void**)kallsyms_lookup_name( "sys_call_table" );
printk( "+ sys_call_table address = %pn", sct );
if( sct ) {
int i;
char table[ 120 ] = "sys_call_table : ";
for( i = 0; i < 10; i++ )
sprintf( table + strlen( table ), "%p ", sct[ i ] );
printk( "+ %s ...n", table );
}
return -EPERM;
}
module_init( ksys_call_tbl_init );
Здесь извлекается адрес таблицы sys_call_table и далее содержащиеся в ней адреса обработчиков первых 10-ти системных вызовов (__NR_restart_syscall … __NR_link):
$ sudo insmod mod_kct.ko
insmod: ERROR: could not insert module mod_kct.ko: Operation not permitted
$ dmesg | tail -n 2
[39473.496040] + sys_call_table address = c1666140
[39473.496045] + sys_call_table : c1067840 c1059280 c1055eb0 c1179ee0 c1179f70 c1178cb0 c1176ff0 c1059570 c1178d10 c1188860 ...
(Ошибка ‘Operation not permitted ‘ не должна смущать — мы и не собирались загружать модуль, на что и указывает ненулевой код возврата -EPERM, мы просто выполняем свой код в привилегированном режиме, супервизоре, нулевом кольце защиты процессора).
Удостоверимся, чему соответствуют найденные адреса, занесённые в начало массива sys_call_table:
$ sudo cat /proc/kallsyms | grep c1067840
c1067840 T sys_restart_syscall
$ sudo cat /proc/kallsyms | grep c1059280
c1059280 T SyS_exit
c1059280 T sys_exit
$ sudo cat /proc/kallsyms | grep c1055eb0
c1055eb0 T sys_fork
… ну и так далее (сравните с таблицей номеров системных вызовов, показанной ранее).
Следующий вариант будет чуть сложнее для понимания, он использует функцию kallsyms_on_each_symbol(), но он и более универсальный (файл mod_koes.c):
static int __init ksys_call_tbl_init( void ) {
void **sct = find_sym( "sys_call_table" ); // table sys_call_table address
printk( "+ sys_call_table address = %pn", sct );
if( sct != NULL ) {
int i;
char table[ 120 ] = "sys_call_table : ";
for( i = 0; i < 10; i++ )
sprintf( table + strlen( table ), "%p ", sct[ i ] );
printk( "+ %s ...n", table );
}
return -EPERM;
}
module_init( ksys_call_tbl_init );
Текстуально он почти полностью повторяет предыдущий, всю продуктивную работу выполняет функция find_sym(), которая приведена и обсуждалась выше. Результат выполнения неизменно тот же:
$ sudo insmod mod_koes.ko
insmod: ERROR: could not insert module mod_koes.ko: Operation not permitted
$ dmesg | tail -n2
[42451.186648] + sys_call_table address = c1666140
[42451.186654] + sys_call_table : c1067840 c1059280 c1055eb0 c1179ee0 c1179f70 c1178cb0 c1176ff0 c1059570 c1178d10 c1188860 ...
Обсуждение
Скептик может возразить: «Ну и что?». А то, что показаны необходимые и достаточные механизмы для того, чтобы использовать любые API ядра в собственно коде модулей ядра, подгружаемых динамически. Показанная техника расширяет спектр возможностей автора модуля ядра на порядки! Это настолько объёмные перспективы, что для их рассмотрения нам потребуются последующие части этого обсуждения.
…но чтобы завершение рассказа не было таким скучным, покажем одно из простых, но впечатляющих применений — выполнение кода системного вызова (вообще то говоря, любого) пользовательской библиотеки из кода модуля ядра.
Вам говорили, что код модуля ядра осуществляет вывод в системный журнал (printk()) и не может осуществлять вывод на терминал (printf())? Сейчас мы покажем, что это не так… Вот такой простой модуль ядра производит вывод на терминал:
static asmlinkage long (*sys_write) (
unsigned int, const char __user *, size_t );
static int __init wr_init( void ) {
char buf[ 80 ] = "Hello from kernel!n";
int len = strlen( buf ), n;
sys_write = find_sym( "sys_write" );
printk( "+ sys_write address = %pn", sys_write );
printk( "+ [%d]: %s", len, buf );
if( sys_write != NULL ) {
mm_segment_t fs = get_fs();
set_fs( get_ds() );
n = sys_write( 1, buf, len );
set_fs( fs );
printk( "+ printf() return : %dn", n );
}
return -EPERM;
}
module_init( wr_init );
А вот его исполнение (попытка загрузки с аварийным кодом завершения):
$ sudo insmod mod_wrc.ko
Hello from kernel!
insmod: ERROR: could not insert module mod_wrc.ko: Operation not permitted
$ dmesg | tail -n3
[23942.974587] + sys_write address = c1179f70
[23942.974591] + [19]: Hello from kernel!
[23942.974612] + printf() return : 19
Первая строка здесь выведена системным вызовом write(). Естественно, что вывод производится на управляющий терминал пользовательского процесса insmod, но здесь важно то, что мы выполняем системный вызов write() из кода пространства ядра. Здесь некоторые детали могут потребовать дополнительных объяснений:
Откуда я взял такой «хитрый» прототип описания адресной переменной sys_write? Конечно, я бессовестно списал его из оригинального определения функции sys_write() в ядре, в заголовочном файле <linux/syscalls.h>, что и показано комментарием в коде (в полном коде, в архиве):
/* <linux/syscalls.h>
asmlinkage long sys_write( unsigned int fd,
const char __user *buf,
size_t count ); */
И только так следует поступать для всех используемых не экспортируемых имён ядра — списывая прототипы реализующих функций из соответствующих заголовочных файлов. Любое минимальное несоответствие прототипа приведёт к немедленному краху операционной системы!
Что означают несколько похожих вызовов вида: get_ds(), get_fs(), set_fs()? Это небольшой трюк, состоящий во временной подмене сегментов данных в ядре. Дело в том, что в прототипе обработчика системного вызова sys_write() стоит квалификатор __user, показывающий что указатель указывает на данные в пространстве пользователя. Код системного вызова проверяет принадлежность (только диапазону численного значения адреса), и если адрес указывает на область пространства ядра (как в нашем случае) вызовет аварийное завершение. Таким трюком мы показываем контролирующему коду, что наш адрес следует толковать как принадлежащий к пространству пользователя. В подобных случаях этот трюк можно использовать механически, не особенно задумываясь над его смыслом.
Примечания
Эксперименты с подобными кодами, а тем более в более обстоятельных случаях, которые я предполагаю обсудить позже, чреваты неприятностями — даже незначительные ошибки в коде мгновенно заваливают операционную систему. Ещё хуже то, что система заваливается в неопределённом неустойчивом состоянии, и существует конечная (не высокая) вероятность того, что система не восстановится и после перезагрузки.
Во время экспериментов с подобными кодами меня всё время занимал вопрос: нельзя ли отработку и тестирование их выполнять в виртуальной машине? Это при том, то нам придётся выполнять (в последующем) очень машинно-зависимые вещи, такие как запись в скрытые аппаратные регистры процессора, например CR0.
С удовлетворением могу констатировать, что все обсуждаемые коды адекватно выполняются в виртуальных машинах в среде Oracle VirtualBox, по крайней мере, в относительно последних версиях, начиная от состояния 2013 года.
Поэтому настоятельно рекомендую работать с такими кодами первоначально в виртуальных машинах, дабы избежать серьёзных неприятностей.
Упоминание Oracle VirtualBox вовсе не означает, что это состояние дел не будет сохраняться в других менеджерах виртуальных машин, просто я не проверял коды в этих менеджерах (почти наверняка всё будет благополучно в QEMU/KVM, поскольку VirtualBox заимствует код виртуализации из QEMU).
Архив файлов (кодов) для экспериментов, который упоминается в тексте, можно взять здесь или здесь.
insmod: Unknown symbol in module
Hello everyone!
I am trying to make two kernel modules which uses each other functions. My problem is that I got modules properly compiled, but the symbol is not resolved for one of them.
To make things simple, let’s call these modules as m1 and m2.
m2 is exporting function void func_m2(void). The m1 is calling this function. Both modules properly compiles.
After it all compiles I need to load first the m2 module (because it has exported func_m2 function) and afterwards m1 module. So, let’s make it:
Code:
volodymyr@sv1:~/development/kmodules/m2$ sudo insmod ./m2.koNow, lets load m1 module which is trying to use func_m2:
Code:
volodymyr@sv1:~/development/kmodules/m1$ sudo insmod ./m1.ko insmod: error inserting './m1.ko': -1 Unknown symbol in moduleFollowing is what I see in logs:
Code:
volodymyr@sv1:~/development/kmodules/m1$ dmesg | tail [ 3938.166616] Loading m2 module ... [ 3963.078055] m1: no symbol version for func_m2 [ 3963.078059] m1: Unknown symbol func_m2So, it seems like the refercens to symbol func_m2 is not resolved. Interesting. Let’s check if it is present in symbol table:
Code:
volodymyr@sv1:~/development/kmodules$ cat /proc/kallsyms | grep 'func_m2' ffffffffa00530d0 r __ksymtab_func_m2 [m2] ffffffffa00530e8 r __kstrtab_func_m2 [m2] ffffffffa00530e0 r __kcrctab_func_m2 [m2] ffffffffa0053000 T func_m2 [m2] 000000004edd543f a __crc_func_m2 [m2]As you can see, the func_m2 is actually present in symbol table. So why m1 can’t be loaded?
I have installed properly linux headers for my kernel and linux sources. I did not make any modifications in kernel, it is untouched, and it’s version is: 2.6.31-16-generic (I run x64)
Now, to show you full picture I am putting here the source code and Makefile I used for this test for both m1 and m2 modules.
m1 module:
m1.c:
Code:
#include <linux/module.h> #include <linux/kernel.h> extern void func_m2(void); int hello_start(void) { printk(KERN_INFO "Loading m1 module ...n"); func_m2(); return 0; } void hello_end(void) { printk(KERN_INFO "Unloading m1 ...n"); } module_init(hello_start); module_exit(hello_end); MODULE_LICENSE("GPL");Makefile:
Code:
obj-m := m1.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) cleanm2 module:
m2.c:
Code:
#include <linux/module.h> #include <linux/kernel.h> int hello_start(void) { printk(KERN_INFO "Loading m2 module ...n"); return 0; } void hello_end(void) { printk(KERN_INFO "Unloading m2 ...n"); } void func_m2(void) { printk(KERN_INFO "This a function in m2n"); } module_init(hello_start); module_exit(hello_end); MODULE_LICENSE("GPL"); EXPORT_SYMBOL(func_m2);Makefile:
Code:
obj-m := m2.o export-objs := m2.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
Re: insmod: Unknown symbol in module
Here are some issues I found with your code (after doing some research)…
1. Your initialization and termination functions should be declared static and properly identified. For example, in m1.c:
Code:
... static int __init hello_start(void) { printk(KERN_INFO "Loading m1 module ...n"); func_m2(); return 0; } static void __exit hello_end(void) { printk(KERN_INFO "Unloading m1 ...n"); } ...Repeat this for m2.c.
2. Build both of your modules together, using the same Makefile. I bet if you look closely at the output from your existing Makefile for m1.c, you will see a warning indicating that func_m2() is undefined. Anyhow, the consolidated Makefile should look like:
Code:
SRCS = m1.c m2.c OBJS = $(SRCS:.c=.o) obj-m += $(OBJS) EXTRA_CFLAGS = -O2 all: $(MAKE) -C /lib/modules/`uname -r`/build M=$(PWD) modules clean: $(MAKE) -C /lib/modules/`uname -r`/build M=$(PWD) clean $(RM) Module.markers modules.orderAfter both modules are built, run insmod on ‘m2.ko’ before issuing the insmod for ‘m1.ko’. Check results via dmesg.
Re: insmod: Unknown symbol in module
dwhitney67,
Thank you very much for your help. You saved hours of my time
Compiling both modules in one make file works, thanks!
However I need the projects to be separated in a different directories. Putting them into one directory in one makefile is messy … How can I build each module independently? I can make one makefile which accesses N directories and builds their source files … but I want to avoid that …
Thank you for your help!
P.S. Changing function prototype to static did not changed much, it is more for optiomization I guess.
Re: insmod: Unknown symbol in module
In particular, I have the following structure:
m1 folder contains 2 c files,
m2 folder contains 3 c files
I can’t use your makefile as it generates *.ko per each c file …
Re: insmod: Unknown symbol in module
Sorry to reply back so late…
I did little research and found a way to build modules in separate directories. The example I used is much simpler than what you have, but perhaps it is adaptable.
I have following manifest of files in a directory called ‘ExportSymbol’…
Code:
$ ls -CFR .: include/ Makefile mod1/ mod2/ ./include: m2_func.h ./mod1: Makefile module1.c ./mod2: Makefile module2.cThe m2_func.h appears as:
Code:
#ifndef M2_FUNC_H #define M2_FUNC_H void m2_func(void); #endifThe top-level Makefile appears as:
Code:
obj-y := mod1/ mod2/ all: $(MAKE) -C /lib/modules/`uname -r`/build M=$(PWD) modules clean: $(MAKE) -C /lib/modules/`uname -r`/build M=$(PWD) clean $(RM) Module.markers modules.orderThe Makefile and module1.c, which are in mod1/, appear as:
Code:
SRCS = module1.c OBJS = $(SRCS:.c=.o) obj-m += $(OBJS) EXTRA_CFLAGS += -I${PWD}/include all: $(MAKE) -C /lib/modules/`uname -r`/build M=$(PWD) modules clean: $(MAKE) -C /lib/modules/`uname -r`/build M=$(PWD) clean $(RM) Module.markers modules.orderCode:
#include "m2_func.h" #include <linux/module.h> #include <linux/kernel.h> static int __init hello_start(void) { printk(KERN_INFO "Loading m1 module ...n"); m2_func(); return 0; } static void __exit hello_end(void) { printk(KERN_INFO "Unloading m1 ...n"); } module_init(hello_start); module_exit(hello_end); MODULE_LICENSE("GPL");The Makefile and module2.c, which are in mod2/, appear as:
Code:
SRCS = module2.c OBJS = $(SRCS:.c=.o) obj-m += $(OBJS) EXTRA_CFLAGS += -I${PWD}/include all: $(MAKE) -C /lib/modules/`uname -r`/build M=$(PWD) modules clean: $(MAKE) -C /lib/modules/`uname -r`/build M=$(PWD) clean $(RM) Module.markers modules.orderCode:
#include "m2_func.h" #include <linux/module.h> #include <linux/kernel.h> static int __init hello_start(void) { printk(KERN_INFO "Loading m2 module ...n"); return 0; } static void __exit hello_end(void) { printk(KERN_INFO "Unloading m2 ...n"); } void m2_func(void) { printk(KERN_INFO "This a function in m2n"); } module_init(hello_start); module_exit(hello_end); MODULE_LICENSE("GPL"); EXPORT_SYMBOL(m2_func);I’ve attached the code above in a tar-ball in case you want to copy the source code to your system in a convenient manner.
P.S.
I can’t use your makefile as it generates *.ko per each c file …
Ummm… the Makefile is doing its job. A ‘ko’ file is a kernel object file; you will have one for each .c source file. There’s no way around this. If you do not want multiple ko-files, then put all of your code in one source file.
Last edited by dwhitney67; October 30th, 2010 at 05:24 PM.
Re: insmod: Unknown symbol in module
Hello dwhitney67,
Thank you very much for your help. I am playing with the example of a new Makefile.
Originally Posted by dwhitney67
![]()
P.S.
Ummm… the Makefile is doing its job. A ‘ko’ file is a kernel object file; you will have one for each .c source file. There’s no way around this. If you do not want multiple ko-files, then put all of your code in one source file.
Well, in my previous Makefile for multiple c files I got only one ko file. The makefile which links all object files into one ko is the following:
Code:
obj-m := maindriver.o maindriver-objs := m1.o m2.o m3.o m4.o m5.0 all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) cleanAs you can see, this makefile generates only one ko file: maindriver.ko which consist from m1.c, m2.c, m3.c, m4.c, m5.c source files …
I will try to combine both type of makefiles into one and will see what happen.
Thanks for your help, you gave me a right direction to solve the problem.
Re: insmod: Unknown symbol in module
Originally Posted by volodymyr
![]()
Well, in my previous Makefile for multiple c files I got only one ko file. The makefile which links all object files into one ko is the following:
Code:
obj-m := maindriver.o maindriver-objs := m1.o m2.o m3.o m4.o m5.0 all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) cleanAs you can see, this makefile generates only one ko file: maindriver.ko which consist from m1.c, m2.c, m3.c, m4.c, m5.c source files …
I was not aware of this feature; I need to give it a shot myself.
Thanks for correcting me.
Re: insmod: Unknown symbol in module
It’s working pretty fine for me, basically it links all objects generated from *.c files into one main *ko, i.e. like in Windows
![]()
Re: insmod: Unknown symbol in module
So I confirm that I was able to solve the problem with a mixture of mine and dwhitney67 Makefiles.
I just added EXTRA_CFLAGS += -I${PWD}/include to mine Makefile which uses multiple *.c files to generate one *.ko file . It now compiles and runs perfectly!
Thank you!
Re: insmod: Unknown symbol in module
If you have a kernel loadable module which uses functions provided by other loadable kernel modules, this could happen when you load the module.
To make the test simple, let’s call these 2 modules as m1 and m2.
- The m2 is exporting function void func_m2(void).
- The m1 is calling this function.
- Both modules properly compile.
You can use the following command to see if the function is registered to the kernel by checking the kernel symbol table:
cat /proc/kallsyms | grep 'func_m2'
The compiling is successful, but the loading of m1 failed with:
m1: no symbol version for func_m2
m1: Unknown symbol func_m2
Why?
To check the output of the compiling, you should see the WARNING:
WARNING:"func_m2" undefined!
To fix it,
- Run-time sequence
- Buil-time sequence
You should run insmod on ‘m2.ko’ before issuing the insmod for ‘m1.ko’.
When you build m2, it creates a Module.symvers file. Copy this file to where you are building m1. Then make m1, and insmod it.
Debug Module’s Version Symbol Issue
- Get the version of running kernel
$ uname -rv
5.8.0-53-generic #60~20.04.1-Ubuntu SMP Thu May 6 09:52:46 UTC 2021
$ find /lib/modules -name igc.ko -print
/lib/modules/5.11.0-1003-intel/kernel/drivers/net/ethernet/intel/igc/igc.ko
/lib/modules/5.13.0-1002-oem/kernel/drivers/net/ethernet/intel/igc/igc.ko
$ modinfo /lib/modules/5.11.0-1003-intel/kernel/drivers/net/ethernet/intel/igc/igc.ko
...
vermagic: 5.11.0-1003-intel SMP mod_unload modversions
...
$ sudo apt-file update
$ sudo apt-file find igc
linux-modules-5.10.0-*-oem: /lib/modules/5.10.0-*-oem/kernel/drivers/net/ethernet/intel/igc/igc.ko
linux-modules-5.4.0-*-lowlatency: /lib/modules/5.4.0-*-lowlatency/kernel/drivers/net/ethernet/intel/igc/igc.ko
linux-modules-5.6.0-*-oem: /lib/modules/5.6.0-*-oem/kernel/drivers/net/ethernet/intel/igc/igc.ko
linux-modules-5.8.0-*-lowlatency: /lib/modules/5.8.0-*-lowlatency/kernel/drivers/net/ethernet/intel/igc/igc.ko
linux-modules-extra-5.4.0-*-*: /lib/modules/5.4.0-*-*/kernel/drivers/net/ethernet/intel/igc/igc.ko
$ dpkg -l | grep linux-modules
ii linux-modules-5.11.0-1003-intel 5.11.0-1003.3 amd64 Linux kernel extra modules for version 5.11.0 on 64 bit x86 SMP
ii linux-modules-extra-5.11.0-1003-intel 5.11.0-1003.3 amd64 Linux kernel extra modules for version 5.11.0 on 64 bit x86 SMP
$ dpkg-deb -R linux-modules-5.11.0-1003-intel_5.11.0-1003.3_amd64.deb linux-modules
Building External Modules
This document describes how to build an out-of-tree kernel module. === Table of Contents === 1 Introduction === 2 How to Build External Modules --- 2.1 Command Syntax --- 2.2 Options --- 2.3 Targets --- 2.4 Building Separate Files === 3. Creating a Kbuild File for an External Module --- 3.1 Shared Makefile --- 3.2 Separate Kbuild file and Makefile --- 3.3 Binary Blobs --- 3.4 Building Multiple Modules === 4. Include Files --- 4.1 Kernel Includes --- 4.2 Single Subdirectory --- 4.3 Several Subdirectories === 5. Module Installation --- 5.1 INSTALL_MOD_PATH --- 5.2 INSTALL_MOD_DIR === 6. Module Versioning --- 6.1 Symbols From the Kernel (vmlinux + modules) --- 6.2 Symbols and External Modules --- 6.3 Symbols From Another External Module === 7. Tips & Tricks --- 7.1 Testing for CONFIG_FOO_BAR === 1. Introduction "kbuild" is the build system used by the Linux kernel. Modules must use kbuild to stay compatible with changes in the build infrastructure and to pick up the right flags to "gcc." Functionality for building modules both in-tree and out-of-tree is provided. The method for building either is similar, and all modules are initially developed and built out-of-tree. Covered in this document is information aimed at developers interested in building out-of-tree (or "external") modules. The author of an external module should supply a makefile that hides most of the complexity, so one only has to type "make" to build the module. This is easily accomplished, and a complete example will be presented in section 3. === 2. How to Build External Modules To build external modules, you must have a prebuilt kernel available that contains the configuration and header files used in the build. Also, the kernel must have been built with modules enabled. If you are using a distribution kernel, there will be a package for the kernel you are running provided by your distribution. An alternative is to use the "make" target "modules_prepare." This will make sure the kernel contains the information required. The target exists solely as a simple way to prepare a kernel source tree for building external modules. NOTE: "modules_prepare" will not build Module.symvers even if CONFIG_MODVERSIONS is set; therefore, a full kernel build needs to be executed to make module versioning work. --- 2.1 Command Syntax The command to build an external module is: $ make -C M=$PWD The kbuild system knows that an external module is being built due to the "M=" option given in the command. To build against the running kernel use: $ make -C /lib/modules/`uname -r`/build M=$PWD Then to install the module(s) just built, add the target "modules_install" to the command: $ make -C /lib/modules/`uname -r`/build M=$PWD modules_install --- 2.2 Options ($KDIR refers to the path of the kernel source directory.) make -C $KDIR M=$PWD -C $KDIR The directory where the kernel source is located. "make" will actually change to the specified directory when executing and will change back when finished. M=$PWD Informs kbuild that an external module is being built. The value given to "M" is the absolute path of the directory where the external module (kbuild file) is located. --- 2.3 Targets When building an external module, only a subset of the "make" targets are available. make -C $KDIR M=$PWD [target] The default will build the module(s) located in the current directory, so a target does not need to be specified. All output files will also be generated in this directory. No attempts are made to update the kernel source, and it is a precondition that a successful "make" has been executed for the kernel. modules The default target for external modules. It has the same functionality as if no target was specified. See description above. modules_install Install the external module(s). The default location is /lib/modules//extra/, but a prefix may be added with INSTALL_MOD_PATH (discussed in section 5). clean Remove all generated files in the module directory only. help List the available targets for external modules. --- 2.4 Building Separate Files It is possible to build single files that are part of a module. This works equally well for the kernel, a module, and even for external modules. Example (The module foo.ko, consist of bar.o and baz.o): make -C $KDIR M=$PWD bar.lst make -C $KDIR M=$PWD baz.o make -C $KDIR M=$PWD foo.ko make -C $KDIR M=$PWD / === 3. Creating a Kbuild File for an External Module In the last section we saw the command to build a module for the running kernel. The module is not actually built, however, because a build file is required. Contained in this file will be the name of the module(s) being built, along with the list of requisite source files. The file may be as simple as a single line: obj-m := module_name.o The kbuild system will build .o from .c, and, after linking, will result in the kernel module .ko. The above line can be put in either a "Kbuild" file or a "Makefile." When the module is built from multiple sources, an additional line is needed listing the files: module_name-y := obj1.o obj2.o ... NOTE: Further documentation describing the syntax used by kbuild is located in Documentation/kbuild/makefiles.txt. The examples below demonstrate how to create a build file for the module 8123.ko, which is built from the following files: 8123_if.c 8123_if.h 8123_pci.c 8123_bin.o_shipped <= Binary blob --- 3.1 Shared Makefile An external module always includes a wrapper makefile that supports building the module using "make" with no arguments. This target is not used by kbuild; it is only for convenience. Additional functionality, such as test targets, can be included but should be filtered out from kbuild due to possible name clashes. Example 1: --> filename: Makefile ifneq ($(KERNELRELEASE),) # kbuild part of makefile obj-m := 8123.o 8123-y := 8123_if.o 8123_pci.o 8123_bin.o else # normal makefile KDIR ?= /lib/modules/`uname -r`/build default: $(MAKE) -C $(KDIR) M=$$PWD # Module specific targets genbin: echo "X" > 8123_bin.o_shipped endif The check for KERNELRELEASE is used to separate the two parts of the makefile. In the example, kbuild will only see the two assignments, whereas "make" will see everything except these two assignments. This is due to two passes made on the file: the first pass is by the "make" instance run on the command line; the second pass is by the kbuild system, which is initiated by the parameterized "make" in the default target. --- 3.2 Separate Kbuild File and Makefile In newer versions of the kernel, kbuild will first look for a file named "Kbuild," and only if that is not found, will it then look for a makefile. Utilizing a "Kbuild" file allows us to split up the makefile from example 1 into two files: Example 2: --> filename: Kbuild obj-m := 8123.o 8123-y := 8123_if.o 8123_pci.o 8123_bin.o --> filename: Makefile KDIR ?= /lib/modules/`uname -r`/build default: $(MAKE) -C $(KDIR) M=$$PWD # Module specific targets genbin: echo "X" > 8123_bin.o_shipped The split in example 2 is questionable due to the simplicity of each file; however, some external modules use makefiles consisting of several hundred lines, and here it really pays off to separate the kbuild part from the rest. The next example shows a backward compatible version. Example 3: --> filename: Kbuild obj-m := 8123.o 8123-y := 8123_if.o 8123_pci.o 8123_bin.o --> filename: Makefile ifneq ($(KERNELRELEASE),) # kbuild part of makefile include Kbuild else # normal makefile KDIR ?= /lib/modules/`uname -r`/build default: $(MAKE) -C $(KDIR) M=$$PWD # Module specific targets genbin: echo "X" > 8123_bin.o_shipped endif Here the "Kbuild" file is included from the makefile. This allows an older version of kbuild, which only knows of makefiles, to be used when the "make" and kbuild parts are split into separate files. --- 3.3 Binary Blobs Some external modules need to include an object file as a blob. kbuild has support for this, but requires the blob file to be named _shipped. When the kbuild rules kick in, a copy of _shipped is created with _shipped stripped off, giving us . This shortened filename can be used in the assignment to the module. Throughout this section, 8123_bin.o_shipped has been used to build the kernel module 8123.ko; it has been included as 8123_bin.o. 8123-y := 8123_if.o 8123_pci.o 8123_bin.o Although there is no distinction between the ordinary source files and the binary file, kbuild will pick up different rules when creating the object file for the module. --- 3.4 Building Multiple Modules kbuild supports building multiple modules with a single build file. For example, if you wanted to build two modules, foo.ko and bar.ko, the kbuild lines would be: obj-m := foo.o bar.o foo-y := bar-y := It is that simple! === 4. Include Files Within the kernel, header files are kept in standard locations according to the following rule: * If the header file only describes the internal interface of a module, then the file is placed in the same directory as the source files. * If the header file describes an interface used by other parts of the kernel that are located in different directories, then the file is placed in include/linux/. NOTE: There are two notable exceptions to this rule: larger subsystems have their own directory under include/, such as include/scsi; and architecture specific headers are located under arch/$(ARCH)/include/. --- 4.1 Kernel Includes To include a header file located under include/linux/, simply use: #include kbuild will add options to "gcc" so the relevant directories are searched. --- 4.2 Single Subdirectory External modules tend to place header files in a separate include/ directory where their source is located, although this is not the usual kernel style. To inform kbuild of the directory, use either ccflags-y or CFLAGS_.o. Using the example from section 3, if we moved 8123_if.h to a subdirectory named include, the resulting kbuild file would look like: --> filename: Kbuild obj-m := 8123.o ccflags-y := -Iinclude 8123-y := 8123_if.o 8123_pci.o 8123_bin.o Note that in the assignment there is no space between -I and the path. This is a limitation of kbuild: there must be no space present. --- 4.3 Several Subdirectories kbuild can handle files that are spread over several directories. Consider the following example: . |__ src | |__ complex_main.c | |__ hal | |__ hardwareif.c | |__ include | |__ hardwareif.h |__ include |__ complex.h To build the module complex.ko, we then need the following kbuild file: --> filename: Kbuild obj-m := complex.o complex-y := src/complex_main.o complex-y += src/hal/hardwareif.o ccflags-y := -I$(src)/include ccflags-y += -I$(src)/src/hal/include As you can see, kbuild knows how to handle object files located in other directories. The trick is to specify the directory relative to the kbuild file's location. That being said, this is NOT recommended practice. For the header files, kbuild must be explicitly told where to look. When kbuild executes, the current directory is always the root of the kernel tree (the argument to "-C") and therefore an absolute path is needed. $(src) provides the absolute path by pointing to the directory where the currently executing kbuild file is located. === 5. Module Installation Modules which are included in the kernel are installed in the directory: /lib/modules/$(KERNELRELEASE)/kernel/ And external modules are installed in: /lib/modules/$(KERNELRELEASE)/extra/ --- 5.1 INSTALL_MOD_PATH Above are the default directories but as always some level of customization is possible. A prefix can be added to the installation path using the variable INSTALL_MOD_PATH: $ make INSTALL_MOD_PATH=/frodo modules_install => Install dir: /frodo/lib/modules/$(KERNELRELEASE)/kernel/ INSTALL_MOD_PATH may be set as an ordinary shell variable or, as shown above, can be specified on the command line when calling "make." This has effect when installing both in-tree and out-of-tree modules. --- 5.2 INSTALL_MOD_DIR External modules are by default installed to a directory under /lib/modules/$(KERNELRELEASE)/extra/, but you may wish to locate modules for a specific functionality in a separate directory. For this purpose, use INSTALL_MOD_DIR to specify an alternative name to "extra." $ make INSTALL_MOD_DIR=gandalf -C $KDIR M=$PWD modules_install => Install dir: /lib/modules/$(KERNELRELEASE)/gandalf/ === 6. Module Versioning Module versioning is enabled by the CONFIG_MODVERSIONS tag, and is used as a simple ABI consistency check. A CRC value of the full prototype for an exported symbol is created. When a module is loaded/used, the CRC values contained in the kernel are compared with similar values in the module; if they are not equal, the kernel refuses to load the module. Module.symvers contains a list of all exported symbols from a kernel build. --- 6.1 Symbols From the Kernel (vmlinux + modules) During a kernel build, a file named Module.symvers will be generated. Module.symvers contains all exported symbols from the kernel and compiled modules. For each symbol, the corresponding CRC value is also stored. The syntax of the Module.symvers file is: 0x2d036834 scsi_remove_host drivers/scsi/scsi_mod For a kernel build without CONFIG_MODVERSIONS enabled, the CRC would read 0x00000000. Module.symvers serves two purposes: 1) It lists all exported symbols from vmlinux and all modules. 2) It lists the CRC if CONFIG_MODVERSIONS is enabled. --- 6.2 Symbols and External Modules When building an external module, the build system needs access to the symbols from the kernel to check if all external symbols are defined. This is done in the MODPOST step. modpost obtains the symbols by reading Module.symvers from the kernel source tree. If a Module.symvers file is present in the directory where the external module is being built, this file will be read too. During the MODPOST step, a new Module.symvers file will be written containing all exported symbols that were not defined in the kernel. --- 6.3 Symbols From Another External Module Sometimes, an external module uses exported symbols from another external module. kbuild needs to have full knowledge of all symbols to avoid spitting out warnings about undefined symbols. Three solutions exist for this situation. NOTE: The method with a top-level kbuild file is recommended but may be impractical in certain situations. Use a top-level kbuild file If you have two modules, foo.ko and bar.ko, where foo.ko needs symbols from bar.ko, you can use a common top-level kbuild file so both modules are compiled in the same build. Consider the following directory layout: ./foo/ <= contains foo.ko ./bar/ <= contains bar.ko The top-level kbuild file would then look like: #./Kbuild (or ./Makefile): obj-y := foo/ bar/ And executing $ make -C $KDIR M=$PWD will then do the expected and compile both modules with full knowledge of symbols from either module. Use an extra Module.symvers file When an external module is built, a Module.symvers file is generated containing all exported symbols which are not defined in the kernel. To get access to symbols from bar.ko, copy the Module.symvers file from the compilation of bar.ko to the directory where foo.ko is built. During the module build, kbuild will read the Module.symvers file in the directory of the external module, and when the build is finished, a new Module.symvers file is created containing the sum of all symbols defined and not part of the kernel. Use "make" variable KBUILD_EXTRA_SYMBOLS If it is impractical to copy Module.symvers from another module, you can assign a space separated list of files to KBUILD_EXTRA_SYMBOLS in your build file. These files will be loaded by modpost during the initialization of its symbol tables. === 7. Tips & Tricks --- 7.1 Testing for CONFIG_FOO_BAR Modules often need to check for certain CONFIG_ options to decide if a specific feature is included in the module. In kbuild this is done by referencing the CONFIG_ variable directly. #fs/ext2/Makefile obj-$(CONFIG_EXT2_FS) += ext2.o ext2-y := balloc.o bitmap.o dir.o ext2-$(CONFIG_EXT2_FS_XATTR) += xattr.o External modules have traditionally used "grep" to check for specific CONFIG_ settings directly in .config. This usage is broken. As introduced before, external modules should use kbuild for building and can therefore use the same methods as in-tree modules when testing for CONFIG_ definitions.