0

Is it possible to hook/callback kernel function to my kernel module by ftrace or anyway.

for example: I want hook each time the function net_tx_action() called to my module, included arguments.

regards peter

Robber Pen
  • 1,033
  • 2
  • 12
  • 24
  • Perhaps, you can use Kprobes (Jprobes, to be exact), for that purpose. See http://elixir.free-electrons.com/linux/latest/source/Documentation/kprobes.txt and http://elixir.free-electrons.com/linux/latest/source/samples/kprobes/jprobe_example.c. – Eugene Jun 25 '17 at 16:42

1 Answers1

0

You can set the IP register to the desired hook function in your ftrace callback:

static void notrace ftrace_callback(unsigned long ip, unsigned long parent_ip,
                struct ftrace_ops *ops, struct pt_regs *regs)
{
        regs->ip = (unsigned long) hook_function;
}

This will make the hook function to execute instead of the hooked function. The hook function should have the same argument types and return value as the original one.

You will also need to save the address of the original hooked function somewhere so that you can call it from your hook function:

static void (*original_function)(void);

static void hook_function(void)
{
        /* some code before */
        original_function();
        /* some code after */
}

However, calling the original function has a caveat: it will recursively call the ftrace callback again, so you need to somehow avoid resetting IP register in this case. One option is to track the recursion manually (count the function activations, set IP only on odd activations).

Here's a working example with the code. It should work for non-IRQ functions. Functions which can be called from interrupt context are trickier because there is no particular task to associate function activations with. I do not have a robust solution for that case yet. Maybe per-CPU variables could help if interrupt handlers cannot be rescheduled to another CPU in mid-execution.

Chris
  • 148
  • 1
  • 9
  • Actually, I have an idea for using `parent_ip` argument which is passed to ftrace callback function. It can be used to weed out original calls made by the hook function based on the module address range. This should allow proper recursive calls and hooks for IRQ functions. I'll try it out. – Chris Apr 20 '18 at 10:46
  • Is it possible to multi programs use this aproarch to hook same kernel function, in same machine ? – TienThanh Aug 09 '23 at 17:55