1.准备如下测试用例,并编译成模块
hi.c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("cbx");
int testModule(int a, int b)
{
return a + b;
}
EXPORT_SYMBOL_GPL(testModule);
static int testModule_init(void)
{
printk("testModule init/n");
return 0;
}
static void testModule_exit(void)
{
printk("testModule exit/n");
}
module_init(testModule_init);
module_exit(testModule_exit);
Makefile(注意GCOV_PROFILE=y)
export sourcepath ?= $(shell pwd)
KERNEL_DIR :=/home/cuibixuan/git/linux
ARCH :=x86_64
GCOV_PROFILE=y # 对此模块做覆盖统计
ifneq ($(KERNELRELEASE),)
obj-m += test.o
else
default:
$(MAKE) -C $(KERNEL_DIR) CROSS_COMPILE=$(CROSS_COMPILE) ARCH=$(ARCH) M=$(sourcepath) modules
clean:
rm -rf *.o *.mod.c *.mod.o *.ko .*.mod .*.cmd .tmp_versions modules.order Module.symvers
endif
test.c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("cbx");
extern int testModule(int a, int b);
static int test_init(void)
{
printk("test init/n");
testModule(1, 2);
return 0;
}
static void test_exit(void)
{
printk("test exit/n");
}
module_init(test_init);
module_exit(test_exit);
主要是把gcov kernel选上,还有gcov profile选上。
在makefile增加GCOV_PROFILE=y
存放gcda的路径为:/sys/kernel/debug/gcov,如果目录下空,则执行下面命令:
mount -t debugfs nodev /sys/kernel/debug/
2.对hi.ko中模块代码做统计
# lcov -z
Auto-detecting gcov kernel support.
Found upstream gcov kernel support at /sys/kernel/debug/gcov
Resetting kernel execution counters
Done.
# insmod hi.ko
# insmod test.ko
# lcov -d . -t test -o test.info -b . -c
error: geninfo: WARNING: no .gcda files found in . - skipping!
(使用下面命令解决,主要是将/sys/kernel/debug/gcov/下统计后生产的.gcda和模块编译目录的.gcno放在一起,才能做统计)
# cp /sys/kernel/debug/gcov/home/cuibixuan/testModule/* ./
(这里./ 是编译hi.ko的目录)
# lcov -d . -t test -o test.info -b . -c
Capturing coverage data from .
Found gcov version: 5.4.0
Scanning . for .gcda files ...
Found 2 data files in .
Processing hi.gcda
Processing test.gcda
Finished .info-file creation
# lcov -l test.info
Reading tracefile test.info
|Lines |Functions |Branches
Filename |Rate Num|Rate Num|Rate Num
==================================================
[/home/cuibixuan/testModule/]
hi.c |62.5% 8|66.7% 3| - 0
test.c |57.1% 7|50.0% 2| - 0
==================================================
Total:|60.0% 15|60.0% 5| - 0