1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Kernel Probes (KProbes)
4  *
5  * Copyright (C) IBM Corporation, 2002, 2004
6  *
7  * 2002-Oct	Created by Vamsi Krishna S <vamsi_krishna@in.ibm.com> Kernel
8  *		Probes initial implementation ( includes contributions from
9  *		Rusty Russell).
10  * 2004-July	Suparna Bhattacharya <suparna@in.ibm.com> added jumper probes
11  *		interface to access function arguments.
12  * 2004-Oct	Jim Keniston <jkenisto@us.ibm.com> and Prasanna S Panchamukhi
13  *		<prasanna@in.ibm.com> adapted for x86_64 from i386.
14  * 2005-Mar	Roland McGrath <roland@redhat.com>
15  *		Fixed to handle %rip-relative addressing mode correctly.
16  * 2005-May	Hien Nguyen <hien@us.ibm.com>, Jim Keniston
17  *		<jkenisto@us.ibm.com> and Prasanna S Panchamukhi
18  *		<prasanna@in.ibm.com> added function-return probes.
19  * 2005-May	Rusty Lynch <rusty.lynch@intel.com>
20  *		Added function return probes functionality
21  * 2006-Feb	Masami Hiramatsu <hiramatu@sdl.hitachi.co.jp> added
22  *		kprobe-booster and kretprobe-booster for i386.
23  * 2007-Dec	Masami Hiramatsu <mhiramat@redhat.com> added kprobe-booster
24  *		and kretprobe-booster for x86-64
25  * 2007-Dec	Masami Hiramatsu <mhiramat@redhat.com>, Arjan van de Ven
26  *		<arjan@infradead.org> and Jim Keniston <jkenisto@us.ibm.com>
27  *		unified x86 kprobes code.
28  */
29 #include <linux/kprobes.h>
30 #include <linux/ptrace.h>
31 #include <linux/string.h>
32 #include <linux/slab.h>
33 #include <linux/hardirq.h>
34 #include <linux/preempt.h>
35 #include <linux/sched/debug.h>
36 #include <linux/perf_event.h>
37 #include <linux/extable.h>
38 #include <linux/kdebug.h>
39 #include <linux/kallsyms.h>
40 #include <linux/kgdb.h>
41 #include <linux/ftrace.h>
42 #include <linux/kasan.h>
43 #include <linux/moduleloader.h>
44 #include <linux/objtool.h>
45 #include <linux/vmalloc.h>
46 #include <linux/pgtable.h>
47 
48 #include <asm/text-patching.h>
49 #include <asm/cacheflush.h>
50 #include <asm/desc.h>
51 #include <linux/uaccess.h>
52 #include <asm/alternative.h>
53 #include <asm/insn.h>
54 #include <asm/debugreg.h>
55 #include <asm/set_memory.h>
56 #include <asm/ibt.h>
57 
58 #include "common.h"
59 
60 DEFINE_PER_CPU(struct kprobe *, current_kprobe) = NULL;
61 DEFINE_PER_CPU(struct kprobe_ctlblk, kprobe_ctlblk);
62 
63 #define W(row, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf)\
64 	(((b0##UL << 0x0)|(b1##UL << 0x1)|(b2##UL << 0x2)|(b3##UL << 0x3) |   \
65 	  (b4##UL << 0x4)|(b5##UL << 0x5)|(b6##UL << 0x6)|(b7##UL << 0x7) |   \
66 	  (b8##UL << 0x8)|(b9##UL << 0x9)|(ba##UL << 0xa)|(bb##UL << 0xb) |   \
67 	  (bc##UL << 0xc)|(bd##UL << 0xd)|(be##UL << 0xe)|(bf##UL << 0xf))    \
68 	 << (row % 32))
69 	/*
70 	 * Undefined/reserved opcodes, conditional jump, Opcode Extension
71 	 * Groups, and some special opcodes can not boost.
72 	 * This is non-const and volatile to keep gcc from statically
73 	 * optimizing it out, as variable_test_bit makes gcc think only
74 	 * *(unsigned long*) is used.
75 	 */
76 static volatile u32 twobyte_is_boostable[256 / 32] = {
77 	/*      0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f          */
78 	/*      ----------------------------------------------          */
79 	W(0x00, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0) | /* 00 */
80 	W(0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1) , /* 10 */
81 	W(0x20, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) | /* 20 */
82 	W(0x30, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) , /* 30 */
83 	W(0x40, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* 40 */
84 	W(0x50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) , /* 50 */
85 	W(0x60, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1) | /* 60 */
86 	W(0x70, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1) , /* 70 */
87 	W(0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) | /* 80 */
88 	W(0x90, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* 90 */
89 	W(0xa0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) | /* a0 */
90 	W(0xb0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1) , /* b0 */
91 	W(0xc0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1) | /* c0 */
92 	W(0xd0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) , /* d0 */
93 	W(0xe0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) | /* e0 */
94 	W(0xf0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0)   /* f0 */
95 	/*      -----------------------------------------------         */
96 	/*      0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f          */
97 };
98 #undef W
99 
100 struct kretprobe_blackpoint kretprobe_blacklist[] = {
101 	{"__switch_to", }, /* This function switches only current task, but
102 			      doesn't switch kernel stack.*/
103 	{NULL, NULL}	/* Terminator */
104 };
105 
106 const int kretprobe_blacklist_size = ARRAY_SIZE(kretprobe_blacklist);
107 
108 static nokprobe_inline void
__synthesize_relative_insn(void * dest,void * from,void * to,u8 op)109 __synthesize_relative_insn(void *dest, void *from, void *to, u8 op)
110 {
111 	struct __arch_relative_insn {
112 		u8 op;
113 		s32 raddr;
114 	} __packed *insn;
115 
116 	insn = (struct __arch_relative_insn *)dest;
117 	insn->raddr = (s32)((long)(to) - ((long)(from) + 5));
118 	insn->op = op;
119 }
120 
121 /* Insert a jump instruction at address 'from', which jumps to address 'to'.*/
synthesize_reljump(void * dest,void * from,void * to)122 void synthesize_reljump(void *dest, void *from, void *to)
123 {
124 	__synthesize_relative_insn(dest, from, to, JMP32_INSN_OPCODE);
125 }
126 NOKPROBE_SYMBOL(synthesize_reljump);
127 
128 /* Insert a call instruction at address 'from', which calls address 'to'.*/
synthesize_relcall(void * dest,void * from,void * to)129 void synthesize_relcall(void *dest, void *from, void *to)
130 {
131 	__synthesize_relative_insn(dest, from, to, CALL_INSN_OPCODE);
132 }
133 NOKPROBE_SYMBOL(synthesize_relcall);
134 
135 /*
136  * Returns non-zero if INSN is boostable.
137  * RIP relative instructions are adjusted at copying time in 64 bits mode
138  */
can_boost(struct insn * insn,void * addr)139 int can_boost(struct insn *insn, void *addr)
140 {
141 	kprobe_opcode_t opcode;
142 	insn_byte_t prefix;
143 	int i;
144 
145 	if (search_exception_tables((unsigned long)addr))
146 		return 0;	/* Page fault may occur on this address. */
147 
148 	/* 2nd-byte opcode */
149 	if (insn->opcode.nbytes == 2)
150 		return test_bit(insn->opcode.bytes[1],
151 				(unsigned long *)twobyte_is_boostable);
152 
153 	if (insn->opcode.nbytes != 1)
154 		return 0;
155 
156 	for_each_insn_prefix(insn, i, prefix) {
157 		insn_attr_t attr;
158 
159 		attr = inat_get_opcode_attribute(prefix);
160 		/* Can't boost Address-size override prefix and CS override prefix */
161 		if (prefix == 0x2e || inat_is_address_size_prefix(attr))
162 			return 0;
163 	}
164 
165 	opcode = insn->opcode.bytes[0];
166 
167 	switch (opcode) {
168 	case 0x62:		/* bound */
169 	case 0x70 ... 0x7f:	/* Conditional jumps */
170 	case 0x9a:		/* Call far */
171 	case 0xc0 ... 0xc1:	/* Grp2 */
172 	case 0xcc ... 0xce:	/* software exceptions */
173 	case 0xd0 ... 0xd3:	/* Grp2 */
174 	case 0xd6:		/* (UD) */
175 	case 0xd8 ... 0xdf:	/* ESC */
176 	case 0xe0 ... 0xe3:	/* LOOP*, JCXZ */
177 	case 0xe8 ... 0xe9:	/* near Call, JMP */
178 	case 0xeb:		/* Short JMP */
179 	case 0xf0 ... 0xf4:	/* LOCK/REP, HLT */
180 	case 0xf6 ... 0xf7:	/* Grp3 */
181 	case 0xfe:		/* Grp4 */
182 		/* ... are not boostable */
183 		return 0;
184 	case 0xff:		/* Grp5 */
185 		/* Only indirect jmp is boostable */
186 		return X86_MODRM_REG(insn->modrm.bytes[0]) == 4;
187 	default:
188 		return 1;
189 	}
190 }
191 
192 static unsigned long
__recover_probed_insn(kprobe_opcode_t * buf,unsigned long addr)193 __recover_probed_insn(kprobe_opcode_t *buf, unsigned long addr)
194 {
195 	struct kprobe *kp;
196 	bool faddr;
197 
198 	kp = get_kprobe((void *)addr);
199 	faddr = ftrace_location(addr) == addr;
200 	/*
201 	 * Use the current code if it is not modified by Kprobe
202 	 * and it cannot be modified by ftrace.
203 	 */
204 	if (!kp && !faddr)
205 		return addr;
206 
207 	/*
208 	 * Basically, kp->ainsn.insn has an original instruction.
209 	 * However, RIP-relative instruction can not do single-stepping
210 	 * at different place, __copy_instruction() tweaks the displacement of
211 	 * that instruction. In that case, we can't recover the instruction
212 	 * from the kp->ainsn.insn.
213 	 *
214 	 * On the other hand, in case on normal Kprobe, kp->opcode has a copy
215 	 * of the first byte of the probed instruction, which is overwritten
216 	 * by int3. And the instruction at kp->addr is not modified by kprobes
217 	 * except for the first byte, we can recover the original instruction
218 	 * from it and kp->opcode.
219 	 *
220 	 * In case of Kprobes using ftrace, we do not have a copy of
221 	 * the original instruction. In fact, the ftrace location might
222 	 * be modified at anytime and even could be in an inconsistent state.
223 	 * Fortunately, we know that the original code is the ideal 5-byte
224 	 * long NOP.
225 	 */
226 	if (copy_from_kernel_nofault(buf, (void *)addr,
227 		MAX_INSN_SIZE * sizeof(kprobe_opcode_t)))
228 		return 0UL;
229 
230 	if (faddr)
231 		memcpy(buf, x86_nops[5], 5);
232 	else
233 		buf[0] = kp->opcode;
234 	return (unsigned long)buf;
235 }
236 
237 /*
238  * Recover the probed instruction at addr for further analysis.
239  * Caller must lock kprobes by kprobe_mutex, or disable preemption
240  * for preventing to release referencing kprobes.
241  * Returns zero if the instruction can not get recovered (or access failed).
242  */
recover_probed_instruction(kprobe_opcode_t * buf,unsigned long addr)243 unsigned long recover_probed_instruction(kprobe_opcode_t *buf, unsigned long addr)
244 {
245 	unsigned long __addr;
246 
247 	__addr = __recover_optprobed_insn(buf, addr);
248 	if (__addr != addr)
249 		return __addr;
250 
251 	return __recover_probed_insn(buf, addr);
252 }
253 
254 /* Check if paddr is at an instruction boundary */
can_probe(unsigned long paddr)255 static int can_probe(unsigned long paddr)
256 {
257 	unsigned long addr, __addr, offset = 0;
258 	struct insn insn;
259 	kprobe_opcode_t buf[MAX_INSN_SIZE];
260 
261 	if (!kallsyms_lookup_size_offset(paddr, NULL, &offset))
262 		return 0;
263 
264 	/* Decode instructions */
265 	addr = paddr - offset;
266 	while (addr < paddr) {
267 		int ret;
268 
269 		/*
270 		 * Check if the instruction has been modified by another
271 		 * kprobe, in which case we replace the breakpoint by the
272 		 * original instruction in our buffer.
273 		 * Also, jump optimization will change the breakpoint to
274 		 * relative-jump. Since the relative-jump itself is
275 		 * normally used, we just go through if there is no kprobe.
276 		 */
277 		__addr = recover_probed_instruction(buf, addr);
278 		if (!__addr)
279 			return 0;
280 
281 		ret = insn_decode_kernel(&insn, (void *)__addr);
282 		if (ret < 0)
283 			return 0;
284 
285 #ifdef CONFIG_KGDB
286 		/*
287 		 * If there is a dynamically installed kgdb sw breakpoint,
288 		 * this function should not be probed.
289 		 */
290 		if (insn.opcode.bytes[0] == INT3_INSN_OPCODE &&
291 		    kgdb_has_hit_break(addr))
292 			return 0;
293 #endif
294 		addr += insn.length;
295 	}
296 
297 	return (addr == paddr);
298 }
299 
300 /* If x86 supports IBT (ENDBR) it must be skipped. */
arch_adjust_kprobe_addr(unsigned long addr,unsigned long offset,bool * on_func_entry)301 kprobe_opcode_t *arch_adjust_kprobe_addr(unsigned long addr, unsigned long offset,
302 					 bool *on_func_entry)
303 {
304 	if (is_endbr(*(u32 *)addr)) {
305 		*on_func_entry = !offset || offset == 4;
306 		if (*on_func_entry)
307 			offset = 4;
308 
309 	} else {
310 		*on_func_entry = !offset;
311 	}
312 
313 	return (kprobe_opcode_t *)(addr + offset);
314 }
315 
316 /*
317  * Copy an instruction with recovering modified instruction by kprobes
318  * and adjust the displacement if the instruction uses the %rip-relative
319  * addressing mode. Note that since @real will be the final place of copied
320  * instruction, displacement must be adjust by @real, not @dest.
321  * This returns the length of copied instruction, or 0 if it has an error.
322  */
__copy_instruction(u8 * dest,u8 * src,u8 * real,struct insn * insn)323 int __copy_instruction(u8 *dest, u8 *src, u8 *real, struct insn *insn)
324 {
325 	kprobe_opcode_t buf[MAX_INSN_SIZE];
326 	unsigned long recovered_insn = recover_probed_instruction(buf, (unsigned long)src);
327 	int ret;
328 
329 	if (!recovered_insn || !insn)
330 		return 0;
331 
332 	/* This can access kernel text if given address is not recovered */
333 	if (copy_from_kernel_nofault(dest, (void *)recovered_insn,
334 			MAX_INSN_SIZE))
335 		return 0;
336 
337 	ret = insn_decode_kernel(insn, dest);
338 	if (ret < 0)
339 		return 0;
340 
341 	/* We can not probe force emulate prefixed instruction */
342 	if (insn_has_emulate_prefix(insn))
343 		return 0;
344 
345 	/* Another subsystem puts a breakpoint, failed to recover */
346 	if (insn->opcode.bytes[0] == INT3_INSN_OPCODE)
347 		return 0;
348 
349 	/* We should not singlestep on the exception masking instructions */
350 	if (insn_masking_exception(insn))
351 		return 0;
352 
353 #ifdef CONFIG_X86_64
354 	/* Only x86_64 has RIP relative instructions */
355 	if (insn_rip_relative(insn)) {
356 		s64 newdisp;
357 		u8 *disp;
358 		/*
359 		 * The copied instruction uses the %rip-relative addressing
360 		 * mode.  Adjust the displacement for the difference between
361 		 * the original location of this instruction and the location
362 		 * of the copy that will actually be run.  The tricky bit here
363 		 * is making sure that the sign extension happens correctly in
364 		 * this calculation, since we need a signed 32-bit result to
365 		 * be sign-extended to 64 bits when it's added to the %rip
366 		 * value and yield the same 64-bit result that the sign-
367 		 * extension of the original signed 32-bit displacement would
368 		 * have given.
369 		 */
370 		newdisp = (u8 *) src + (s64) insn->displacement.value
371 			  - (u8 *) real;
372 		if ((s64) (s32) newdisp != newdisp) {
373 			pr_err("Kprobes error: new displacement does not fit into s32 (%llx)\n", newdisp);
374 			return 0;
375 		}
376 		disp = (u8 *) dest + insn_offset_displacement(insn);
377 		*(s32 *) disp = (s32) newdisp;
378 	}
379 #endif
380 	return insn->length;
381 }
382 
383 /* Prepare reljump or int3 right after instruction */
prepare_singlestep(kprobe_opcode_t * buf,struct kprobe * p,struct insn * insn)384 static int prepare_singlestep(kprobe_opcode_t *buf, struct kprobe *p,
385 			      struct insn *insn)
386 {
387 	int len = insn->length;
388 
389 	if (!IS_ENABLED(CONFIG_PREEMPTION) &&
390 	    !p->post_handler && can_boost(insn, p->addr) &&
391 	    MAX_INSN_SIZE - len >= JMP32_INSN_SIZE) {
392 		/*
393 		 * These instructions can be executed directly if it
394 		 * jumps back to correct address.
395 		 */
396 		synthesize_reljump(buf + len, p->ainsn.insn + len,
397 				   p->addr + insn->length);
398 		len += JMP32_INSN_SIZE;
399 		p->ainsn.boostable = 1;
400 	} else {
401 		/* Otherwise, put an int3 for trapping singlestep */
402 		if (MAX_INSN_SIZE - len < INT3_INSN_SIZE)
403 			return -ENOSPC;
404 
405 		buf[len] = INT3_INSN_OPCODE;
406 		len += INT3_INSN_SIZE;
407 	}
408 
409 	return len;
410 }
411 
412 /* Make page to RO mode when allocate it */
alloc_insn_page(void)413 void *alloc_insn_page(void)
414 {
415 	void *page;
416 
417 	page = module_alloc(PAGE_SIZE);
418 	if (!page)
419 		return NULL;
420 
421 	set_vm_flush_reset_perms(page);
422 	/*
423 	 * First make the page read-only, and only then make it executable to
424 	 * prevent it from being W+X in between.
425 	 */
426 	set_memory_ro((unsigned long)page, 1);
427 
428 	/*
429 	 * TODO: Once additional kernel code protection mechanisms are set, ensure
430 	 * that the page was not maliciously altered and it is still zeroed.
431 	 */
432 	set_memory_x((unsigned long)page, 1);
433 
434 	return page;
435 }
436 
437 /* Kprobe x86 instruction emulation - only regs->ip or IF flag modifiers */
438 
kprobe_emulate_ifmodifiers(struct kprobe * p,struct pt_regs * regs)439 static void kprobe_emulate_ifmodifiers(struct kprobe *p, struct pt_regs *regs)
440 {
441 	switch (p->ainsn.opcode) {
442 	case 0xfa:	/* cli */
443 		regs->flags &= ~(X86_EFLAGS_IF);
444 		break;
445 	case 0xfb:	/* sti */
446 		regs->flags |= X86_EFLAGS_IF;
447 		break;
448 	case 0x9c:	/* pushf */
449 		int3_emulate_push(regs, regs->flags);
450 		break;
451 	case 0x9d:	/* popf */
452 		regs->flags = int3_emulate_pop(regs);
453 		break;
454 	}
455 	regs->ip = regs->ip - INT3_INSN_SIZE + p->ainsn.size;
456 }
457 NOKPROBE_SYMBOL(kprobe_emulate_ifmodifiers);
458 
kprobe_emulate_ret(struct kprobe * p,struct pt_regs * regs)459 static void kprobe_emulate_ret(struct kprobe *p, struct pt_regs *regs)
460 {
461 	int3_emulate_ret(regs);
462 }
463 NOKPROBE_SYMBOL(kprobe_emulate_ret);
464 
kprobe_emulate_call(struct kprobe * p,struct pt_regs * regs)465 static void kprobe_emulate_call(struct kprobe *p, struct pt_regs *regs)
466 {
467 	unsigned long func = regs->ip - INT3_INSN_SIZE + p->ainsn.size;
468 
469 	func += p->ainsn.rel32;
470 	int3_emulate_call(regs, func);
471 }
472 NOKPROBE_SYMBOL(kprobe_emulate_call);
473 
474 static nokprobe_inline
__kprobe_emulate_jmp(struct kprobe * p,struct pt_regs * regs,bool cond)475 void __kprobe_emulate_jmp(struct kprobe *p, struct pt_regs *regs, bool cond)
476 {
477 	unsigned long ip = regs->ip - INT3_INSN_SIZE + p->ainsn.size;
478 
479 	if (cond)
480 		ip += p->ainsn.rel32;
481 	int3_emulate_jmp(regs, ip);
482 }
483 
kprobe_emulate_jmp(struct kprobe * p,struct pt_regs * regs)484 static void kprobe_emulate_jmp(struct kprobe *p, struct pt_regs *regs)
485 {
486 	__kprobe_emulate_jmp(p, regs, true);
487 }
488 NOKPROBE_SYMBOL(kprobe_emulate_jmp);
489 
490 static const unsigned long jcc_mask[6] = {
491 	[0] = X86_EFLAGS_OF,
492 	[1] = X86_EFLAGS_CF,
493 	[2] = X86_EFLAGS_ZF,
494 	[3] = X86_EFLAGS_CF | X86_EFLAGS_ZF,
495 	[4] = X86_EFLAGS_SF,
496 	[5] = X86_EFLAGS_PF,
497 };
498 
kprobe_emulate_jcc(struct kprobe * p,struct pt_regs * regs)499 static void kprobe_emulate_jcc(struct kprobe *p, struct pt_regs *regs)
500 {
501 	bool invert = p->ainsn.jcc.type & 1;
502 	bool match;
503 
504 	if (p->ainsn.jcc.type < 0xc) {
505 		match = regs->flags & jcc_mask[p->ainsn.jcc.type >> 1];
506 	} else {
507 		match = ((regs->flags & X86_EFLAGS_SF) >> X86_EFLAGS_SF_BIT) ^
508 			((regs->flags & X86_EFLAGS_OF) >> X86_EFLAGS_OF_BIT);
509 		if (p->ainsn.jcc.type >= 0xe)
510 			match = match || (regs->flags & X86_EFLAGS_ZF);
511 	}
512 	__kprobe_emulate_jmp(p, regs, (match && !invert) || (!match && invert));
513 }
514 NOKPROBE_SYMBOL(kprobe_emulate_jcc);
515 
kprobe_emulate_loop(struct kprobe * p,struct pt_regs * regs)516 static void kprobe_emulate_loop(struct kprobe *p, struct pt_regs *regs)
517 {
518 	bool match;
519 
520 	if (p->ainsn.loop.type != 3) {	/* LOOP* */
521 		if (p->ainsn.loop.asize == 32)
522 			match = ((*(u32 *)&regs->cx)--) != 0;
523 #ifdef CONFIG_X86_64
524 		else if (p->ainsn.loop.asize == 64)
525 			match = ((*(u64 *)&regs->cx)--) != 0;
526 #endif
527 		else
528 			match = ((*(u16 *)&regs->cx)--) != 0;
529 	} else {			/* JCXZ */
530 		if (p->ainsn.loop.asize == 32)
531 			match = *(u32 *)(&regs->cx) == 0;
532 #ifdef CONFIG_X86_64
533 		else if (p->ainsn.loop.asize == 64)
534 			match = *(u64 *)(&regs->cx) == 0;
535 #endif
536 		else
537 			match = *(u16 *)(&regs->cx) == 0;
538 	}
539 
540 	if (p->ainsn.loop.type == 0)	/* LOOPNE */
541 		match = match && !(regs->flags & X86_EFLAGS_ZF);
542 	else if (p->ainsn.loop.type == 1)	/* LOOPE */
543 		match = match && (regs->flags & X86_EFLAGS_ZF);
544 
545 	__kprobe_emulate_jmp(p, regs, match);
546 }
547 NOKPROBE_SYMBOL(kprobe_emulate_loop);
548 
549 static const int addrmode_regoffs[] = {
550 	offsetof(struct pt_regs, ax),
551 	offsetof(struct pt_regs, cx),
552 	offsetof(struct pt_regs, dx),
553 	offsetof(struct pt_regs, bx),
554 	offsetof(struct pt_regs, sp),
555 	offsetof(struct pt_regs, bp),
556 	offsetof(struct pt_regs, si),
557 	offsetof(struct pt_regs, di),
558 #ifdef CONFIG_X86_64
559 	offsetof(struct pt_regs, r8),
560 	offsetof(struct pt_regs, r9),
561 	offsetof(struct pt_regs, r10),
562 	offsetof(struct pt_regs, r11),
563 	offsetof(struct pt_regs, r12),
564 	offsetof(struct pt_regs, r13),
565 	offsetof(struct pt_regs, r14),
566 	offsetof(struct pt_regs, r15),
567 #endif
568 };
569 
kprobe_emulate_call_indirect(struct kprobe * p,struct pt_regs * regs)570 static void kprobe_emulate_call_indirect(struct kprobe *p, struct pt_regs *regs)
571 {
572 	unsigned long offs = addrmode_regoffs[p->ainsn.indirect.reg];
573 
574 	int3_emulate_call(regs, regs_get_register(regs, offs));
575 }
576 NOKPROBE_SYMBOL(kprobe_emulate_call_indirect);
577 
kprobe_emulate_jmp_indirect(struct kprobe * p,struct pt_regs * regs)578 static void kprobe_emulate_jmp_indirect(struct kprobe *p, struct pt_regs *regs)
579 {
580 	unsigned long offs = addrmode_regoffs[p->ainsn.indirect.reg];
581 
582 	int3_emulate_jmp(regs, regs_get_register(regs, offs));
583 }
584 NOKPROBE_SYMBOL(kprobe_emulate_jmp_indirect);
585 
prepare_emulation(struct kprobe * p,struct insn * insn)586 static int prepare_emulation(struct kprobe *p, struct insn *insn)
587 {
588 	insn_byte_t opcode = insn->opcode.bytes[0];
589 
590 	switch (opcode) {
591 	case 0xfa:		/* cli */
592 	case 0xfb:		/* sti */
593 	case 0x9c:		/* pushfl */
594 	case 0x9d:		/* popf/popfd */
595 		/*
596 		 * IF modifiers must be emulated since it will enable interrupt while
597 		 * int3 single stepping.
598 		 */
599 		p->ainsn.emulate_op = kprobe_emulate_ifmodifiers;
600 		p->ainsn.opcode = opcode;
601 		break;
602 	case 0xc2:	/* ret/lret */
603 	case 0xc3:
604 	case 0xca:
605 	case 0xcb:
606 		p->ainsn.emulate_op = kprobe_emulate_ret;
607 		break;
608 	case 0x9a:	/* far call absolute -- segment is not supported */
609 	case 0xea:	/* far jmp absolute -- segment is not supported */
610 	case 0xcc:	/* int3 */
611 	case 0xcf:	/* iret -- in-kernel IRET is not supported */
612 		return -EOPNOTSUPP;
613 		break;
614 	case 0xe8:	/* near call relative */
615 		p->ainsn.emulate_op = kprobe_emulate_call;
616 		if (insn->immediate.nbytes == 2)
617 			p->ainsn.rel32 = *(s16 *)&insn->immediate.value;
618 		else
619 			p->ainsn.rel32 = *(s32 *)&insn->immediate.value;
620 		break;
621 	case 0xeb:	/* short jump relative */
622 	case 0xe9:	/* near jump relative */
623 		p->ainsn.emulate_op = kprobe_emulate_jmp;
624 		if (insn->immediate.nbytes == 1)
625 			p->ainsn.rel32 = *(s8 *)&insn->immediate.value;
626 		else if (insn->immediate.nbytes == 2)
627 			p->ainsn.rel32 = *(s16 *)&insn->immediate.value;
628 		else
629 			p->ainsn.rel32 = *(s32 *)&insn->immediate.value;
630 		break;
631 	case 0x70 ... 0x7f:
632 		/* 1 byte conditional jump */
633 		p->ainsn.emulate_op = kprobe_emulate_jcc;
634 		p->ainsn.jcc.type = opcode & 0xf;
635 		p->ainsn.rel32 = *(char *)insn->immediate.bytes;
636 		break;
637 	case 0x0f:
638 		opcode = insn->opcode.bytes[1];
639 		if ((opcode & 0xf0) == 0x80) {
640 			/* 2 bytes Conditional Jump */
641 			p->ainsn.emulate_op = kprobe_emulate_jcc;
642 			p->ainsn.jcc.type = opcode & 0xf;
643 			if (insn->immediate.nbytes == 2)
644 				p->ainsn.rel32 = *(s16 *)&insn->immediate.value;
645 			else
646 				p->ainsn.rel32 = *(s32 *)&insn->immediate.value;
647 		} else if (opcode == 0x01 &&
648 			   X86_MODRM_REG(insn->modrm.bytes[0]) == 0 &&
649 			   X86_MODRM_MOD(insn->modrm.bytes[0]) == 3) {
650 			/* VM extensions - not supported */
651 			return -EOPNOTSUPP;
652 		}
653 		break;
654 	case 0xe0:	/* Loop NZ */
655 	case 0xe1:	/* Loop */
656 	case 0xe2:	/* Loop */
657 	case 0xe3:	/* J*CXZ */
658 		p->ainsn.emulate_op = kprobe_emulate_loop;
659 		p->ainsn.loop.type = opcode & 0x3;
660 		p->ainsn.loop.asize = insn->addr_bytes * 8;
661 		p->ainsn.rel32 = *(s8 *)&insn->immediate.value;
662 		break;
663 	case 0xff:
664 		/*
665 		 * Since the 0xff is an extended group opcode, the instruction
666 		 * is determined by the MOD/RM byte.
667 		 */
668 		opcode = insn->modrm.bytes[0];
669 		if ((opcode & 0x30) == 0x10) {
670 			if ((opcode & 0x8) == 0x8)
671 				return -EOPNOTSUPP;	/* far call */
672 			/* call absolute, indirect */
673 			p->ainsn.emulate_op = kprobe_emulate_call_indirect;
674 		} else if ((opcode & 0x30) == 0x20) {
675 			if ((opcode & 0x8) == 0x8)
676 				return -EOPNOTSUPP;	/* far jmp */
677 			/* jmp near absolute indirect */
678 			p->ainsn.emulate_op = kprobe_emulate_jmp_indirect;
679 		} else
680 			break;
681 
682 		if (insn->addr_bytes != sizeof(unsigned long))
683 			return -EOPNOTSUPP;	/* Don't support different size */
684 		if (X86_MODRM_MOD(opcode) != 3)
685 			return -EOPNOTSUPP;	/* TODO: support memory addressing */
686 
687 		p->ainsn.indirect.reg = X86_MODRM_RM(opcode);
688 #ifdef CONFIG_X86_64
689 		if (X86_REX_B(insn->rex_prefix.value))
690 			p->ainsn.indirect.reg += 8;
691 #endif
692 		break;
693 	default:
694 		break;
695 	}
696 	p->ainsn.size = insn->length;
697 
698 	return 0;
699 }
700 
arch_copy_kprobe(struct kprobe * p)701 static int arch_copy_kprobe(struct kprobe *p)
702 {
703 	struct insn insn;
704 	kprobe_opcode_t buf[MAX_INSN_SIZE];
705 	int ret, len;
706 
707 	/* Copy an instruction with recovering if other optprobe modifies it.*/
708 	len = __copy_instruction(buf, p->addr, p->ainsn.insn, &insn);
709 	if (!len)
710 		return -EINVAL;
711 
712 	/* Analyze the opcode and setup emulate functions */
713 	ret = prepare_emulation(p, &insn);
714 	if (ret < 0)
715 		return ret;
716 
717 	/* Add int3 for single-step or booster jmp */
718 	len = prepare_singlestep(buf, p, &insn);
719 	if (len < 0)
720 		return len;
721 
722 	/* Also, displacement change doesn't affect the first byte */
723 	p->opcode = buf[0];
724 
725 	p->ainsn.tp_len = len;
726 	perf_event_text_poke(p->ainsn.insn, NULL, 0, buf, len);
727 
728 	/* OK, write back the instruction(s) into ROX insn buffer */
729 	text_poke(p->ainsn.insn, buf, len);
730 
731 	return 0;
732 }
733 
arch_prepare_kprobe(struct kprobe * p)734 int arch_prepare_kprobe(struct kprobe *p)
735 {
736 	int ret;
737 
738 	if (alternatives_text_reserved(p->addr, p->addr))
739 		return -EINVAL;
740 
741 	if (!can_probe((unsigned long)p->addr))
742 		return -EILSEQ;
743 
744 	memset(&p->ainsn, 0, sizeof(p->ainsn));
745 
746 	/* insn: must be on special executable page on x86. */
747 	p->ainsn.insn = get_insn_slot();
748 	if (!p->ainsn.insn)
749 		return -ENOMEM;
750 
751 	ret = arch_copy_kprobe(p);
752 	if (ret) {
753 		free_insn_slot(p->ainsn.insn, 0);
754 		p->ainsn.insn = NULL;
755 	}
756 
757 	return ret;
758 }
759 
arch_arm_kprobe(struct kprobe * p)760 void arch_arm_kprobe(struct kprobe *p)
761 {
762 	u8 int3 = INT3_INSN_OPCODE;
763 
764 	text_poke(p->addr, &int3, 1);
765 	text_poke_sync();
766 	perf_event_text_poke(p->addr, &p->opcode, 1, &int3, 1);
767 }
768 
arch_disarm_kprobe(struct kprobe * p)769 void arch_disarm_kprobe(struct kprobe *p)
770 {
771 	u8 int3 = INT3_INSN_OPCODE;
772 
773 	perf_event_text_poke(p->addr, &int3, 1, &p->opcode, 1);
774 	text_poke(p->addr, &p->opcode, 1);
775 	text_poke_sync();
776 }
777 
arch_remove_kprobe(struct kprobe * p)778 void arch_remove_kprobe(struct kprobe *p)
779 {
780 	if (p->ainsn.insn) {
781 		/* Record the perf event before freeing the slot */
782 		perf_event_text_poke(p->ainsn.insn, p->ainsn.insn,
783 				     p->ainsn.tp_len, NULL, 0);
784 		free_insn_slot(p->ainsn.insn, p->ainsn.boostable);
785 		p->ainsn.insn = NULL;
786 	}
787 }
788 
789 static nokprobe_inline void
save_previous_kprobe(struct kprobe_ctlblk * kcb)790 save_previous_kprobe(struct kprobe_ctlblk *kcb)
791 {
792 	kcb->prev_kprobe.kp = kprobe_running();
793 	kcb->prev_kprobe.status = kcb->kprobe_status;
794 	kcb->prev_kprobe.old_flags = kcb->kprobe_old_flags;
795 	kcb->prev_kprobe.saved_flags = kcb->kprobe_saved_flags;
796 }
797 
798 static nokprobe_inline void
restore_previous_kprobe(struct kprobe_ctlblk * kcb)799 restore_previous_kprobe(struct kprobe_ctlblk *kcb)
800 {
801 	__this_cpu_write(current_kprobe, kcb->prev_kprobe.kp);
802 	kcb->kprobe_status = kcb->prev_kprobe.status;
803 	kcb->kprobe_old_flags = kcb->prev_kprobe.old_flags;
804 	kcb->kprobe_saved_flags = kcb->prev_kprobe.saved_flags;
805 }
806 
807 static nokprobe_inline void
set_current_kprobe(struct kprobe * p,struct pt_regs * regs,struct kprobe_ctlblk * kcb)808 set_current_kprobe(struct kprobe *p, struct pt_regs *regs,
809 		   struct kprobe_ctlblk *kcb)
810 {
811 	__this_cpu_write(current_kprobe, p);
812 	kcb->kprobe_saved_flags = kcb->kprobe_old_flags
813 		= (regs->flags & X86_EFLAGS_IF);
814 }
815 
kprobe_post_process(struct kprobe * cur,struct pt_regs * regs,struct kprobe_ctlblk * kcb)816 static void kprobe_post_process(struct kprobe *cur, struct pt_regs *regs,
817 			       struct kprobe_ctlblk *kcb)
818 {
819 	/* Restore back the original saved kprobes variables and continue. */
820 	if (kcb->kprobe_status == KPROBE_REENTER) {
821 		/* This will restore both kcb and current_kprobe */
822 		restore_previous_kprobe(kcb);
823 	} else {
824 		/*
825 		 * Always update the kcb status because
826 		 * reset_curent_kprobe() doesn't update kcb.
827 		 */
828 		kcb->kprobe_status = KPROBE_HIT_SSDONE;
829 		if (cur->post_handler)
830 			cur->post_handler(cur, regs, 0);
831 		reset_current_kprobe();
832 	}
833 }
834 NOKPROBE_SYMBOL(kprobe_post_process);
835 
setup_singlestep(struct kprobe * p,struct pt_regs * regs,struct kprobe_ctlblk * kcb,int reenter)836 static void setup_singlestep(struct kprobe *p, struct pt_regs *regs,
837 			     struct kprobe_ctlblk *kcb, int reenter)
838 {
839 	if (setup_detour_execution(p, regs, reenter))
840 		return;
841 
842 #if !defined(CONFIG_PREEMPTION)
843 	if (p->ainsn.boostable) {
844 		/* Boost up -- we can execute copied instructions directly */
845 		if (!reenter)
846 			reset_current_kprobe();
847 		/*
848 		 * Reentering boosted probe doesn't reset current_kprobe,
849 		 * nor set current_kprobe, because it doesn't use single
850 		 * stepping.
851 		 */
852 		regs->ip = (unsigned long)p->ainsn.insn;
853 		return;
854 	}
855 #endif
856 	if (reenter) {
857 		save_previous_kprobe(kcb);
858 		set_current_kprobe(p, regs, kcb);
859 		kcb->kprobe_status = KPROBE_REENTER;
860 	} else
861 		kcb->kprobe_status = KPROBE_HIT_SS;
862 
863 	if (p->ainsn.emulate_op) {
864 		p->ainsn.emulate_op(p, regs);
865 		kprobe_post_process(p, regs, kcb);
866 		return;
867 	}
868 
869 	/* Disable interrupt, and set ip register on trampoline */
870 	regs->flags &= ~X86_EFLAGS_IF;
871 	regs->ip = (unsigned long)p->ainsn.insn;
872 }
873 NOKPROBE_SYMBOL(setup_singlestep);
874 
875 /*
876  * Called after single-stepping.  p->addr is the address of the
877  * instruction whose first byte has been replaced by the "int3"
878  * instruction.  To avoid the SMP problems that can occur when we
879  * temporarily put back the original opcode to single-step, we
880  * single-stepped a copy of the instruction.  The address of this
881  * copy is p->ainsn.insn. We also doesn't use trap, but "int3" again
882  * right after the copied instruction.
883  * Different from the trap single-step, "int3" single-step can not
884  * handle the instruction which changes the ip register, e.g. jmp,
885  * call, conditional jmp, and the instructions which changes the IF
886  * flags because interrupt must be disabled around the single-stepping.
887  * Such instructions are software emulated, but others are single-stepped
888  * using "int3".
889  *
890  * When the 2nd "int3" handled, the regs->ip and regs->flags needs to
891  * be adjusted, so that we can resume execution on correct code.
892  */
resume_singlestep(struct kprobe * p,struct pt_regs * regs,struct kprobe_ctlblk * kcb)893 static void resume_singlestep(struct kprobe *p, struct pt_regs *regs,
894 			      struct kprobe_ctlblk *kcb)
895 {
896 	unsigned long copy_ip = (unsigned long)p->ainsn.insn;
897 	unsigned long orig_ip = (unsigned long)p->addr;
898 
899 	/* Restore saved interrupt flag and ip register */
900 	regs->flags |= kcb->kprobe_saved_flags;
901 	/* Note that regs->ip is executed int3 so must be a step back */
902 	regs->ip += (orig_ip - copy_ip) - INT3_INSN_SIZE;
903 }
904 NOKPROBE_SYMBOL(resume_singlestep);
905 
906 /*
907  * We have reentered the kprobe_handler(), since another probe was hit while
908  * within the handler. We save the original kprobes variables and just single
909  * step on the instruction of the new probe without calling any user handlers.
910  */
reenter_kprobe(struct kprobe * p,struct pt_regs * regs,struct kprobe_ctlblk * kcb)911 static int reenter_kprobe(struct kprobe *p, struct pt_regs *regs,
912 			  struct kprobe_ctlblk *kcb)
913 {
914 	switch (kcb->kprobe_status) {
915 	case KPROBE_HIT_SSDONE:
916 	case KPROBE_HIT_ACTIVE:
917 	case KPROBE_HIT_SS:
918 		kprobes_inc_nmissed_count(p);
919 		setup_singlestep(p, regs, kcb, 1);
920 		break;
921 	case KPROBE_REENTER:
922 		/* A probe has been hit in the codepath leading up to, or just
923 		 * after, single-stepping of a probed instruction. This entire
924 		 * codepath should strictly reside in .kprobes.text section.
925 		 * Raise a BUG or we'll continue in an endless reentering loop
926 		 * and eventually a stack overflow.
927 		 */
928 		pr_err("Unrecoverable kprobe detected.\n");
929 		dump_kprobe(p);
930 		BUG();
931 	default:
932 		/* impossible cases */
933 		WARN_ON(1);
934 		return 0;
935 	}
936 
937 	return 1;
938 }
939 NOKPROBE_SYMBOL(reenter_kprobe);
940 
kprobe_is_ss(struct kprobe_ctlblk * kcb)941 static nokprobe_inline int kprobe_is_ss(struct kprobe_ctlblk *kcb)
942 {
943 	return (kcb->kprobe_status == KPROBE_HIT_SS ||
944 		kcb->kprobe_status == KPROBE_REENTER);
945 }
946 
947 /*
948  * Interrupts are disabled on entry as trap3 is an interrupt gate and they
949  * remain disabled throughout this function.
950  */
kprobe_int3_handler(struct pt_regs * regs)951 int kprobe_int3_handler(struct pt_regs *regs)
952 {
953 	kprobe_opcode_t *addr;
954 	struct kprobe *p;
955 	struct kprobe_ctlblk *kcb;
956 
957 	if (user_mode(regs))
958 		return 0;
959 
960 	addr = (kprobe_opcode_t *)(regs->ip - sizeof(kprobe_opcode_t));
961 	/*
962 	 * We don't want to be preempted for the entire duration of kprobe
963 	 * processing. Since int3 and debug trap disables irqs and we clear
964 	 * IF while singlestepping, it must be no preemptible.
965 	 */
966 
967 	kcb = get_kprobe_ctlblk();
968 	p = get_kprobe(addr);
969 
970 	if (p) {
971 		if (kprobe_running()) {
972 			if (reenter_kprobe(p, regs, kcb))
973 				return 1;
974 		} else {
975 			set_current_kprobe(p, regs, kcb);
976 			kcb->kprobe_status = KPROBE_HIT_ACTIVE;
977 
978 			/*
979 			 * If we have no pre-handler or it returned 0, we
980 			 * continue with normal processing.  If we have a
981 			 * pre-handler and it returned non-zero, that means
982 			 * user handler setup registers to exit to another
983 			 * instruction, we must skip the single stepping.
984 			 */
985 			if (!p->pre_handler || !p->pre_handler(p, regs))
986 				setup_singlestep(p, regs, kcb, 0);
987 			else
988 				reset_current_kprobe();
989 			return 1;
990 		}
991 	} else if (kprobe_is_ss(kcb)) {
992 		p = kprobe_running();
993 		if ((unsigned long)p->ainsn.insn < regs->ip &&
994 		    (unsigned long)p->ainsn.insn + MAX_INSN_SIZE > regs->ip) {
995 			/* Most provably this is the second int3 for singlestep */
996 			resume_singlestep(p, regs, kcb);
997 			kprobe_post_process(p, regs, kcb);
998 			return 1;
999 		}
1000 	}
1001 
1002 	if (*addr != INT3_INSN_OPCODE) {
1003 		/*
1004 		 * The breakpoint instruction was removed right
1005 		 * after we hit it.  Another cpu has removed
1006 		 * either a probepoint or a debugger breakpoint
1007 		 * at this address.  In either case, no further
1008 		 * handling of this interrupt is appropriate.
1009 		 * Back up over the (now missing) int3 and run
1010 		 * the original instruction.
1011 		 */
1012 		regs->ip = (unsigned long)addr;
1013 		return 1;
1014 	} /* else: not a kprobe fault; let the kernel handle it */
1015 
1016 	return 0;
1017 }
1018 NOKPROBE_SYMBOL(kprobe_int3_handler);
1019 
kprobe_fault_handler(struct pt_regs * regs,int trapnr)1020 int kprobe_fault_handler(struct pt_regs *regs, int trapnr)
1021 {
1022 	struct kprobe *cur = kprobe_running();
1023 	struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
1024 
1025 	if (unlikely(regs->ip == (unsigned long)cur->ainsn.insn)) {
1026 		/* This must happen on single-stepping */
1027 		WARN_ON(kcb->kprobe_status != KPROBE_HIT_SS &&
1028 			kcb->kprobe_status != KPROBE_REENTER);
1029 		/*
1030 		 * We are here because the instruction being single
1031 		 * stepped caused a page fault. We reset the current
1032 		 * kprobe and the ip points back to the probe address
1033 		 * and allow the page fault handler to continue as a
1034 		 * normal page fault.
1035 		 */
1036 		regs->ip = (unsigned long)cur->addr;
1037 
1038 		/*
1039 		 * If the IF flag was set before the kprobe hit,
1040 		 * don't touch it:
1041 		 */
1042 		regs->flags |= kcb->kprobe_old_flags;
1043 
1044 		if (kcb->kprobe_status == KPROBE_REENTER)
1045 			restore_previous_kprobe(kcb);
1046 		else
1047 			reset_current_kprobe();
1048 	}
1049 
1050 	return 0;
1051 }
1052 NOKPROBE_SYMBOL(kprobe_fault_handler);
1053 
arch_populate_kprobe_blacklist(void)1054 int __init arch_populate_kprobe_blacklist(void)
1055 {
1056 	return kprobe_add_area_blacklist((unsigned long)__entry_text_start,
1057 					 (unsigned long)__entry_text_end);
1058 }
1059 
arch_init_kprobes(void)1060 int __init arch_init_kprobes(void)
1061 {
1062 	return 0;
1063 }
1064 
arch_trampoline_kprobe(struct kprobe * p)1065 int arch_trampoline_kprobe(struct kprobe *p)
1066 {
1067 	return 0;
1068 }
1069