2 * Kernel Probes (KProbes)
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 * Copyright (C) IBM Corporation, 2002, 2004
20 * 2002-Oct Created by Vamsi Krishna S <vamsi_krishna@in.ibm.com> Kernel
21 * Probes initial implementation ( includes contributions from
23 * 2004-July Suparna Bhattacharya <suparna@in.ibm.com> added jumper probes
24 * interface to access function arguments.
25 * 2004-Oct Jim Keniston <jkenisto@us.ibm.com> and Prasanna S Panchamukhi
26 * <prasanna@in.ibm.com> adapted for x86_64 from i386.
27 * 2005-Mar Roland McGrath <roland@redhat.com>
28 * Fixed to handle %rip-relative addressing mode correctly.
29 * 2005-May Hien Nguyen <hien@us.ibm.com>, Jim Keniston
30 * <jkenisto@us.ibm.com> and Prasanna S Panchamukhi
31 * <prasanna@in.ibm.com> added function-return probes.
32 * 2005-May Rusty Lynch <rusty.lynch@intel.com>
33 * Added function return probes functionality
34 * 2006-Feb Masami Hiramatsu <hiramatu@sdl.hitachi.co.jp> added
35 * kprobe-booster and kretprobe-booster for i386.
36 * 2007-Dec Masami Hiramatsu <mhiramat@redhat.com> added kprobe-booster
37 * and kretprobe-booster for x86-64
38 * 2007-Dec Masami Hiramatsu <mhiramat@redhat.com>, Arjan van de Ven
39 * <arjan@infradead.org> and Jim Keniston <jkenisto@us.ibm.com>
40 * unified x86 kprobes code.
43 #include <linux/kprobes.h>
44 #include <linux/ptrace.h>
45 #include <linux/string.h>
46 #include <linux/slab.h>
47 #include <linux/hardirq.h>
48 #include <linux/preempt.h>
49 #include <linux/module.h>
50 #include <linux/kdebug.h>
51 #include <linux/kallsyms.h>
52 #include <linux/ftrace.h>
54 #include <asm/cacheflush.h>
56 #include <asm/pgtable.h>
57 #include <asm/uaccess.h>
58 #include <asm/alternative.h>
60 #include <asm/debugreg.h>
62 void jprobe_return_end(void);
64 DEFINE_PER_CPU(struct kprobe *, current_kprobe) = NULL;
65 DEFINE_PER_CPU(struct kprobe_ctlblk, kprobe_ctlblk);
67 #define stack_addr(regs) ((unsigned long *)kernel_stack_pointer(regs))
69 #define W(row, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf)\
70 (((b0##UL << 0x0)|(b1##UL << 0x1)|(b2##UL << 0x2)|(b3##UL << 0x3) | \
71 (b4##UL << 0x4)|(b5##UL << 0x5)|(b6##UL << 0x6)|(b7##UL << 0x7) | \
72 (b8##UL << 0x8)|(b9##UL << 0x9)|(ba##UL << 0xa)|(bb##UL << 0xb) | \
73 (bc##UL << 0xc)|(bd##UL << 0xd)|(be##UL << 0xe)|(bf##UL << 0xf)) \
76 * Undefined/reserved opcodes, conditional jump, Opcode Extension
77 * Groups, and some special opcodes can not boost.
78 * This is non-const and volatile to keep gcc from statically
79 * optimizing it out, as variable_test_bit makes gcc think only
80 * *(unsigned long*) is used.
82 static volatile u32 twobyte_is_boostable[256 / 32] = {
83 /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
84 /* ---------------------------------------------- */
85 W(0x00, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0) | /* 00 */
86 W(0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) , /* 10 */
87 W(0x20, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) | /* 20 */
88 W(0x30, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) , /* 30 */
89 W(0x40, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* 40 */
90 W(0x50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) , /* 50 */
91 W(0x60, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1) | /* 60 */
92 W(0x70, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1) , /* 70 */
93 W(0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) | /* 80 */
94 W(0x90, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* 90 */
95 W(0xa0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) | /* a0 */
96 W(0xb0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1) , /* b0 */
97 W(0xc0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1) | /* c0 */
98 W(0xd0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) , /* d0 */
99 W(0xe0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) | /* e0 */
100 W(0xf0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0) /* f0 */
101 /* ----------------------------------------------- */
102 /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
106 struct kretprobe_blackpoint kretprobe_blacklist[] = {
107 {"__switch_to", }, /* This function switches only current task, but
108 doesn't switch kernel stack.*/
109 {NULL, NULL} /* Terminator */
111 const int kretprobe_blacklist_size = ARRAY_SIZE(kretprobe_blacklist);
113 static void __kprobes __synthesize_relative_insn(void *from, void *to, u8 op)
115 struct __arch_relative_insn {
118 } __attribute__((packed)) *insn;
120 insn = (struct __arch_relative_insn *)from;
121 insn->raddr = (s32)((long)(to) - ((long)(from) + 5));
125 /* Insert a jump instruction at address 'from', which jumps to address 'to'.*/
126 static void __kprobes synthesize_reljump(void *from, void *to)
128 __synthesize_relative_insn(from, to, RELATIVEJUMP_OPCODE);
132 * Skip the prefixes of the instruction.
134 static kprobe_opcode_t *__kprobes skip_prefixes(kprobe_opcode_t *insn)
138 attr = inat_get_opcode_attribute((insn_byte_t)*insn);
139 while (inat_is_legacy_prefix(attr)) {
141 attr = inat_get_opcode_attribute((insn_byte_t)*insn);
144 if (inat_is_rex_prefix(attr))
151 * Returns non-zero if opcode is boostable.
152 * RIP relative instructions are adjusted at copying time in 64 bits mode
154 static int __kprobes can_boost(kprobe_opcode_t *opcodes)
156 kprobe_opcode_t opcode;
157 kprobe_opcode_t *orig_opcodes = opcodes;
159 if (search_exception_tables((unsigned long)opcodes))
160 return 0; /* Page fault may occur on this address. */
163 if (opcodes - orig_opcodes > MAX_INSN_SIZE - 1)
165 opcode = *(opcodes++);
167 /* 2nd-byte opcode */
168 if (opcode == 0x0f) {
169 if (opcodes - orig_opcodes > MAX_INSN_SIZE - 1)
171 return test_bit(*opcodes,
172 (unsigned long *)twobyte_is_boostable);
175 switch (opcode & 0xf0) {
178 goto retry; /* REX prefix is boostable */
181 if (0x63 < opcode && opcode < 0x67)
182 goto retry; /* prefixes */
183 /* can't boost Address-size override and bound */
184 return (opcode != 0x62 && opcode != 0x67);
186 return 0; /* can't boost conditional jump */
188 /* can't boost software-interruptions */
189 return (0xc1 < opcode && opcode < 0xcc) || opcode == 0xcf;
191 /* can boost AA* and XLAT */
192 return (opcode == 0xd4 || opcode == 0xd5 || opcode == 0xd7);
194 /* can boost in/out and absolute jmps */
195 return ((opcode & 0x04) || opcode == 0xea);
197 if ((opcode & 0x0c) == 0 && opcode != 0xf1)
198 goto retry; /* lock/rep(ne) prefix */
199 /* clear and set flags are boostable */
200 return (opcode == 0xf5 || (0xf7 < opcode && opcode < 0xfe));
202 /* segment override prefixes are boostable */
203 if (opcode == 0x26 || opcode == 0x36 || opcode == 0x3e)
204 goto retry; /* prefixes */
205 /* CS override prefix and call are not boostable */
206 return (opcode != 0x2e && opcode != 0x9a);
210 /* Recover the probed instruction at addr for further analysis. */
211 static int recover_probed_instruction(kprobe_opcode_t *buf, unsigned long addr)
214 kp = get_kprobe((void *)addr);
219 * Basically, kp->ainsn.insn has an original instruction.
220 * However, RIP-relative instruction can not do single-stepping
221 * at different place, __copy_instruction() tweaks the displacement of
222 * that instruction. In that case, we can't recover the instruction
223 * from the kp->ainsn.insn.
225 * On the other hand, kp->opcode has a copy of the first byte of
226 * the probed instruction, which is overwritten by int3. And
227 * the instruction at kp->addr is not modified by kprobes except
228 * for the first byte, we can recover the original instruction
229 * from it and kp->opcode.
231 memcpy(buf, kp->addr, MAX_INSN_SIZE * sizeof(kprobe_opcode_t));
236 /* Check if paddr is at an instruction boundary */
237 static int __kprobes can_probe(unsigned long paddr)
240 unsigned long addr, offset = 0;
242 kprobe_opcode_t buf[MAX_INSN_SIZE];
244 if (!kallsyms_lookup_size_offset(paddr, NULL, &offset))
247 /* Decode instructions */
248 addr = paddr - offset;
249 while (addr < paddr) {
250 kernel_insn_init(&insn, (void *)addr);
251 insn_get_opcode(&insn);
254 * Check if the instruction has been modified by another
255 * kprobe, in which case we replace the breakpoint by the
256 * original instruction in our buffer.
258 if (insn.opcode.bytes[0] == BREAKPOINT_INSTRUCTION) {
259 ret = recover_probed_instruction(buf, addr);
262 * Another debugging subsystem might insert
263 * this breakpoint. In that case, we can't
267 kernel_insn_init(&insn, buf);
269 insn_get_length(&insn);
273 return (addr == paddr);
277 * Returns non-zero if opcode modifies the interrupt flag.
279 static int __kprobes is_IF_modifier(kprobe_opcode_t *insn)
282 insn = skip_prefixes(insn);
287 case 0xcf: /* iret/iretd */
288 case 0x9d: /* popf/popfd */
296 * Copy an instruction and adjust the displacement if the instruction
297 * uses the %rip-relative addressing mode.
298 * If it does, Return the address of the 32-bit displacement word.
299 * If not, return null.
300 * Only applicable to 64-bit x86.
302 static int __kprobes __copy_instruction(u8 *dest, u8 *src, int recover)
306 kprobe_opcode_t buf[MAX_INSN_SIZE];
308 kernel_insn_init(&insn, src);
310 insn_get_opcode(&insn);
311 if (insn.opcode.bytes[0] == BREAKPOINT_INSTRUCTION) {
312 ret = recover_probed_instruction(buf,
316 kernel_insn_init(&insn, buf);
319 insn_get_length(&insn);
320 memcpy(dest, insn.kaddr, insn.length);
323 if (insn_rip_relative(&insn)) {
326 kernel_insn_init(&insn, dest);
327 insn_get_displacement(&insn);
329 * The copied instruction uses the %rip-relative addressing
330 * mode. Adjust the displacement for the difference between
331 * the original location of this instruction and the location
332 * of the copy that will actually be run. The tricky bit here
333 * is making sure that the sign extension happens correctly in
334 * this calculation, since we need a signed 32-bit result to
335 * be sign-extended to 64 bits when it's added to the %rip
336 * value and yield the same 64-bit result that the sign-
337 * extension of the original signed 32-bit displacement would
340 newdisp = (u8 *) src + (s64) insn.displacement.value -
342 BUG_ON((s64) (s32) newdisp != newdisp); /* Sanity check. */
343 disp = (u8 *) dest + insn_offset_displacement(&insn);
344 *(s32 *) disp = (s32) newdisp;
350 static void __kprobes arch_copy_kprobe(struct kprobe *p)
353 * Copy an instruction without recovering int3, because it will be
354 * put by another subsystem.
356 __copy_instruction(p->ainsn.insn, p->addr, 0);
358 if (can_boost(p->addr))
359 p->ainsn.boostable = 0;
361 p->ainsn.boostable = -1;
363 p->opcode = *p->addr;
366 int __kprobes arch_prepare_kprobe(struct kprobe *p)
368 if (alternatives_text_reserved(p->addr, p->addr))
371 if (!can_probe((unsigned long)p->addr))
373 /* insn: must be on special executable page on x86. */
374 p->ainsn.insn = get_insn_slot();
381 void __kprobes arch_arm_kprobe(struct kprobe *p)
383 text_poke(p->addr, ((unsigned char []){BREAKPOINT_INSTRUCTION}), 1);
386 void __kprobes arch_disarm_kprobe(struct kprobe *p)
388 text_poke(p->addr, &p->opcode, 1);
391 void __kprobes arch_remove_kprobe(struct kprobe *p)
394 free_insn_slot(p->ainsn.insn, (p->ainsn.boostable == 1));
395 p->ainsn.insn = NULL;
399 static void __kprobes save_previous_kprobe(struct kprobe_ctlblk *kcb)
401 kcb->prev_kprobe.kp = kprobe_running();
402 kcb->prev_kprobe.status = kcb->kprobe_status;
403 kcb->prev_kprobe.old_flags = kcb->kprobe_old_flags;
404 kcb->prev_kprobe.saved_flags = kcb->kprobe_saved_flags;
407 static void __kprobes restore_previous_kprobe(struct kprobe_ctlblk *kcb)
409 __this_cpu_write(current_kprobe, kcb->prev_kprobe.kp);
410 kcb->kprobe_status = kcb->prev_kprobe.status;
411 kcb->kprobe_old_flags = kcb->prev_kprobe.old_flags;
412 kcb->kprobe_saved_flags = kcb->prev_kprobe.saved_flags;
415 static void __kprobes set_current_kprobe(struct kprobe *p, struct pt_regs *regs,
416 struct kprobe_ctlblk *kcb)
418 __this_cpu_write(current_kprobe, p);
419 kcb->kprobe_saved_flags = kcb->kprobe_old_flags
420 = (regs->flags & (X86_EFLAGS_TF | X86_EFLAGS_IF));
421 if (is_IF_modifier(p->ainsn.insn))
422 kcb->kprobe_saved_flags &= ~X86_EFLAGS_IF;
425 static void __kprobes clear_btf(void)
427 if (test_thread_flag(TIF_BLOCKSTEP)) {
428 unsigned long debugctl = get_debugctlmsr();
430 debugctl &= ~DEBUGCTLMSR_BTF;
431 update_debugctlmsr(debugctl);
435 static void __kprobes restore_btf(void)
437 if (test_thread_flag(TIF_BLOCKSTEP)) {
438 unsigned long debugctl = get_debugctlmsr();
440 debugctl |= DEBUGCTLMSR_BTF;
441 update_debugctlmsr(debugctl);
445 void __kprobes arch_prepare_kretprobe(struct kretprobe_instance *ri,
446 struct pt_regs *regs)
448 unsigned long *sara = stack_addr(regs);
450 ri->ret_addr = (kprobe_opcode_t *) *sara;
452 /* Replace the return addr with trampoline addr */
453 *sara = (unsigned long) &kretprobe_trampoline;
456 #ifdef CONFIG_OPTPROBES
457 static int __kprobes setup_detour_execution(struct kprobe *p,
458 struct pt_regs *regs,
461 #define setup_detour_execution(p, regs, reenter) (0)
464 static void __kprobes setup_singlestep(struct kprobe *p, struct pt_regs *regs,
465 struct kprobe_ctlblk *kcb, int reenter)
467 if (setup_detour_execution(p, regs, reenter))
470 #if !defined(CONFIG_PREEMPT)
471 if (p->ainsn.boostable == 1 && !p->post_handler) {
472 /* Boost up -- we can execute copied instructions directly */
474 reset_current_kprobe();
476 * Reentering boosted probe doesn't reset current_kprobe,
477 * nor set current_kprobe, because it doesn't use single
480 regs->ip = (unsigned long)p->ainsn.insn;
481 preempt_enable_no_resched();
486 save_previous_kprobe(kcb);
487 set_current_kprobe(p, regs, kcb);
488 kcb->kprobe_status = KPROBE_REENTER;
490 kcb->kprobe_status = KPROBE_HIT_SS;
491 /* Prepare real single stepping */
493 regs->flags |= X86_EFLAGS_TF;
494 regs->flags &= ~X86_EFLAGS_IF;
495 /* single step inline if the instruction is an int3 */
496 if (p->opcode == BREAKPOINT_INSTRUCTION)
497 regs->ip = (unsigned long)p->addr;
499 regs->ip = (unsigned long)p->ainsn.insn;
503 * We have reentered the kprobe_handler(), since another probe was hit while
504 * within the handler. We save the original kprobes variables and just single
505 * step on the instruction of the new probe without calling any user handlers.
507 static int __kprobes reenter_kprobe(struct kprobe *p, struct pt_regs *regs,
508 struct kprobe_ctlblk *kcb)
510 switch (kcb->kprobe_status) {
511 case KPROBE_HIT_SSDONE:
512 case KPROBE_HIT_ACTIVE:
513 kprobes_inc_nmissed_count(p);
514 setup_singlestep(p, regs, kcb, 1);
517 /* A probe has been hit in the codepath leading up to, or just
518 * after, single-stepping of a probed instruction. This entire
519 * codepath should strictly reside in .kprobes.text section.
520 * Raise a BUG or we'll continue in an endless reentering loop
521 * and eventually a stack overflow.
523 printk(KERN_WARNING "Unrecoverable kprobe detected at %p.\n",
528 /* impossible cases */
537 * Interrupts are disabled on entry as trap3 is an interrupt gate and they
538 * remain disabled throughout this function.
540 static int __kprobes kprobe_handler(struct pt_regs *regs)
542 kprobe_opcode_t *addr;
544 struct kprobe_ctlblk *kcb;
546 addr = (kprobe_opcode_t *)(regs->ip - sizeof(kprobe_opcode_t));
548 * We don't want to be preempted for the entire
549 * duration of kprobe processing. We conditionally
550 * re-enable preemption at the end of this function,
551 * and also in reenter_kprobe() and setup_singlestep().
555 kcb = get_kprobe_ctlblk();
556 p = get_kprobe(addr);
559 if (kprobe_running()) {
560 if (reenter_kprobe(p, regs, kcb))
563 set_current_kprobe(p, regs, kcb);
564 kcb->kprobe_status = KPROBE_HIT_ACTIVE;
567 * If we have no pre-handler or it returned 0, we
568 * continue with normal processing. If we have a
569 * pre-handler and it returned non-zero, it prepped
570 * for calling the break_handler below on re-entry
571 * for jprobe processing, so get out doing nothing
574 if (!p->pre_handler || !p->pre_handler(p, regs))
575 setup_singlestep(p, regs, kcb, 0);
578 } else if (*addr != BREAKPOINT_INSTRUCTION) {
580 * The breakpoint instruction was removed right
581 * after we hit it. Another cpu has removed
582 * either a probepoint or a debugger breakpoint
583 * at this address. In either case, no further
584 * handling of this interrupt is appropriate.
585 * Back up over the (now missing) int3 and run
586 * the original instruction.
588 regs->ip = (unsigned long)addr;
589 preempt_enable_no_resched();
591 } else if (kprobe_running()) {
592 p = __this_cpu_read(current_kprobe);
593 if (p->break_handler && p->break_handler(p, regs)) {
594 setup_singlestep(p, regs, kcb, 0);
597 } /* else: not a kprobe fault; let the kernel handle it */
599 preempt_enable_no_resched();
604 #define SAVE_REGS_STRING \
605 /* Skip cs, ip, orig_ax. */ \
606 " subq $24, %rsp\n" \
622 #define RESTORE_REGS_STRING \
638 /* Skip orig_ax, ip, cs */ \
641 #define SAVE_REGS_STRING \
642 /* Skip cs, ip, orig_ax and gs. */ \
643 " subl $16, %esp\n" \
654 #define RESTORE_REGS_STRING \
662 /* Skip ds, es, fs, gs, orig_ax, and ip. Note: don't pop cs here*/\
667 * When a retprobed function returns, this code saves registers and
668 * calls trampoline_handler() runs, which calls the kretprobe's handler.
670 static void __used __kprobes kretprobe_trampoline_holder(void)
673 ".global kretprobe_trampoline\n"
674 "kretprobe_trampoline: \n"
676 /* We don't bother saving the ss register */
681 " call trampoline_handler\n"
682 /* Replace saved sp with true return address. */
683 " movq %rax, 152(%rsp)\n"
690 " call trampoline_handler\n"
691 /* Move flags to cs */
692 " movl 56(%esp), %edx\n"
693 " movl %edx, 52(%esp)\n"
694 /* Replace saved flags with true return address. */
695 " movl %eax, 56(%esp)\n"
703 * Called from kretprobe_trampoline
705 static __used __kprobes void *trampoline_handler(struct pt_regs *regs)
707 struct kretprobe_instance *ri = NULL;
708 struct hlist_head *head, empty_rp;
709 struct hlist_node *node, *tmp;
710 unsigned long flags, orig_ret_address = 0;
711 unsigned long trampoline_address = (unsigned long)&kretprobe_trampoline;
712 kprobe_opcode_t *correct_ret_addr = NULL;
714 INIT_HLIST_HEAD(&empty_rp);
715 kretprobe_hash_lock(current, &head, &flags);
716 /* fixup registers */
718 regs->cs = __KERNEL_CS;
720 regs->cs = __KERNEL_CS | get_kernel_rpl();
723 regs->ip = trampoline_address;
724 regs->orig_ax = ~0UL;
727 * It is possible to have multiple instances associated with a given
728 * task either because multiple functions in the call path have
729 * return probes installed on them, and/or more than one
730 * return probe was registered for a target function.
732 * We can handle this because:
733 * - instances are always pushed into the head of the list
734 * - when multiple return probes are registered for the same
735 * function, the (chronologically) first instance's ret_addr
736 * will be the real return address, and all the rest will
737 * point to kretprobe_trampoline.
739 hlist_for_each_entry_safe(ri, node, tmp, head, hlist) {
740 if (ri->task != current)
741 /* another task is sharing our hash bucket */
744 orig_ret_address = (unsigned long)ri->ret_addr;
746 if (orig_ret_address != trampoline_address)
748 * This is the real return address. Any other
749 * instances associated with this task are for
750 * other calls deeper on the call stack
755 kretprobe_assert(ri, orig_ret_address, trampoline_address);
757 correct_ret_addr = ri->ret_addr;
758 hlist_for_each_entry_safe(ri, node, tmp, head, hlist) {
759 if (ri->task != current)
760 /* another task is sharing our hash bucket */
763 orig_ret_address = (unsigned long)ri->ret_addr;
764 if (ri->rp && ri->rp->handler) {
765 __this_cpu_write(current_kprobe, &ri->rp->kp);
766 get_kprobe_ctlblk()->kprobe_status = KPROBE_HIT_ACTIVE;
767 ri->ret_addr = correct_ret_addr;
768 ri->rp->handler(ri, regs);
769 __this_cpu_write(current_kprobe, NULL);
772 recycle_rp_inst(ri, &empty_rp);
774 if (orig_ret_address != trampoline_address)
776 * This is the real return address. Any other
777 * instances associated with this task are for
778 * other calls deeper on the call stack
783 kretprobe_hash_unlock(current, &flags);
785 hlist_for_each_entry_safe(ri, node, tmp, &empty_rp, hlist) {
786 hlist_del(&ri->hlist);
789 return (void *)orig_ret_address;
793 * Called after single-stepping. p->addr is the address of the
794 * instruction whose first byte has been replaced by the "int 3"
795 * instruction. To avoid the SMP problems that can occur when we
796 * temporarily put back the original opcode to single-step, we
797 * single-stepped a copy of the instruction. The address of this
798 * copy is p->ainsn.insn.
800 * This function prepares to return from the post-single-step
801 * interrupt. We have to fix up the stack as follows:
803 * 0) Except in the case of absolute or indirect jump or call instructions,
804 * the new ip is relative to the copied instruction. We need to make
805 * it relative to the original instruction.
807 * 1) If the single-stepped instruction was pushfl, then the TF and IF
808 * flags are set in the just-pushed flags, and may need to be cleared.
810 * 2) If the single-stepped instruction was a call, the return address
811 * that is atop the stack is the address following the copied instruction.
812 * We need to make it the address following the original instruction.
814 * If this is the first time we've single-stepped the instruction at
815 * this probepoint, and the instruction is boostable, boost it: add a
816 * jump instruction after the copied instruction, that jumps to the next
817 * instruction after the probepoint.
819 static void __kprobes resume_execution(struct kprobe *p,
820 struct pt_regs *regs, struct kprobe_ctlblk *kcb)
822 unsigned long *tos = stack_addr(regs);
823 unsigned long copy_ip = (unsigned long)p->ainsn.insn;
824 unsigned long orig_ip = (unsigned long)p->addr;
825 kprobe_opcode_t *insn = p->ainsn.insn;
828 insn = skip_prefixes(insn);
830 regs->flags &= ~X86_EFLAGS_TF;
832 case 0x9c: /* pushfl */
833 *tos &= ~(X86_EFLAGS_TF | X86_EFLAGS_IF);
834 *tos |= kcb->kprobe_old_flags;
836 case 0xc2: /* iret/ret/lret */
841 case 0xea: /* jmp absolute -- ip is correct */
842 /* ip is already adjusted, no more changes required */
843 p->ainsn.boostable = 1;
845 case 0xe8: /* call relative - Fix return addr */
846 *tos = orig_ip + (*tos - copy_ip);
849 case 0x9a: /* call absolute -- same as call absolute, indirect */
850 *tos = orig_ip + (*tos - copy_ip);
854 if ((insn[1] & 0x30) == 0x10) {
856 * call absolute, indirect
857 * Fix return addr; ip is correct.
858 * But this is not boostable
860 *tos = orig_ip + (*tos - copy_ip);
862 } else if (((insn[1] & 0x31) == 0x20) ||
863 ((insn[1] & 0x31) == 0x21)) {
865 * jmp near and far, absolute indirect
866 * ip is correct. And this is boostable
868 p->ainsn.boostable = 1;
875 if (p->ainsn.boostable == 0) {
876 if ((regs->ip > copy_ip) &&
877 (regs->ip - copy_ip) + 5 < MAX_INSN_SIZE) {
879 * These instructions can be executed directly if it
880 * jumps back to correct address.
882 synthesize_reljump((void *)regs->ip,
883 (void *)orig_ip + (regs->ip - copy_ip));
884 p->ainsn.boostable = 1;
886 p->ainsn.boostable = -1;
890 regs->ip += orig_ip - copy_ip;
897 * Interrupts are disabled on entry as trap1 is an interrupt gate and they
898 * remain disabled throughout this function.
900 static int __kprobes post_kprobe_handler(struct pt_regs *regs)
902 struct kprobe *cur = kprobe_running();
903 struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
908 resume_execution(cur, regs, kcb);
909 regs->flags |= kcb->kprobe_saved_flags;
911 if ((kcb->kprobe_status != KPROBE_REENTER) && cur->post_handler) {
912 kcb->kprobe_status = KPROBE_HIT_SSDONE;
913 cur->post_handler(cur, regs, 0);
916 /* Restore back the original saved kprobes variables and continue. */
917 if (kcb->kprobe_status == KPROBE_REENTER) {
918 restore_previous_kprobe(kcb);
921 reset_current_kprobe();
923 preempt_enable_no_resched();
926 * if somebody else is singlestepping across a probe point, flags
927 * will have TF set, in which case, continue the remaining processing
928 * of do_debug, as if this is not a probe hit.
930 if (regs->flags & X86_EFLAGS_TF)
936 int __kprobes kprobe_fault_handler(struct pt_regs *regs, int trapnr)
938 struct kprobe *cur = kprobe_running();
939 struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
941 switch (kcb->kprobe_status) {
945 * We are here because the instruction being single
946 * stepped caused a page fault. We reset the current
947 * kprobe and the ip points back to the probe address
948 * and allow the page fault handler to continue as a
951 regs->ip = (unsigned long)cur->addr;
953 * Trap flag (TF) has been set here because this fault
954 * happened where the single stepping will be done.
955 * So clear it by resetting the current kprobe:
957 regs->flags &= ~X86_EFLAGS_TF;
960 * If the TF flag was set before the kprobe hit,
963 regs->flags |= kcb->kprobe_old_flags;
965 if (kcb->kprobe_status == KPROBE_REENTER)
966 restore_previous_kprobe(kcb);
968 reset_current_kprobe();
969 preempt_enable_no_resched();
971 case KPROBE_HIT_ACTIVE:
972 case KPROBE_HIT_SSDONE:
974 * We increment the nmissed count for accounting,
975 * we can also use npre/npostfault count for accounting
976 * these specific fault cases.
978 kprobes_inc_nmissed_count(cur);
981 * We come here because instructions in the pre/post
982 * handler caused the page_fault, this could happen
983 * if handler tries to access user space by
984 * copy_from_user(), get_user() etc. Let the
985 * user-specified handler try to fix it first.
987 if (cur->fault_handler && cur->fault_handler(cur, regs, trapnr))
991 * In case the user-specified fault handler returned
992 * zero, try to fix up.
994 if (fixup_exception(regs))
998 * fixup routine could not handle it,
999 * Let do_page_fault() fix it.
1009 * Wrapper routine for handling exceptions.
1011 int __kprobes kprobe_exceptions_notify(struct notifier_block *self,
1012 unsigned long val, void *data)
1014 struct die_args *args = data;
1015 int ret = NOTIFY_DONE;
1017 if (args->regs && user_mode_vm(args->regs))
1022 if (kprobe_handler(args->regs))
1026 if (post_kprobe_handler(args->regs)) {
1028 * Reset the BS bit in dr6 (pointed by args->err) to
1029 * denote completion of processing
1031 (*(unsigned long *)ERR_PTR(args->err)) &= ~DR_STEP;
1037 * To be potentially processing a kprobe fault and to
1038 * trust the result from kprobe_running(), we have
1039 * be non-preemptible.
1041 if (!preemptible() && kprobe_running() &&
1042 kprobe_fault_handler(args->regs, args->trapnr))
1051 int __kprobes setjmp_pre_handler(struct kprobe *p, struct pt_regs *regs)
1053 struct jprobe *jp = container_of(p, struct jprobe, kp);
1055 struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
1057 kcb->jprobe_saved_regs = *regs;
1058 kcb->jprobe_saved_sp = stack_addr(regs);
1059 addr = (unsigned long)(kcb->jprobe_saved_sp);
1062 * As Linus pointed out, gcc assumes that the callee
1063 * owns the argument space and could overwrite it, e.g.
1064 * tailcall optimization. So, to be absolutely safe
1065 * we also save and restore enough stack bytes to cover
1066 * the argument area.
1068 memcpy(kcb->jprobes_stack, (kprobe_opcode_t *)addr,
1069 MIN_STACK_SIZE(addr));
1070 regs->flags &= ~X86_EFLAGS_IF;
1071 trace_hardirqs_off();
1072 regs->ip = (unsigned long)(jp->entry);
1075 * jprobes use jprobe_return() which skips the normal return
1076 * path of the function, and this messes up the accounting of the
1077 * function graph tracer to get messed up.
1079 * Pause function graph tracing while performing the jprobe function.
1081 pause_graph_tracing();
1085 void __kprobes jprobe_return(void)
1087 struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
1090 #ifdef CONFIG_X86_64
1091 " xchg %%rbx,%%rsp \n"
1093 " xchgl %%ebx,%%esp \n"
1096 " .globl jprobe_return_end\n"
1097 " jprobe_return_end: \n"
1099 (kcb->jprobe_saved_sp):"memory");
1102 int __kprobes longjmp_break_handler(struct kprobe *p, struct pt_regs *regs)
1104 struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
1105 u8 *addr = (u8 *) (regs->ip - 1);
1106 struct jprobe *jp = container_of(p, struct jprobe, kp);
1107 void *saved_sp = kcb->jprobe_saved_sp;
1109 if ((addr > (u8 *) jprobe_return) &&
1110 (addr < (u8 *) jprobe_return_end)) {
1111 if (stack_addr(regs) != saved_sp) {
1112 struct pt_regs *saved_regs = &kcb->jprobe_saved_regs;
1114 "current sp %p does not match saved sp %p\n",
1115 stack_addr(regs), saved_sp);
1116 printk(KERN_ERR "Saved registers for jprobe %p\n", jp);
1117 show_registers(saved_regs);
1118 printk(KERN_ERR "Current registers\n");
1119 show_registers(regs);
1122 /* It's OK to start function graph tracing again */
1123 unpause_graph_tracing();
1124 *regs = kcb->jprobe_saved_regs;
1125 memcpy(saved_sp, kcb->jprobes_stack, MIN_STACK_SIZE(saved_sp));
1126 preempt_enable_no_resched();
1133 #ifdef CONFIG_OPTPROBES
1135 /* Insert a call instruction at address 'from', which calls address 'to'.*/
1136 static void __kprobes synthesize_relcall(void *from, void *to)
1138 __synthesize_relative_insn(from, to, RELATIVECALL_OPCODE);
1141 /* Insert a move instruction which sets a pointer to eax/rdi (1st arg). */
1142 static void __kprobes synthesize_set_arg1(kprobe_opcode_t *addr,
1145 #ifdef CONFIG_X86_64
1151 *(unsigned long *)addr = val;
1154 static void __used __kprobes kprobes_optinsn_template_holder(void)
1157 ".global optprobe_template_entry\n"
1158 "optprobe_template_entry: \n"
1159 #ifdef CONFIG_X86_64
1160 /* We don't bother saving the ss register */
1164 " movq %rsp, %rsi\n"
1165 ".global optprobe_template_val\n"
1166 "optprobe_template_val: \n"
1169 ".global optprobe_template_call\n"
1170 "optprobe_template_call: \n"
1172 /* Move flags to rsp */
1173 " movq 144(%rsp), %rdx\n"
1174 " movq %rdx, 152(%rsp)\n"
1176 /* Skip flags entry */
1179 #else /* CONFIG_X86_32 */
1182 " movl %esp, %edx\n"
1183 ".global optprobe_template_val\n"
1184 "optprobe_template_val: \n"
1186 ".global optprobe_template_call\n"
1187 "optprobe_template_call: \n"
1190 " addl $4, %esp\n" /* skip cs */
1193 ".global optprobe_template_end\n"
1194 "optprobe_template_end: \n");
1197 #define TMPL_MOVE_IDX \
1198 ((long)&optprobe_template_val - (long)&optprobe_template_entry)
1199 #define TMPL_CALL_IDX \
1200 ((long)&optprobe_template_call - (long)&optprobe_template_entry)
1201 #define TMPL_END_IDX \
1202 ((long)&optprobe_template_end - (long)&optprobe_template_entry)
1204 #define INT3_SIZE sizeof(kprobe_opcode_t)
1206 /* Optimized kprobe call back function: called from optinsn */
1207 static void __kprobes optimized_callback(struct optimized_kprobe *op,
1208 struct pt_regs *regs)
1210 struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
1211 unsigned long flags;
1213 /* This is possible if op is under delayed unoptimizing */
1214 if (kprobe_disabled(&op->kp))
1217 local_irq_save(flags);
1218 if (kprobe_running()) {
1219 kprobes_inc_nmissed_count(&op->kp);
1221 /* Save skipped registers */
1222 #ifdef CONFIG_X86_64
1223 regs->cs = __KERNEL_CS;
1225 regs->cs = __KERNEL_CS | get_kernel_rpl();
1228 regs->ip = (unsigned long)op->kp.addr + INT3_SIZE;
1229 regs->orig_ax = ~0UL;
1231 __this_cpu_write(current_kprobe, &op->kp);
1232 kcb->kprobe_status = KPROBE_HIT_ACTIVE;
1233 opt_pre_handler(&op->kp, regs);
1234 __this_cpu_write(current_kprobe, NULL);
1236 local_irq_restore(flags);
1239 static int __kprobes copy_optimized_instructions(u8 *dest, u8 *src)
1243 while (len < RELATIVEJUMP_SIZE) {
1244 ret = __copy_instruction(dest + len, src + len, 1);
1245 if (!ret || !can_boost(dest + len))
1249 /* Check whether the address range is reserved */
1250 if (ftrace_text_reserved(src, src + len - 1) ||
1251 alternatives_text_reserved(src, src + len - 1) ||
1252 jump_label_text_reserved(src, src + len - 1))
1258 /* Check whether insn is indirect jump */
1259 static int __kprobes insn_is_indirect_jump(struct insn *insn)
1261 return ((insn->opcode.bytes[0] == 0xff &&
1262 (X86_MODRM_REG(insn->modrm.value) & 6) == 4) || /* Jump */
1263 insn->opcode.bytes[0] == 0xea); /* Segment based jump */
1266 /* Check whether insn jumps into specified address range */
1267 static int insn_jump_into_range(struct insn *insn, unsigned long start, int len)
1269 unsigned long target = 0;
1271 switch (insn->opcode.bytes[0]) {
1272 case 0xe0: /* loopne */
1273 case 0xe1: /* loope */
1274 case 0xe2: /* loop */
1275 case 0xe3: /* jcxz */
1276 case 0xe9: /* near relative jump */
1277 case 0xeb: /* short relative jump */
1280 if ((insn->opcode.bytes[1] & 0xf0) == 0x80) /* jcc near */
1284 if ((insn->opcode.bytes[0] & 0xf0) == 0x70) /* jcc short */
1288 target = (unsigned long)insn->next_byte + insn->immediate.value;
1290 return (start <= target && target <= start + len);
1293 /* Decode whole function to ensure any instructions don't jump into target */
1294 static int __kprobes can_optimize(unsigned long paddr)
1297 unsigned long addr, size = 0, offset = 0;
1299 kprobe_opcode_t buf[MAX_INSN_SIZE];
1301 /* Lookup symbol including addr */
1302 if (!kallsyms_lookup_size_offset(paddr, &size, &offset))
1306 * Do not optimize in the entry code due to the unstable
1309 if ((paddr >= (unsigned long )__entry_text_start) &&
1310 (paddr < (unsigned long )__entry_text_end))
1313 /* Check there is enough space for a relative jump. */
1314 if (size - offset < RELATIVEJUMP_SIZE)
1317 /* Decode instructions */
1318 addr = paddr - offset;
1319 while (addr < paddr - offset + size) { /* Decode until function end */
1320 if (search_exception_tables(addr))
1322 * Since some fixup code will jumps into this function,
1323 * we can't optimize kprobe in this function.
1326 kernel_insn_init(&insn, (void *)addr);
1327 insn_get_opcode(&insn);
1328 if (insn.opcode.bytes[0] == BREAKPOINT_INSTRUCTION) {
1329 ret = recover_probed_instruction(buf, addr);
1332 kernel_insn_init(&insn, buf);
1334 insn_get_length(&insn);
1335 /* Recover address */
1336 insn.kaddr = (void *)addr;
1337 insn.next_byte = (void *)(addr + insn.length);
1338 /* Check any instructions don't jump into target */
1339 if (insn_is_indirect_jump(&insn) ||
1340 insn_jump_into_range(&insn, paddr + INT3_SIZE,
1341 RELATIVE_ADDR_SIZE))
1343 addr += insn.length;
1349 /* Check optimized_kprobe can actually be optimized. */
1350 int __kprobes arch_check_optimized_kprobe(struct optimized_kprobe *op)
1355 for (i = 1; i < op->optinsn.size; i++) {
1356 p = get_kprobe(op->kp.addr + i);
1357 if (p && !kprobe_disabled(p))
1364 /* Check the addr is within the optimized instructions. */
1365 int __kprobes arch_within_optimized_kprobe(struct optimized_kprobe *op,
1368 return ((unsigned long)op->kp.addr <= addr &&
1369 (unsigned long)op->kp.addr + op->optinsn.size > addr);
1372 /* Free optimized instruction slot */
1374 void __arch_remove_optimized_kprobe(struct optimized_kprobe *op, int dirty)
1376 if (op->optinsn.insn) {
1377 free_optinsn_slot(op->optinsn.insn, dirty);
1378 op->optinsn.insn = NULL;
1379 op->optinsn.size = 0;
1383 void __kprobes arch_remove_optimized_kprobe(struct optimized_kprobe *op)
1385 __arch_remove_optimized_kprobe(op, 1);
1389 * Copy replacing target instructions
1390 * Target instructions MUST be relocatable (checked inside)
1392 int __kprobes arch_prepare_optimized_kprobe(struct optimized_kprobe *op)
1398 if (!can_optimize((unsigned long)op->kp.addr))
1401 op->optinsn.insn = get_optinsn_slot();
1402 if (!op->optinsn.insn)
1406 * Verify if the address gap is in 2GB range, because this uses
1409 rel = (long)op->optinsn.insn - (long)op->kp.addr + RELATIVEJUMP_SIZE;
1410 if (abs(rel) > 0x7fffffff)
1413 buf = (u8 *)op->optinsn.insn;
1415 /* Copy instructions into the out-of-line buffer */
1416 ret = copy_optimized_instructions(buf + TMPL_END_IDX, op->kp.addr);
1418 __arch_remove_optimized_kprobe(op, 0);
1421 op->optinsn.size = ret;
1423 /* Copy arch-dep-instance from template */
1424 memcpy(buf, &optprobe_template_entry, TMPL_END_IDX);
1426 /* Set probe information */
1427 synthesize_set_arg1(buf + TMPL_MOVE_IDX, (unsigned long)op);
1429 /* Set probe function call */
1430 synthesize_relcall(buf + TMPL_CALL_IDX, optimized_callback);
1432 /* Set returning jmp instruction at the tail of out-of-line buffer */
1433 synthesize_reljump(buf + TMPL_END_IDX + op->optinsn.size,
1434 (u8 *)op->kp.addr + op->optinsn.size);
1436 flush_icache_range((unsigned long) buf,
1437 (unsigned long) buf + TMPL_END_IDX +
1438 op->optinsn.size + RELATIVEJUMP_SIZE);
1442 #define MAX_OPTIMIZE_PROBES 256
1443 static struct text_poke_param *jump_poke_params;
1444 static struct jump_poke_buffer {
1445 u8 buf[RELATIVEJUMP_SIZE];
1448 static void __kprobes setup_optimize_kprobe(struct text_poke_param *tprm,
1450 struct optimized_kprobe *op)
1452 s32 rel = (s32)((long)op->optinsn.insn -
1453 ((long)op->kp.addr + RELATIVEJUMP_SIZE));
1455 /* Backup instructions which will be replaced by jump address */
1456 memcpy(op->optinsn.copied_insn, op->kp.addr + INT3_SIZE,
1457 RELATIVE_ADDR_SIZE);
1459 insn_buf[0] = RELATIVEJUMP_OPCODE;
1460 *(s32 *)(&insn_buf[1]) = rel;
1462 tprm->addr = op->kp.addr;
1463 tprm->opcode = insn_buf;
1464 tprm->len = RELATIVEJUMP_SIZE;
1468 * Replace breakpoints (int3) with relative jumps.
1469 * Caller must call with locking kprobe_mutex and text_mutex.
1471 void __kprobes arch_optimize_kprobes(struct list_head *oplist)
1473 struct optimized_kprobe *op, *tmp;
1476 list_for_each_entry_safe(op, tmp, oplist, list) {
1477 WARN_ON(kprobe_disabled(&op->kp));
1479 setup_optimize_kprobe(&jump_poke_params[c],
1480 jump_poke_bufs[c].buf, op);
1481 list_del_init(&op->list);
1482 if (++c >= MAX_OPTIMIZE_PROBES)
1487 * text_poke_smp doesn't support NMI/MCE code modifying.
1488 * However, since kprobes itself also doesn't support NMI/MCE
1489 * code probing, it's not a problem.
1491 text_poke_smp_batch(jump_poke_params, c);
1494 static void __kprobes setup_unoptimize_kprobe(struct text_poke_param *tprm,
1496 struct optimized_kprobe *op)
1498 /* Set int3 to first byte for kprobes */
1499 insn_buf[0] = BREAKPOINT_INSTRUCTION;
1500 memcpy(insn_buf + 1, op->optinsn.copied_insn, RELATIVE_ADDR_SIZE);
1502 tprm->addr = op->kp.addr;
1503 tprm->opcode = insn_buf;
1504 tprm->len = RELATIVEJUMP_SIZE;
1508 * Recover original instructions and breakpoints from relative jumps.
1509 * Caller must call with locking kprobe_mutex.
1511 extern void arch_unoptimize_kprobes(struct list_head *oplist,
1512 struct list_head *done_list)
1514 struct optimized_kprobe *op, *tmp;
1517 list_for_each_entry_safe(op, tmp, oplist, list) {
1519 setup_unoptimize_kprobe(&jump_poke_params[c],
1520 jump_poke_bufs[c].buf, op);
1521 list_move(&op->list, done_list);
1522 if (++c >= MAX_OPTIMIZE_PROBES)
1527 * text_poke_smp doesn't support NMI/MCE code modifying.
1528 * However, since kprobes itself also doesn't support NMI/MCE
1529 * code probing, it's not a problem.
1531 text_poke_smp_batch(jump_poke_params, c);
1534 /* Replace a relative jump with a breakpoint (int3). */
1535 void __kprobes arch_unoptimize_kprobe(struct optimized_kprobe *op)
1537 u8 buf[RELATIVEJUMP_SIZE];
1539 /* Set int3 to first byte for kprobes */
1540 buf[0] = BREAKPOINT_INSTRUCTION;
1541 memcpy(buf + 1, op->optinsn.copied_insn, RELATIVE_ADDR_SIZE);
1542 text_poke_smp(op->kp.addr, buf, RELATIVEJUMP_SIZE);
1545 static int __kprobes setup_detour_execution(struct kprobe *p,
1546 struct pt_regs *regs,
1549 struct optimized_kprobe *op;
1551 if (p->flags & KPROBE_FLAG_OPTIMIZED) {
1552 /* This kprobe is really able to run optimized path. */
1553 op = container_of(p, struct optimized_kprobe, kp);
1554 /* Detour through copied instructions */
1555 regs->ip = (unsigned long)op->optinsn.insn + TMPL_END_IDX;
1557 reset_current_kprobe();
1558 preempt_enable_no_resched();
1564 static int __kprobes init_poke_params(void)
1566 /* Allocate code buffer and parameter array */
1567 jump_poke_bufs = kmalloc(sizeof(struct jump_poke_buffer) *
1568 MAX_OPTIMIZE_PROBES, GFP_KERNEL);
1569 if (!jump_poke_bufs)
1572 jump_poke_params = kmalloc(sizeof(struct text_poke_param) *
1573 MAX_OPTIMIZE_PROBES, GFP_KERNEL);
1574 if (!jump_poke_params) {
1575 kfree(jump_poke_bufs);
1576 jump_poke_bufs = NULL;
1582 #else /* !CONFIG_OPTPROBES */
1583 static int __kprobes init_poke_params(void)
1589 int __init arch_init_kprobes(void)
1591 return init_poke_params();
1594 int __kprobes arch_trampoline_kprobe(struct kprobe *p)