xref: /linux/arch/powerpc/kernel/rethook.c (revision 00389c58ffe993782a8ba4bb5a34a102b1f6fe24)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * PowerPC implementation of rethook. This depends on kprobes.
4  */
5 
6 #include <linux/kprobes.h>
7 #include <linux/rethook.h>
8 
9 /*
10  * Function return trampoline:
11  * 	- init_kprobes() establishes a probepoint here
12  * 	- When the probed function returns, this probe
13  * 		causes the handlers to fire
14  */
15 asm(".global arch_rethook_trampoline\n"
16 	".type arch_rethook_trampoline, @function\n"
17 	"arch_rethook_trampoline:\n"
18 	"nop\n"
19 	"blr\n"
20 	".size arch_rethook_trampoline, .-arch_rethook_trampoline\n");
21 
22 /*
23  * Called when the probe at kretprobe trampoline is hit
24  */
25 static int trampoline_rethook_handler(struct kprobe *p, struct pt_regs *regs)
26 {
27 	unsigned long orig_ret_address;
28 
29 	orig_ret_address = rethook_trampoline_handler(regs, 0);
30 	/*
31 	 * We get here through one of two paths:
32 	 * 1. by taking a trap -> kprobe_handler() -> here
33 	 * 2. by optprobe branch -> optimized_callback() -> opt_pre_handler() -> here
34 	 *
35 	 * When going back through (1), we need regs->nip to be setup properly
36 	 * as it is used to determine the return address from the trap.
37 	 * For (2), since nip is not honoured with optprobes, we instead setup
38 	 * the link register properly so that the subsequent 'blr' in
39 	 * __kretprobe_trampoline jumps back to the right instruction.
40 	 *
41 	 * For nip, we should set the address to the previous instruction since
42 	 * we end up emulating it in kprobe_handler(), which increments the nip
43 	 * again.
44 	 */
45 	regs_set_return_ip(regs, orig_ret_address - 4);
46 	regs->link = orig_ret_address;
47 
48 	return 0;
49 }
50 NOKPROBE_SYMBOL(trampoline_rethook_handler);
51 
52 void arch_rethook_prepare(struct rethook_node *rh, struct pt_regs *regs, bool mcount)
53 {
54 	rh->ret_addr = regs->link;
55 	rh->frame = 0;
56 
57 	/* Replace the return addr with trampoline addr */
58 	regs->link = (unsigned long)arch_rethook_trampoline;
59 }
60 NOKPROBE_SYMBOL(arch_prepare_kretprobe);
61 
62 static struct kprobe trampoline_p = {
63 	.addr = (kprobe_opcode_t *) &arch_rethook_trampoline,
64 	.pre_handler = trampoline_rethook_handler
65 };
66 
67 static int init_arch_rethook(void)
68 {
69 	return register_kprobe(&trampoline_p);
70 }
71 
72 core_initcall(init_arch_rethook);
73