I can use kprobe
mechanism to attach handlers using following example code:
#include <asm/uaccess.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/version.h>
#include <linux/kallsyms.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/kprobes.h>
static struct kprobe kp;
int Pre_Handler(struct kprobe *p, struct pt_regs *regs){
printk("pre_handler\n");
return 0;
}
void Post_Handler(struct kprobe *p, struct pt_regs *regs, unsigned long flags) {
printk("post_handler\n");
}
int __init init (void) {
kp.pre_handler = Pre_Handler;
kp.post_handler = Post_Handler;
kp.addr = (kprobe_opcode_t *)kallsyms_lookup_name("sys_fork");
printk("%d\n", register_kprobe(&kp));
return 0;
}
void __exit cleanup(void) {
unregister_kprobe(&kp);
}
MODULE_LICENSE("GPL");
module_init(init);
module_exit(cleanup);
However, it looks like not all kernel routines can be tracked this way. I've tried to attach handlers to system_call
to have them called with any system call execution with following change:
kp.addr = (kprobe_opcode_t *)kallsyms_lookup_name("system_call");
And probes aren't inserted. dmesg
shows that register_kprobe
returns -22 which is -EINVAL
. Why is this function impossible to trace? Is it possible to attach kprobe handler before dispatching any system call?
$ uname -r
3.8.0-29-generic