1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include <linux/kprobes.h>
4 
5 /* Ftrace callback handler for kprobes -- called under preepmt disabled */
kprobe_ftrace_handler(unsigned long ip,unsigned long parent_ip,struct ftrace_ops * ops,struct ftrace_regs * fregs)6 void kprobe_ftrace_handler(unsigned long ip, unsigned long parent_ip,
7 			   struct ftrace_ops *ops, struct ftrace_regs *fregs)
8 {
9 	struct kprobe *p;
10 	struct pt_regs *regs;
11 	struct kprobe_ctlblk *kcb;
12 	int bit;
13 
14 	bit = ftrace_test_recursion_trylock(ip, parent_ip);
15 	if (bit < 0)
16 		return;
17 
18 	preempt_disable_notrace();
19 	p = get_kprobe((kprobe_opcode_t *)ip);
20 	if (unlikely(!p) || kprobe_disabled(p))
21 		goto out;
22 
23 	regs = ftrace_get_regs(fregs);
24 	kcb = get_kprobe_ctlblk();
25 	if (kprobe_running()) {
26 		kprobes_inc_nmissed_count(p);
27 	} else {
28 		unsigned long orig_ip = instruction_pointer(regs);
29 
30 		instruction_pointer_set(regs, ip);
31 
32 		__this_cpu_write(current_kprobe, p);
33 		kcb->kprobe_status = KPROBE_HIT_ACTIVE;
34 		if (!p->pre_handler || !p->pre_handler(p, regs)) {
35 			/*
36 			 * Emulate singlestep (and also recover regs->pc)
37 			 * as if there is a nop
38 			 */
39 			instruction_pointer_set(regs,
40 				(unsigned long)p->addr + MCOUNT_INSN_SIZE);
41 			if (unlikely(p->post_handler)) {
42 				kcb->kprobe_status = KPROBE_HIT_SSDONE;
43 				p->post_handler(p, regs, 0);
44 			}
45 			instruction_pointer_set(regs, orig_ip);
46 		}
47 
48 		/*
49 		 * If pre_handler returns !0, it changes regs->pc. We have to
50 		 * skip emulating post_handler.
51 		 */
52 		__this_cpu_write(current_kprobe, NULL);
53 	}
54 out:
55 	preempt_enable_notrace();
56 	ftrace_test_recursion_unlock(bit);
57 }
58 NOKPROBE_SYMBOL(kprobe_ftrace_handler);
59 
arch_prepare_kprobe_ftrace(struct kprobe * p)60 int arch_prepare_kprobe_ftrace(struct kprobe *p)
61 {
62 	p->ainsn.api.insn = NULL;
63 	return 0;
64 }
65