xref: /openbmc/linux/arch/x86/kernel/kprobes/opt.c (revision dc6a81c3)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Kernel Probes Jump Optimization (Optprobes)
4  *
5  * Copyright (C) IBM Corporation, 2002, 2004
6  * Copyright (C) Hitachi Ltd., 2012
7  */
8 #include <linux/kprobes.h>
9 #include <linux/ptrace.h>
10 #include <linux/string.h>
11 #include <linux/slab.h>
12 #include <linux/hardirq.h>
13 #include <linux/preempt.h>
14 #include <linux/extable.h>
15 #include <linux/kdebug.h>
16 #include <linux/kallsyms.h>
17 #include <linux/ftrace.h>
18 #include <linux/frame.h>
19 
20 #include <asm/text-patching.h>
21 #include <asm/cacheflush.h>
22 #include <asm/desc.h>
23 #include <asm/pgtable.h>
24 #include <linux/uaccess.h>
25 #include <asm/alternative.h>
26 #include <asm/insn.h>
27 #include <asm/debugreg.h>
28 #include <asm/set_memory.h>
29 #include <asm/sections.h>
30 #include <asm/nospec-branch.h>
31 
32 #include "common.h"
33 
34 unsigned long __recover_optprobed_insn(kprobe_opcode_t *buf, unsigned long addr)
35 {
36 	struct optimized_kprobe *op;
37 	struct kprobe *kp;
38 	long offs;
39 	int i;
40 
41 	for (i = 0; i < JMP32_INSN_SIZE; i++) {
42 		kp = get_kprobe((void *)addr - i);
43 		/* This function only handles jump-optimized kprobe */
44 		if (kp && kprobe_optimized(kp)) {
45 			op = container_of(kp, struct optimized_kprobe, kp);
46 			/* If op->list is not empty, op is under optimizing */
47 			if (list_empty(&op->list))
48 				goto found;
49 		}
50 	}
51 
52 	return addr;
53 found:
54 	/*
55 	 * If the kprobe can be optimized, original bytes which can be
56 	 * overwritten by jump destination address. In this case, original
57 	 * bytes must be recovered from op->optinsn.copied_insn buffer.
58 	 */
59 	if (probe_kernel_read(buf, (void *)addr,
60 		MAX_INSN_SIZE * sizeof(kprobe_opcode_t)))
61 		return 0UL;
62 
63 	if (addr == (unsigned long)kp->addr) {
64 		buf[0] = kp->opcode;
65 		memcpy(buf + 1, op->optinsn.copied_insn, DISP32_SIZE);
66 	} else {
67 		offs = addr - (unsigned long)kp->addr - 1;
68 		memcpy(buf, op->optinsn.copied_insn + offs, DISP32_SIZE - offs);
69 	}
70 
71 	return (unsigned long)buf;
72 }
73 
74 /* Insert a move instruction which sets a pointer to eax/rdi (1st arg). */
75 static void synthesize_set_arg1(kprobe_opcode_t *addr, unsigned long val)
76 {
77 #ifdef CONFIG_X86_64
78 	*addr++ = 0x48;
79 	*addr++ = 0xbf;
80 #else
81 	*addr++ = 0xb8;
82 #endif
83 	*(unsigned long *)addr = val;
84 }
85 
86 asm (
87 			".pushsection .rodata\n"
88 			"optprobe_template_func:\n"
89 			".global optprobe_template_entry\n"
90 			"optprobe_template_entry:\n"
91 #ifdef CONFIG_X86_64
92 			/* We don't bother saving the ss register */
93 			"	pushq %rsp\n"
94 			"	pushfq\n"
95 			SAVE_REGS_STRING
96 			"	movq %rsp, %rsi\n"
97 			".global optprobe_template_val\n"
98 			"optprobe_template_val:\n"
99 			ASM_NOP5
100 			ASM_NOP5
101 			".global optprobe_template_call\n"
102 			"optprobe_template_call:\n"
103 			ASM_NOP5
104 			/* Move flags to rsp */
105 			"	movq 18*8(%rsp), %rdx\n"
106 			"	movq %rdx, 19*8(%rsp)\n"
107 			RESTORE_REGS_STRING
108 			/* Skip flags entry */
109 			"	addq $8, %rsp\n"
110 			"	popfq\n"
111 #else /* CONFIG_X86_32 */
112 			"	pushl %esp\n"
113 			"	pushfl\n"
114 			SAVE_REGS_STRING
115 			"	movl %esp, %edx\n"
116 			".global optprobe_template_val\n"
117 			"optprobe_template_val:\n"
118 			ASM_NOP5
119 			".global optprobe_template_call\n"
120 			"optprobe_template_call:\n"
121 			ASM_NOP5
122 			/* Move flags into esp */
123 			"	movl 14*4(%esp), %edx\n"
124 			"	movl %edx, 15*4(%esp)\n"
125 			RESTORE_REGS_STRING
126 			/* Skip flags entry */
127 			"	addl $4, %esp\n"
128 			"	popfl\n"
129 #endif
130 			".global optprobe_template_end\n"
131 			"optprobe_template_end:\n"
132 			".popsection\n");
133 
134 void optprobe_template_func(void);
135 STACK_FRAME_NON_STANDARD(optprobe_template_func);
136 
137 #define TMPL_MOVE_IDX \
138 	((long)optprobe_template_val - (long)optprobe_template_entry)
139 #define TMPL_CALL_IDX \
140 	((long)optprobe_template_call - (long)optprobe_template_entry)
141 #define TMPL_END_IDX \
142 	((long)optprobe_template_end - (long)optprobe_template_entry)
143 
144 /* Optimized kprobe call back function: called from optinsn */
145 static void
146 optimized_callback(struct optimized_kprobe *op, struct pt_regs *regs)
147 {
148 	/* This is possible if op is under delayed unoptimizing */
149 	if (kprobe_disabled(&op->kp))
150 		return;
151 
152 	preempt_disable();
153 	if (kprobe_running()) {
154 		kprobes_inc_nmissed_count(&op->kp);
155 	} else {
156 		struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
157 		/* Save skipped registers */
158 		regs->cs = __KERNEL_CS;
159 #ifdef CONFIG_X86_32
160 		regs->cs |= get_kernel_rpl();
161 		regs->gs = 0;
162 #endif
163 		regs->ip = (unsigned long)op->kp.addr + INT3_INSN_SIZE;
164 		regs->orig_ax = ~0UL;
165 
166 		__this_cpu_write(current_kprobe, &op->kp);
167 		kcb->kprobe_status = KPROBE_HIT_ACTIVE;
168 		opt_pre_handler(&op->kp, regs);
169 		__this_cpu_write(current_kprobe, NULL);
170 	}
171 	preempt_enable();
172 }
173 NOKPROBE_SYMBOL(optimized_callback);
174 
175 static int copy_optimized_instructions(u8 *dest, u8 *src, u8 *real)
176 {
177 	struct insn insn;
178 	int len = 0, ret;
179 
180 	while (len < JMP32_INSN_SIZE) {
181 		ret = __copy_instruction(dest + len, src + len, real + len, &insn);
182 		if (!ret || !can_boost(&insn, src + len))
183 			return -EINVAL;
184 		len += ret;
185 	}
186 	/* Check whether the address range is reserved */
187 	if (ftrace_text_reserved(src, src + len - 1) ||
188 	    alternatives_text_reserved(src, src + len - 1) ||
189 	    jump_label_text_reserved(src, src + len - 1))
190 		return -EBUSY;
191 
192 	return len;
193 }
194 
195 /* Check whether insn is indirect jump */
196 static int __insn_is_indirect_jump(struct insn *insn)
197 {
198 	return ((insn->opcode.bytes[0] == 0xff &&
199 		(X86_MODRM_REG(insn->modrm.value) & 6) == 4) || /* Jump */
200 		insn->opcode.bytes[0] == 0xea);	/* Segment based jump */
201 }
202 
203 /* Check whether insn jumps into specified address range */
204 static int insn_jump_into_range(struct insn *insn, unsigned long start, int len)
205 {
206 	unsigned long target = 0;
207 
208 	switch (insn->opcode.bytes[0]) {
209 	case 0xe0:	/* loopne */
210 	case 0xe1:	/* loope */
211 	case 0xe2:	/* loop */
212 	case 0xe3:	/* jcxz */
213 	case 0xe9:	/* near relative jump */
214 	case 0xeb:	/* short relative jump */
215 		break;
216 	case 0x0f:
217 		if ((insn->opcode.bytes[1] & 0xf0) == 0x80) /* jcc near */
218 			break;
219 		return 0;
220 	default:
221 		if ((insn->opcode.bytes[0] & 0xf0) == 0x70) /* jcc short */
222 			break;
223 		return 0;
224 	}
225 	target = (unsigned long)insn->next_byte + insn->immediate.value;
226 
227 	return (start <= target && target <= start + len);
228 }
229 
230 static int insn_is_indirect_jump(struct insn *insn)
231 {
232 	int ret = __insn_is_indirect_jump(insn);
233 
234 #ifdef CONFIG_RETPOLINE
235 	/*
236 	 * Jump to x86_indirect_thunk_* is treated as an indirect jump.
237 	 * Note that even with CONFIG_RETPOLINE=y, the kernel compiled with
238 	 * older gcc may use indirect jump. So we add this check instead of
239 	 * replace indirect-jump check.
240 	 */
241 	if (!ret)
242 		ret = insn_jump_into_range(insn,
243 				(unsigned long)__indirect_thunk_start,
244 				(unsigned long)__indirect_thunk_end -
245 				(unsigned long)__indirect_thunk_start);
246 #endif
247 	return ret;
248 }
249 
250 /* Decode whole function to ensure any instructions don't jump into target */
251 static int can_optimize(unsigned long paddr)
252 {
253 	unsigned long addr, size = 0, offset = 0;
254 	struct insn insn;
255 	kprobe_opcode_t buf[MAX_INSN_SIZE];
256 
257 	/* Lookup symbol including addr */
258 	if (!kallsyms_lookup_size_offset(paddr, &size, &offset))
259 		return 0;
260 
261 	/*
262 	 * Do not optimize in the entry code due to the unstable
263 	 * stack handling and registers setup.
264 	 */
265 	if (((paddr >= (unsigned long)__entry_text_start) &&
266 	     (paddr <  (unsigned long)__entry_text_end)) ||
267 	    ((paddr >= (unsigned long)__irqentry_text_start) &&
268 	     (paddr <  (unsigned long)__irqentry_text_end)))
269 		return 0;
270 
271 	/* Check there is enough space for a relative jump. */
272 	if (size - offset < JMP32_INSN_SIZE)
273 		return 0;
274 
275 	/* Decode instructions */
276 	addr = paddr - offset;
277 	while (addr < paddr - offset + size) { /* Decode until function end */
278 		unsigned long recovered_insn;
279 		if (search_exception_tables(addr))
280 			/*
281 			 * Since some fixup code will jumps into this function,
282 			 * we can't optimize kprobe in this function.
283 			 */
284 			return 0;
285 		recovered_insn = recover_probed_instruction(buf, addr);
286 		if (!recovered_insn)
287 			return 0;
288 		kernel_insn_init(&insn, (void *)recovered_insn, MAX_INSN_SIZE);
289 		insn_get_length(&insn);
290 		/* Another subsystem puts a breakpoint */
291 		if (insn.opcode.bytes[0] == INT3_INSN_OPCODE)
292 			return 0;
293 		/* Recover address */
294 		insn.kaddr = (void *)addr;
295 		insn.next_byte = (void *)(addr + insn.length);
296 		/* Check any instructions don't jump into target */
297 		if (insn_is_indirect_jump(&insn) ||
298 		    insn_jump_into_range(&insn, paddr + INT3_INSN_SIZE,
299 					 DISP32_SIZE))
300 			return 0;
301 		addr += insn.length;
302 	}
303 
304 	return 1;
305 }
306 
307 /* Check optimized_kprobe can actually be optimized. */
308 int arch_check_optimized_kprobe(struct optimized_kprobe *op)
309 {
310 	int i;
311 	struct kprobe *p;
312 
313 	for (i = 1; i < op->optinsn.size; i++) {
314 		p = get_kprobe(op->kp.addr + i);
315 		if (p && !kprobe_disabled(p))
316 			return -EEXIST;
317 	}
318 
319 	return 0;
320 }
321 
322 /* Check the addr is within the optimized instructions. */
323 int arch_within_optimized_kprobe(struct optimized_kprobe *op,
324 				 unsigned long addr)
325 {
326 	return ((unsigned long)op->kp.addr <= addr &&
327 		(unsigned long)op->kp.addr + op->optinsn.size > addr);
328 }
329 
330 /* Free optimized instruction slot */
331 static
332 void __arch_remove_optimized_kprobe(struct optimized_kprobe *op, int dirty)
333 {
334 	if (op->optinsn.insn) {
335 		free_optinsn_slot(op->optinsn.insn, dirty);
336 		op->optinsn.insn = NULL;
337 		op->optinsn.size = 0;
338 	}
339 }
340 
341 void arch_remove_optimized_kprobe(struct optimized_kprobe *op)
342 {
343 	__arch_remove_optimized_kprobe(op, 1);
344 }
345 
346 /*
347  * Copy replacing target instructions
348  * Target instructions MUST be relocatable (checked inside)
349  * This is called when new aggr(opt)probe is allocated or reused.
350  */
351 int arch_prepare_optimized_kprobe(struct optimized_kprobe *op,
352 				  struct kprobe *__unused)
353 {
354 	u8 *buf = NULL, *slot;
355 	int ret, len;
356 	long rel;
357 
358 	if (!can_optimize((unsigned long)op->kp.addr))
359 		return -EILSEQ;
360 
361 	buf = kzalloc(MAX_OPTINSN_SIZE, GFP_KERNEL);
362 	if (!buf)
363 		return -ENOMEM;
364 
365 	op->optinsn.insn = slot = get_optinsn_slot();
366 	if (!slot) {
367 		ret = -ENOMEM;
368 		goto out;
369 	}
370 
371 	/*
372 	 * Verify if the address gap is in 2GB range, because this uses
373 	 * a relative jump.
374 	 */
375 	rel = (long)slot - (long)op->kp.addr + JMP32_INSN_SIZE;
376 	if (abs(rel) > 0x7fffffff) {
377 		ret = -ERANGE;
378 		goto err;
379 	}
380 
381 	/* Copy arch-dep-instance from template */
382 	memcpy(buf, optprobe_template_entry, TMPL_END_IDX);
383 
384 	/* Copy instructions into the out-of-line buffer */
385 	ret = copy_optimized_instructions(buf + TMPL_END_IDX, op->kp.addr,
386 					  slot + TMPL_END_IDX);
387 	if (ret < 0)
388 		goto err;
389 	op->optinsn.size = ret;
390 	len = TMPL_END_IDX + op->optinsn.size;
391 
392 	/* Set probe information */
393 	synthesize_set_arg1(buf + TMPL_MOVE_IDX, (unsigned long)op);
394 
395 	/* Set probe function call */
396 	synthesize_relcall(buf + TMPL_CALL_IDX,
397 			   slot + TMPL_CALL_IDX, optimized_callback);
398 
399 	/* Set returning jmp instruction at the tail of out-of-line buffer */
400 	synthesize_reljump(buf + len, slot + len,
401 			   (u8 *)op->kp.addr + op->optinsn.size);
402 	len += JMP32_INSN_SIZE;
403 
404 	/* We have to use text_poke() for instruction buffer because it is RO */
405 	text_poke(slot, buf, len);
406 	ret = 0;
407 out:
408 	kfree(buf);
409 	return ret;
410 
411 err:
412 	__arch_remove_optimized_kprobe(op, 0);
413 	goto out;
414 }
415 
416 /*
417  * Replace breakpoints (INT3) with relative jumps (JMP.d32).
418  * Caller must call with locking kprobe_mutex and text_mutex.
419  *
420  * The caller will have installed a regular kprobe and after that issued
421  * syncrhonize_rcu_tasks(), this ensures that the instruction(s) that live in
422  * the 4 bytes after the INT3 are unused and can now be overwritten.
423  */
424 void arch_optimize_kprobes(struct list_head *oplist)
425 {
426 	struct optimized_kprobe *op, *tmp;
427 	u8 insn_buff[JMP32_INSN_SIZE];
428 
429 	list_for_each_entry_safe(op, tmp, oplist, list) {
430 		s32 rel = (s32)((long)op->optinsn.insn -
431 			((long)op->kp.addr + JMP32_INSN_SIZE));
432 
433 		WARN_ON(kprobe_disabled(&op->kp));
434 
435 		/* Backup instructions which will be replaced by jump address */
436 		memcpy(op->optinsn.copied_insn, op->kp.addr + INT3_INSN_SIZE,
437 		       DISP32_SIZE);
438 
439 		insn_buff[0] = JMP32_INSN_OPCODE;
440 		*(s32 *)(&insn_buff[1]) = rel;
441 
442 		text_poke_bp(op->kp.addr, insn_buff, JMP32_INSN_SIZE, NULL);
443 
444 		list_del_init(&op->list);
445 	}
446 }
447 
448 /*
449  * Replace a relative jump (JMP.d32) with a breakpoint (INT3).
450  *
451  * After that, we can restore the 4 bytes after the INT3 to undo what
452  * arch_optimize_kprobes() scribbled. This is safe since those bytes will be
453  * unused once the INT3 lands.
454  */
455 void arch_unoptimize_kprobe(struct optimized_kprobe *op)
456 {
457 	arch_arm_kprobe(&op->kp);
458 	text_poke(op->kp.addr + INT3_INSN_SIZE,
459 		  op->optinsn.copied_insn, DISP32_SIZE);
460 	text_poke_sync();
461 }
462 
463 /*
464  * Recover original instructions and breakpoints from relative jumps.
465  * Caller must call with locking kprobe_mutex.
466  */
467 extern void arch_unoptimize_kprobes(struct list_head *oplist,
468 				    struct list_head *done_list)
469 {
470 	struct optimized_kprobe *op, *tmp;
471 
472 	list_for_each_entry_safe(op, tmp, oplist, list) {
473 		arch_unoptimize_kprobe(op);
474 		list_move(&op->list, done_list);
475 	}
476 }
477 
478 int setup_detour_execution(struct kprobe *p, struct pt_regs *regs, int reenter)
479 {
480 	struct optimized_kprobe *op;
481 
482 	if (p->flags & KPROBE_FLAG_OPTIMIZED) {
483 		/* This kprobe is really able to run optimized path. */
484 		op = container_of(p, struct optimized_kprobe, kp);
485 		/* Detour through copied instructions */
486 		regs->ip = (unsigned long)op->optinsn.insn + TMPL_END_IDX;
487 		if (!reenter)
488 			reset_current_kprobe();
489 		return 1;
490 	}
491 	return 0;
492 }
493 NOKPROBE_SYMBOL(setup_detour_execution);
494