系统相关
首页 > 系统相关> > Linux kernel 使用 kprobe

Linux kernel 使用 kprobe

作者:互联网

 1 #include <linux/module.h>
 2 #include <linux/file.h>
 3 #include <linux/uaccess.h>
 4 #include <linux/kallsyms.h>
 5 #include <linux/kprobes.h>
 6 
 7 //
 8 // long do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode)
 9 //
10 //
11 //
12 static struct kprobe kp = {
13     .symbol_name = "do_sys_open",
14 };
15 static int handler_pre(struct kprobe *p, struct pt_regs *regs)
16 {
17     //printk(KERN_INFO "pre_handler: p->addr = 0x%p, ip = %lx,"
18     //        " flags = 0x%lx\n",
19     //        p->addr, regs->ip, regs->flags);  /*打印地址、指令和标识*/
20 
21     
22     
23 
24     /* 在这里可以调用内核接口函数dump_stack打印出栈的内容*/
25     return 0;
26 }
27 
28 static void handler_post(struct kprobe *p, struct pt_regs *regs,
29                 unsigned long flags)
30 {
31     //printk(KERN_INFO "post_handler: p->addr = 0x%p, flags = 0x%lx\n",
32     //    p->addr, regs->flags);
33     pr_err("");
34 
35     //pr_err("pid: %d do fork\n", current->pid);
36     //pr_err("ppid: %d do fork\n", current->parent->pid);
37         
38 }
39 
40 /*在pre-handler或post-handler中的任何指令或者kprobe单步执行的被探测指令产生了例外时,会调用fault_handler*/
41 static int handler_fault(struct kprobe *p, struct pt_regs *regs, int trapnr)
42 {
43     printk(KERN_INFO "fault_handler: p->addr = 0x%p, trap #%dn",
44         p->addr, trapnr);
45     /* 不处理错误时应该返回*/
46     return 0;
47 }
48 
49 static int __init driver_init(void)
50 {
51 
52     
53     int ret;
54     
55     kp.pre_handler = handler_pre;
56     kp.post_handler = handler_post;
57     kp.fault_handler = handler_fault;
58     
59     ret = register_kprobe(&kp);  /*注册kprobe*/
60     if (ret < 0) {
61         printk(KERN_INFO "register_kprobe failed, returned %d\n", ret);
62         return ret;
63     }
64     
65     printk(KERN_INFO "Planted kprobe at %p\n", kp.addr);
66     pr_err("driver_init");
67     return 0;
68 }
69 
70 static void __exit driver_exit(void)
71 {
72     pr_err("driver_exit");
73     unregister_kprobe(&kp);
74     printk(KERN_INFO "kprobe at %p unregistered\n", kp.addr);
75 }
76 
77 
78 
79 
80 MODULE_LICENSE("GPL");
81 module_init(driver_init);
82 module_exit(driver_exit);
 1 ifeq ($(KERNELRELEASE),)
 2 
 3 KERNELDIR ?=/lib/modules/$(shell uname -r)/build
 4 PWD := $(shell pwd)
 5 
 6 modules:
 7     $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
 8 
 9 modules_install:
10     $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install
11 
12 clean:
13     rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions modules* Module*
14 
15 .PHONY: modules modules_install clean
16 
17 else
18     obj-m += kprobe_.o
19     kprobe_-objs := kprobe.o
20 endif

 

标签:kernel,addr,modules,regs,kprobe,handler,Linux,kp
来源: https://www.cnblogs.com/maojun1998/p/13695477.html