Path: blob/master/samples/kprobes/kprobe_example.c
10818 views
/*1* NOTE: This example is works on x86 and powerpc.2* Here's a sample kernel module showing the use of kprobes to dump a3* stack trace and selected registers when do_fork() is called.4*5* For more information on theory of operation of kprobes, see6* Documentation/kprobes.txt7*8* You will see the trace data in /var/log/messages and on the console9* whenever do_fork() is invoked to create a new process.10*/1112#include <linux/kernel.h>13#include <linux/module.h>14#include <linux/kprobes.h>1516/* For each probe you need to allocate a kprobe structure */17static struct kprobe kp = {18.symbol_name = "do_fork",19};2021/* kprobe pre_handler: called just before the probed instruction is executed */22static int handler_pre(struct kprobe *p, struct pt_regs *regs)23{24#ifdef CONFIG_X8625printk(KERN_INFO "pre_handler: p->addr = 0x%p, ip = %lx,"26" flags = 0x%lx\n",27p->addr, regs->ip, regs->flags);28#endif29#ifdef CONFIG_PPC30printk(KERN_INFO "pre_handler: p->addr = 0x%p, nip = 0x%lx,"31" msr = 0x%lx\n",32p->addr, regs->nip, regs->msr);33#endif34#ifdef CONFIG_MIPS35printk(KERN_INFO "pre_handler: p->addr = 0x%p, epc = 0x%lx,"36" status = 0x%lx\n",37p->addr, regs->cp0_epc, regs->cp0_status);38#endif3940/* A dump_stack() here will give a stack backtrace */41return 0;42}4344/* kprobe post_handler: called after the probed instruction is executed */45static void handler_post(struct kprobe *p, struct pt_regs *regs,46unsigned long flags)47{48#ifdef CONFIG_X8649printk(KERN_INFO "post_handler: p->addr = 0x%p, flags = 0x%lx\n",50p->addr, regs->flags);51#endif52#ifdef CONFIG_PPC53printk(KERN_INFO "post_handler: p->addr = 0x%p, msr = 0x%lx\n",54p->addr, regs->msr);55#endif56#ifdef CONFIG_MIPS57printk(KERN_INFO "post_handler: p->addr = 0x%p, status = 0x%lx\n",58p->addr, regs->cp0_status);59#endif60}6162/*63* fault_handler: this is called if an exception is generated for any64* instruction within the pre- or post-handler, or when Kprobes65* single-steps the probed instruction.66*/67static int handler_fault(struct kprobe *p, struct pt_regs *regs, int trapnr)68{69printk(KERN_INFO "fault_handler: p->addr = 0x%p, trap #%dn",70p->addr, trapnr);71/* Return 0 because we don't handle the fault. */72return 0;73}7475static int __init kprobe_init(void)76{77int ret;78kp.pre_handler = handler_pre;79kp.post_handler = handler_post;80kp.fault_handler = handler_fault;8182ret = register_kprobe(&kp);83if (ret < 0) {84printk(KERN_INFO "register_kprobe failed, returned %d\n", ret);85return ret;86}87printk(KERN_INFO "Planted kprobe at %p\n", kp.addr);88return 0;89}9091static void __exit kprobe_exit(void)92{93unregister_kprobe(&kp);94printk(KERN_INFO "kprobe at %p unregistered\n", kp.addr);95}9697module_init(kprobe_init)98module_exit(kprobe_exit)99MODULE_LICENSE("GPL");100101102