clinux-kernelkernelinterceptionprobing

Linux, kprobes/kretprobes: a way to recover [from registers?] probe function's arguments?


/*kprobe_example.c*/
#define FUNCNAME alloc_file /* Find something better. printk() isnt recommended */
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/kprobes.h>
#include <linux/kallsyms.h>
#include <linux/sched.h>
/*For each probe you need to allocate a kprobe structure*/
static struct kprobe kp;

/*kprobe pre_handler: called just before the probed instruction is
executed*/
int handler_pre(struct kprobe *p, struct pt_regs *regs)
{
//      dump_stack();
        return 0;
}

/*kprobe post_handler: called after the probed instruction is executed*/
void handler_post(struct kprobe *p, struct pt_regs *regs, unsigned long
flags)
{

}

/* fault_handler: this is called if an exception is generated for any
 * instruction within the pre- or post-handler, or when Kprobes
 * single-steps the probed instruction.
 */
int handler_fault(struct kprobe *p, struct pt_regs *regs, int trapnr)
{
        /* Return 0 because we don't handle the fault. */
        return 0;
}

int init_module(void)
{
        int ret;
        kp.pre_handler = handler_pre;
        kp.post_handler = handler_post;
        kp.fault_handler = handler_fault;
        kp.addr = (kprobe_opcode_t*) kallsyms_lookup_name(FUNCNAME);
        /* register the kprobe now */
        if (!kp.addr) {
                printk("Couldn't find %s to plant kprobe\n", FUNCNAME);
                return -1;
        }
        if ((ret = register_kprobe(&kp) < 0)) {
                printk("register_kprobe failed, returned %d\n", ret);
                return -1;
        }
        printk("kprobe registered\n");
        return 0;
}

void cleanup_module(void)
{
        unregister_kprobe(&kp);
        printk("kprobe unregistered\n");
}

MODULE_LICENSE("GPL");

The question is simple: I need pointers to probed (intercepted) function's arguments. Is there any way to get/recover them from registers?


Solution

  • The answer is jprobes.

    Be afraid of redhat's example code missing my_jprobe.kp.addr = (kprobe_opcode_t *) kallsyms_lookup_name(FUNCAME);

    Another problem is, that to caught and modify a return value, a better place for probing should be found (refer to http://lwn.net/Articles/132196/ for better understanding).