轉載:http://blog.csdn.net/sanchuyayun/article/details/39183941
剛剛接觸內核,在調試過程中用printk打印信息當然是直接有效的辦法,但當我們不知到一個函數或者一個模塊到底在哪里出了問題時我們可以利用dump_stack有效的找到問題的根源,下面只是簡單的給出了使用方法。
我在自己的主機上試了一下dump_stack()
Makefile文件
obj-m := hello.o KERNELBUILD :=/lib/modules/$(shell uname -r)/build default: make -C $(KERNELBUILD) M=$(shell pwd) modules clean: rm -rf *.o *.ko *.mod.c .*.cmd *.markers *.order *.symvers .tmp_versions
hello.c文件
#include <linux/module.h> #include <linux/init.h> #include <linux/kprobes.h> #include <asm/traps.h> MODULE_LICENSE("Dual BSD/GPL"); static int __init hello_init(void) { printk(KERN_ALERT "dump_stack start\n"); dump_stack(); printk(KERN_ALERT "dump_stack over\n"); return 0; } static void __exit hello_exit(void) { printk(KERN_ALERT "test module\n"); } module_init(hello_init); module_exit(hello_exit);
注意使用dump_stack()要加上這兩個頭文件
#include <linux/kprobes.h> #include <asm/traps.h>
然后make得到hello.ko
在運行insmod hello.ko把模塊插入內核
運行dmesg
[ 3719.352022] usb 1-8: new high speed USB device number 11 using ehci_hcd [ 4266.252826] usb 1-8: USB disconnect, device number 11 [ 5246.942980] dump_stack start [ 5246.942985] Pid: 3438, comm: insmod Not tainted 3.0.0-21-generic #35-Ubuntu [ 5246.942987] Call Trace: [ 5246.942993] [<ffffffffa0072017>] hello_init+0x17/0x1000 [hello] [ 5246.942999] [<ffffffff81002042>] do_one_initcall+0x42/0x180 [ 5246.943003] [<ffffffff810a011e>] sys_init_module+0xbe/0x230 [ 5246.943006] [<ffffffff815fd202>] system_call_fastpath+0x16/0x1b [ 5246.943008] dump_stack over
打出運行這個模塊時調用的函數
刪除模rmmod hello
補充:
Android.mk文件
obj-m := hello.o #hello-objs := hello-world.o KVERSION := $(ANDROID_PRODUCT_OUT)/obj/KERNEL_OBJ all: make ARCH=arm CROSS_COMPILE=arm-eabi- -C $(KVERSION) M=$(PWD) modules clean: make -C $(KVERSION) M=$(PWD) clean
在android編譯環境下編譯,編譯出來的.ko文件可以在手機中insmod。