Mention branches and keyring.
[releases.git] / x86 / kernel / kprobes / core.c
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
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'.*/
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'.*/
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  */
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
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  */
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 */
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. */
301 kprobe_opcode_t *arch_adjust_kprobe_addr(unsigned long addr, unsigned long offset,
302                                          bool *on_func_entry)
303 {
304         u32 insn;
305
306         /*
307          * Since 'addr' is not guaranteed to be safe to access, use
308          * copy_from_kernel_nofault() to read the instruction:
309          */
310         if (copy_from_kernel_nofault(&insn, (void *)addr, sizeof(u32)))
311                 return NULL;
312
313         if (is_endbr(insn)) {
314                 *on_func_entry = !offset || offset == 4;
315                 if (*on_func_entry)
316                         offset = 4;
317
318         } else {
319                 *on_func_entry = !offset;
320         }
321
322         return (kprobe_opcode_t *)(addr + offset);
323 }
324
325 /*
326  * Copy an instruction with recovering modified instruction by kprobes
327  * and adjust the displacement if the instruction uses the %rip-relative
328  * addressing mode. Note that since @real will be the final place of copied
329  * instruction, displacement must be adjust by @real, not @dest.
330  * This returns the length of copied instruction, or 0 if it has an error.
331  */
332 int __copy_instruction(u8 *dest, u8 *src, u8 *real, struct insn *insn)
333 {
334         kprobe_opcode_t buf[MAX_INSN_SIZE];
335         unsigned long recovered_insn = recover_probed_instruction(buf, (unsigned long)src);
336         int ret;
337
338         if (!recovered_insn || !insn)
339                 return 0;
340
341         /* This can access kernel text if given address is not recovered */
342         if (copy_from_kernel_nofault(dest, (void *)recovered_insn,
343                         MAX_INSN_SIZE))
344                 return 0;
345
346         ret = insn_decode_kernel(insn, dest);
347         if (ret < 0)
348                 return 0;
349
350         /* We can not probe force emulate prefixed instruction */
351         if (insn_has_emulate_prefix(insn))
352                 return 0;
353
354         /* Another subsystem puts a breakpoint, failed to recover */
355         if (insn->opcode.bytes[0] == INT3_INSN_OPCODE)
356                 return 0;
357
358         /* We should not singlestep on the exception masking instructions */
359         if (insn_masking_exception(insn))
360                 return 0;
361
362 #ifdef CONFIG_X86_64
363         /* Only x86_64 has RIP relative instructions */
364         if (insn_rip_relative(insn)) {
365                 s64 newdisp;
366                 u8 *disp;
367                 /*
368                  * The copied instruction uses the %rip-relative addressing
369                  * mode.  Adjust the displacement for the difference between
370                  * the original location of this instruction and the location
371                  * of the copy that will actually be run.  The tricky bit here
372                  * is making sure that the sign extension happens correctly in
373                  * this calculation, since we need a signed 32-bit result to
374                  * be sign-extended to 64 bits when it's added to the %rip
375                  * value and yield the same 64-bit result that the sign-
376                  * extension of the original signed 32-bit displacement would
377                  * have given.
378                  */
379                 newdisp = (u8 *) src + (s64) insn->displacement.value
380                           - (u8 *) real;
381                 if ((s64) (s32) newdisp != newdisp) {
382                         pr_err("Kprobes error: new displacement does not fit into s32 (%llx)\n", newdisp);
383                         return 0;
384                 }
385                 disp = (u8 *) dest + insn_offset_displacement(insn);
386                 *(s32 *) disp = (s32) newdisp;
387         }
388 #endif
389         return insn->length;
390 }
391
392 /* Prepare reljump or int3 right after instruction */
393 static int prepare_singlestep(kprobe_opcode_t *buf, struct kprobe *p,
394                               struct insn *insn)
395 {
396         int len = insn->length;
397
398         if (!IS_ENABLED(CONFIG_PREEMPTION) &&
399             !p->post_handler && can_boost(insn, p->addr) &&
400             MAX_INSN_SIZE - len >= JMP32_INSN_SIZE) {
401                 /*
402                  * These instructions can be executed directly if it
403                  * jumps back to correct address.
404                  */
405                 synthesize_reljump(buf + len, p->ainsn.insn + len,
406                                    p->addr + insn->length);
407                 len += JMP32_INSN_SIZE;
408                 p->ainsn.boostable = 1;
409         } else {
410                 /* Otherwise, put an int3 for trapping singlestep */
411                 if (MAX_INSN_SIZE - len < INT3_INSN_SIZE)
412                         return -ENOSPC;
413
414                 buf[len] = INT3_INSN_OPCODE;
415                 len += INT3_INSN_SIZE;
416         }
417
418         return len;
419 }
420
421 /* Make page to RO mode when allocate it */
422 void *alloc_insn_page(void)
423 {
424         void *page;
425
426         page = module_alloc(PAGE_SIZE);
427         if (!page)
428                 return NULL;
429
430         set_vm_flush_reset_perms(page);
431         /*
432          * First make the page read-only, and only then make it executable to
433          * prevent it from being W+X in between.
434          */
435         set_memory_ro((unsigned long)page, 1);
436
437         /*
438          * TODO: Once additional kernel code protection mechanisms are set, ensure
439          * that the page was not maliciously altered and it is still zeroed.
440          */
441         set_memory_x((unsigned long)page, 1);
442
443         return page;
444 }
445
446 /* Kprobe x86 instruction emulation - only regs->ip or IF flag modifiers */
447
448 static void kprobe_emulate_ifmodifiers(struct kprobe *p, struct pt_regs *regs)
449 {
450         switch (p->ainsn.opcode) {
451         case 0xfa:      /* cli */
452                 regs->flags &= ~(X86_EFLAGS_IF);
453                 break;
454         case 0xfb:      /* sti */
455                 regs->flags |= X86_EFLAGS_IF;
456                 break;
457         case 0x9c:      /* pushf */
458                 int3_emulate_push(regs, regs->flags);
459                 break;
460         case 0x9d:      /* popf */
461                 regs->flags = int3_emulate_pop(regs);
462                 break;
463         }
464         regs->ip = regs->ip - INT3_INSN_SIZE + p->ainsn.size;
465 }
466 NOKPROBE_SYMBOL(kprobe_emulate_ifmodifiers);
467
468 static void kprobe_emulate_ret(struct kprobe *p, struct pt_regs *regs)
469 {
470         int3_emulate_ret(regs);
471 }
472 NOKPROBE_SYMBOL(kprobe_emulate_ret);
473
474 static void kprobe_emulate_call(struct kprobe *p, struct pt_regs *regs)
475 {
476         unsigned long func = regs->ip - INT3_INSN_SIZE + p->ainsn.size;
477
478         func += p->ainsn.rel32;
479         int3_emulate_call(regs, func);
480 }
481 NOKPROBE_SYMBOL(kprobe_emulate_call);
482
483 static void kprobe_emulate_jmp(struct kprobe *p, struct pt_regs *regs)
484 {
485         unsigned long ip = regs->ip - INT3_INSN_SIZE + p->ainsn.size;
486
487         ip += p->ainsn.rel32;
488         int3_emulate_jmp(regs, ip);
489 }
490 NOKPROBE_SYMBOL(kprobe_emulate_jmp);
491
492 static void kprobe_emulate_jcc(struct kprobe *p, struct pt_regs *regs)
493 {
494         unsigned long ip = regs->ip - INT3_INSN_SIZE + p->ainsn.size;
495
496         int3_emulate_jcc(regs, p->ainsn.jcc.type, ip, p->ainsn.rel32);
497 }
498 NOKPROBE_SYMBOL(kprobe_emulate_jcc);
499
500 static void kprobe_emulate_loop(struct kprobe *p, struct pt_regs *regs)
501 {
502         unsigned long ip = regs->ip - INT3_INSN_SIZE + p->ainsn.size;
503         bool match;
504
505         if (p->ainsn.loop.type != 3) {  /* LOOP* */
506                 if (p->ainsn.loop.asize == 32)
507                         match = ((*(u32 *)&regs->cx)--) != 0;
508 #ifdef CONFIG_X86_64
509                 else if (p->ainsn.loop.asize == 64)
510                         match = ((*(u64 *)&regs->cx)--) != 0;
511 #endif
512                 else
513                         match = ((*(u16 *)&regs->cx)--) != 0;
514         } else {                        /* JCXZ */
515                 if (p->ainsn.loop.asize == 32)
516                         match = *(u32 *)(&regs->cx) == 0;
517 #ifdef CONFIG_X86_64
518                 else if (p->ainsn.loop.asize == 64)
519                         match = *(u64 *)(&regs->cx) == 0;
520 #endif
521                 else
522                         match = *(u16 *)(&regs->cx) == 0;
523         }
524
525         if (p->ainsn.loop.type == 0)    /* LOOPNE */
526                 match = match && !(regs->flags & X86_EFLAGS_ZF);
527         else if (p->ainsn.loop.type == 1)       /* LOOPE */
528                 match = match && (regs->flags & X86_EFLAGS_ZF);
529
530         if (match)
531                 ip += p->ainsn.rel32;
532         int3_emulate_jmp(regs, ip);
533 }
534 NOKPROBE_SYMBOL(kprobe_emulate_loop);
535
536 static const int addrmode_regoffs[] = {
537         offsetof(struct pt_regs, ax),
538         offsetof(struct pt_regs, cx),
539         offsetof(struct pt_regs, dx),
540         offsetof(struct pt_regs, bx),
541         offsetof(struct pt_regs, sp),
542         offsetof(struct pt_regs, bp),
543         offsetof(struct pt_regs, si),
544         offsetof(struct pt_regs, di),
545 #ifdef CONFIG_X86_64
546         offsetof(struct pt_regs, r8),
547         offsetof(struct pt_regs, r9),
548         offsetof(struct pt_regs, r10),
549         offsetof(struct pt_regs, r11),
550         offsetof(struct pt_regs, r12),
551         offsetof(struct pt_regs, r13),
552         offsetof(struct pt_regs, r14),
553         offsetof(struct pt_regs, r15),
554 #endif
555 };
556
557 static void kprobe_emulate_call_indirect(struct kprobe *p, struct pt_regs *regs)
558 {
559         unsigned long offs = addrmode_regoffs[p->ainsn.indirect.reg];
560
561         int3_emulate_push(regs, regs->ip - INT3_INSN_SIZE + p->ainsn.size);
562         int3_emulate_jmp(regs, regs_get_register(regs, offs));
563 }
564 NOKPROBE_SYMBOL(kprobe_emulate_call_indirect);
565
566 static void kprobe_emulate_jmp_indirect(struct kprobe *p, struct pt_regs *regs)
567 {
568         unsigned long offs = addrmode_regoffs[p->ainsn.indirect.reg];
569
570         int3_emulate_jmp(regs, regs_get_register(regs, offs));
571 }
572 NOKPROBE_SYMBOL(kprobe_emulate_jmp_indirect);
573
574 static int prepare_emulation(struct kprobe *p, struct insn *insn)
575 {
576         insn_byte_t opcode = insn->opcode.bytes[0];
577
578         switch (opcode) {
579         case 0xfa:              /* cli */
580         case 0xfb:              /* sti */
581         case 0x9c:              /* pushfl */
582         case 0x9d:              /* popf/popfd */
583                 /*
584                  * IF modifiers must be emulated since it will enable interrupt while
585                  * int3 single stepping.
586                  */
587                 p->ainsn.emulate_op = kprobe_emulate_ifmodifiers;
588                 p->ainsn.opcode = opcode;
589                 break;
590         case 0xc2:      /* ret/lret */
591         case 0xc3:
592         case 0xca:
593         case 0xcb:
594                 p->ainsn.emulate_op = kprobe_emulate_ret;
595                 break;
596         case 0x9a:      /* far call absolute -- segment is not supported */
597         case 0xea:      /* far jmp absolute -- segment is not supported */
598         case 0xcc:      /* int3 */
599         case 0xcf:      /* iret -- in-kernel IRET is not supported */
600                 return -EOPNOTSUPP;
601                 break;
602         case 0xe8:      /* near call relative */
603                 p->ainsn.emulate_op = kprobe_emulate_call;
604                 if (insn->immediate.nbytes == 2)
605                         p->ainsn.rel32 = *(s16 *)&insn->immediate.value;
606                 else
607                         p->ainsn.rel32 = *(s32 *)&insn->immediate.value;
608                 break;
609         case 0xeb:      /* short jump relative */
610         case 0xe9:      /* near jump relative */
611                 p->ainsn.emulate_op = kprobe_emulate_jmp;
612                 if (insn->immediate.nbytes == 1)
613                         p->ainsn.rel32 = *(s8 *)&insn->immediate.value;
614                 else if (insn->immediate.nbytes == 2)
615                         p->ainsn.rel32 = *(s16 *)&insn->immediate.value;
616                 else
617                         p->ainsn.rel32 = *(s32 *)&insn->immediate.value;
618                 break;
619         case 0x70 ... 0x7f:
620                 /* 1 byte conditional jump */
621                 p->ainsn.emulate_op = kprobe_emulate_jcc;
622                 p->ainsn.jcc.type = opcode & 0xf;
623                 p->ainsn.rel32 = *(char *)insn->immediate.bytes;
624                 break;
625         case 0x0f:
626                 opcode = insn->opcode.bytes[1];
627                 if ((opcode & 0xf0) == 0x80) {
628                         /* 2 bytes Conditional Jump */
629                         p->ainsn.emulate_op = kprobe_emulate_jcc;
630                         p->ainsn.jcc.type = opcode & 0xf;
631                         if (insn->immediate.nbytes == 2)
632                                 p->ainsn.rel32 = *(s16 *)&insn->immediate.value;
633                         else
634                                 p->ainsn.rel32 = *(s32 *)&insn->immediate.value;
635                 } else if (opcode == 0x01 &&
636                            X86_MODRM_REG(insn->modrm.bytes[0]) == 0 &&
637                            X86_MODRM_MOD(insn->modrm.bytes[0]) == 3) {
638                         /* VM extensions - not supported */
639                         return -EOPNOTSUPP;
640                 }
641                 break;
642         case 0xe0:      /* Loop NZ */
643         case 0xe1:      /* Loop */
644         case 0xe2:      /* Loop */
645         case 0xe3:      /* J*CXZ */
646                 p->ainsn.emulate_op = kprobe_emulate_loop;
647                 p->ainsn.loop.type = opcode & 0x3;
648                 p->ainsn.loop.asize = insn->addr_bytes * 8;
649                 p->ainsn.rel32 = *(s8 *)&insn->immediate.value;
650                 break;
651         case 0xff:
652                 /*
653                  * Since the 0xff is an extended group opcode, the instruction
654                  * is determined by the MOD/RM byte.
655                  */
656                 opcode = insn->modrm.bytes[0];
657                 if ((opcode & 0x30) == 0x10) {
658                         if ((opcode & 0x8) == 0x8)
659                                 return -EOPNOTSUPP;     /* far call */
660                         /* call absolute, indirect */
661                         p->ainsn.emulate_op = kprobe_emulate_call_indirect;
662                 } else if ((opcode & 0x30) == 0x20) {
663                         if ((opcode & 0x8) == 0x8)
664                                 return -EOPNOTSUPP;     /* far jmp */
665                         /* jmp near absolute indirect */
666                         p->ainsn.emulate_op = kprobe_emulate_jmp_indirect;
667                 } else
668                         break;
669
670                 if (insn->addr_bytes != sizeof(unsigned long))
671                         return -EOPNOTSUPP;     /* Don't support different size */
672                 if (X86_MODRM_MOD(opcode) != 3)
673                         return -EOPNOTSUPP;     /* TODO: support memory addressing */
674
675                 p->ainsn.indirect.reg = X86_MODRM_RM(opcode);
676 #ifdef CONFIG_X86_64
677                 if (X86_REX_B(insn->rex_prefix.value))
678                         p->ainsn.indirect.reg += 8;
679 #endif
680                 break;
681         default:
682                 break;
683         }
684         p->ainsn.size = insn->length;
685
686         return 0;
687 }
688
689 static int arch_copy_kprobe(struct kprobe *p)
690 {
691         struct insn insn;
692         kprobe_opcode_t buf[MAX_INSN_SIZE];
693         int ret, len;
694
695         /* Copy an instruction with recovering if other optprobe modifies it.*/
696         len = __copy_instruction(buf, p->addr, p->ainsn.insn, &insn);
697         if (!len)
698                 return -EINVAL;
699
700         /* Analyze the opcode and setup emulate functions */
701         ret = prepare_emulation(p, &insn);
702         if (ret < 0)
703                 return ret;
704
705         /* Add int3 for single-step or booster jmp */
706         len = prepare_singlestep(buf, p, &insn);
707         if (len < 0)
708                 return len;
709
710         /* Also, displacement change doesn't affect the first byte */
711         p->opcode = buf[0];
712
713         p->ainsn.tp_len = len;
714         perf_event_text_poke(p->ainsn.insn, NULL, 0, buf, len);
715
716         /* OK, write back the instruction(s) into ROX insn buffer */
717         text_poke(p->ainsn.insn, buf, len);
718
719         return 0;
720 }
721
722 int arch_prepare_kprobe(struct kprobe *p)
723 {
724         int ret;
725
726         if (alternatives_text_reserved(p->addr, p->addr))
727                 return -EINVAL;
728
729         if (!can_probe((unsigned long)p->addr))
730                 return -EILSEQ;
731
732         memset(&p->ainsn, 0, sizeof(p->ainsn));
733
734         /* insn: must be on special executable page on x86. */
735         p->ainsn.insn = get_insn_slot();
736         if (!p->ainsn.insn)
737                 return -ENOMEM;
738
739         ret = arch_copy_kprobe(p);
740         if (ret) {
741                 free_insn_slot(p->ainsn.insn, 0);
742                 p->ainsn.insn = NULL;
743         }
744
745         return ret;
746 }
747
748 void arch_arm_kprobe(struct kprobe *p)
749 {
750         u8 int3 = INT3_INSN_OPCODE;
751
752         text_poke(p->addr, &int3, 1);
753         text_poke_sync();
754         perf_event_text_poke(p->addr, &p->opcode, 1, &int3, 1);
755 }
756
757 void arch_disarm_kprobe(struct kprobe *p)
758 {
759         u8 int3 = INT3_INSN_OPCODE;
760
761         perf_event_text_poke(p->addr, &int3, 1, &p->opcode, 1);
762         text_poke(p->addr, &p->opcode, 1);
763         text_poke_sync();
764 }
765
766 void arch_remove_kprobe(struct kprobe *p)
767 {
768         if (p->ainsn.insn) {
769                 /* Record the perf event before freeing the slot */
770                 perf_event_text_poke(p->ainsn.insn, p->ainsn.insn,
771                                      p->ainsn.tp_len, NULL, 0);
772                 free_insn_slot(p->ainsn.insn, p->ainsn.boostable);
773                 p->ainsn.insn = NULL;
774         }
775 }
776
777 static nokprobe_inline void
778 save_previous_kprobe(struct kprobe_ctlblk *kcb)
779 {
780         kcb->prev_kprobe.kp = kprobe_running();
781         kcb->prev_kprobe.status = kcb->kprobe_status;
782         kcb->prev_kprobe.old_flags = kcb->kprobe_old_flags;
783         kcb->prev_kprobe.saved_flags = kcb->kprobe_saved_flags;
784 }
785
786 static nokprobe_inline void
787 restore_previous_kprobe(struct kprobe_ctlblk *kcb)
788 {
789         __this_cpu_write(current_kprobe, kcb->prev_kprobe.kp);
790         kcb->kprobe_status = kcb->prev_kprobe.status;
791         kcb->kprobe_old_flags = kcb->prev_kprobe.old_flags;
792         kcb->kprobe_saved_flags = kcb->prev_kprobe.saved_flags;
793 }
794
795 static nokprobe_inline void
796 set_current_kprobe(struct kprobe *p, struct pt_regs *regs,
797                    struct kprobe_ctlblk *kcb)
798 {
799         __this_cpu_write(current_kprobe, p);
800         kcb->kprobe_saved_flags = kcb->kprobe_old_flags
801                 = (regs->flags & X86_EFLAGS_IF);
802 }
803
804 static void kprobe_post_process(struct kprobe *cur, struct pt_regs *regs,
805                                struct kprobe_ctlblk *kcb)
806 {
807         /* Restore back the original saved kprobes variables and continue. */
808         if (kcb->kprobe_status == KPROBE_REENTER) {
809                 /* This will restore both kcb and current_kprobe */
810                 restore_previous_kprobe(kcb);
811         } else {
812                 /*
813                  * Always update the kcb status because
814                  * reset_curent_kprobe() doesn't update kcb.
815                  */
816                 kcb->kprobe_status = KPROBE_HIT_SSDONE;
817                 if (cur->post_handler)
818                         cur->post_handler(cur, regs, 0);
819                 reset_current_kprobe();
820         }
821 }
822 NOKPROBE_SYMBOL(kprobe_post_process);
823
824 static void setup_singlestep(struct kprobe *p, struct pt_regs *regs,
825                              struct kprobe_ctlblk *kcb, int reenter)
826 {
827         if (setup_detour_execution(p, regs, reenter))
828                 return;
829
830 #if !defined(CONFIG_PREEMPTION)
831         if (p->ainsn.boostable) {
832                 /* Boost up -- we can execute copied instructions directly */
833                 if (!reenter)
834                         reset_current_kprobe();
835                 /*
836                  * Reentering boosted probe doesn't reset current_kprobe,
837                  * nor set current_kprobe, because it doesn't use single
838                  * stepping.
839                  */
840                 regs->ip = (unsigned long)p->ainsn.insn;
841                 return;
842         }
843 #endif
844         if (reenter) {
845                 save_previous_kprobe(kcb);
846                 set_current_kprobe(p, regs, kcb);
847                 kcb->kprobe_status = KPROBE_REENTER;
848         } else
849                 kcb->kprobe_status = KPROBE_HIT_SS;
850
851         if (p->ainsn.emulate_op) {
852                 p->ainsn.emulate_op(p, regs);
853                 kprobe_post_process(p, regs, kcb);
854                 return;
855         }
856
857         /* Disable interrupt, and set ip register on trampoline */
858         regs->flags &= ~X86_EFLAGS_IF;
859         regs->ip = (unsigned long)p->ainsn.insn;
860 }
861 NOKPROBE_SYMBOL(setup_singlestep);
862
863 /*
864  * Called after single-stepping.  p->addr is the address of the
865  * instruction whose first byte has been replaced by the "int3"
866  * instruction.  To avoid the SMP problems that can occur when we
867  * temporarily put back the original opcode to single-step, we
868  * single-stepped a copy of the instruction.  The address of this
869  * copy is p->ainsn.insn. We also doesn't use trap, but "int3" again
870  * right after the copied instruction.
871  * Different from the trap single-step, "int3" single-step can not
872  * handle the instruction which changes the ip register, e.g. jmp,
873  * call, conditional jmp, and the instructions which changes the IF
874  * flags because interrupt must be disabled around the single-stepping.
875  * Such instructions are software emulated, but others are single-stepped
876  * using "int3".
877  *
878  * When the 2nd "int3" handled, the regs->ip and regs->flags needs to
879  * be adjusted, so that we can resume execution on correct code.
880  */
881 static void resume_singlestep(struct kprobe *p, struct pt_regs *regs,
882                               struct kprobe_ctlblk *kcb)
883 {
884         unsigned long copy_ip = (unsigned long)p->ainsn.insn;
885         unsigned long orig_ip = (unsigned long)p->addr;
886
887         /* Restore saved interrupt flag and ip register */
888         regs->flags |= kcb->kprobe_saved_flags;
889         /* Note that regs->ip is executed int3 so must be a step back */
890         regs->ip += (orig_ip - copy_ip) - INT3_INSN_SIZE;
891 }
892 NOKPROBE_SYMBOL(resume_singlestep);
893
894 /*
895  * We have reentered the kprobe_handler(), since another probe was hit while
896  * within the handler. We save the original kprobes variables and just single
897  * step on the instruction of the new probe without calling any user handlers.
898  */
899 static int reenter_kprobe(struct kprobe *p, struct pt_regs *regs,
900                           struct kprobe_ctlblk *kcb)
901 {
902         switch (kcb->kprobe_status) {
903         case KPROBE_HIT_SSDONE:
904         case KPROBE_HIT_ACTIVE:
905         case KPROBE_HIT_SS:
906                 kprobes_inc_nmissed_count(p);
907                 setup_singlestep(p, regs, kcb, 1);
908                 break;
909         case KPROBE_REENTER:
910                 /* A probe has been hit in the codepath leading up to, or just
911                  * after, single-stepping of a probed instruction. This entire
912                  * codepath should strictly reside in .kprobes.text section.
913                  * Raise a BUG or we'll continue in an endless reentering loop
914                  * and eventually a stack overflow.
915                  */
916                 pr_err("Unrecoverable kprobe detected.\n");
917                 dump_kprobe(p);
918                 BUG();
919         default:
920                 /* impossible cases */
921                 WARN_ON(1);
922                 return 0;
923         }
924
925         return 1;
926 }
927 NOKPROBE_SYMBOL(reenter_kprobe);
928
929 static nokprobe_inline int kprobe_is_ss(struct kprobe_ctlblk *kcb)
930 {
931         return (kcb->kprobe_status == KPROBE_HIT_SS ||
932                 kcb->kprobe_status == KPROBE_REENTER);
933 }
934
935 /*
936  * Interrupts are disabled on entry as trap3 is an interrupt gate and they
937  * remain disabled throughout this function.
938  */
939 int kprobe_int3_handler(struct pt_regs *regs)
940 {
941         kprobe_opcode_t *addr;
942         struct kprobe *p;
943         struct kprobe_ctlblk *kcb;
944
945         if (user_mode(regs))
946                 return 0;
947
948         addr = (kprobe_opcode_t *)(regs->ip - sizeof(kprobe_opcode_t));
949         /*
950          * We don't want to be preempted for the entire duration of kprobe
951          * processing. Since int3 and debug trap disables irqs and we clear
952          * IF while singlestepping, it must be no preemptible.
953          */
954
955         kcb = get_kprobe_ctlblk();
956         p = get_kprobe(addr);
957
958         if (p) {
959                 if (kprobe_running()) {
960                         if (reenter_kprobe(p, regs, kcb))
961                                 return 1;
962                 } else {
963                         set_current_kprobe(p, regs, kcb);
964                         kcb->kprobe_status = KPROBE_HIT_ACTIVE;
965
966                         /*
967                          * If we have no pre-handler or it returned 0, we
968                          * continue with normal processing.  If we have a
969                          * pre-handler and it returned non-zero, that means
970                          * user handler setup registers to exit to another
971                          * instruction, we must skip the single stepping.
972                          */
973                         if (!p->pre_handler || !p->pre_handler(p, regs))
974                                 setup_singlestep(p, regs, kcb, 0);
975                         else
976                                 reset_current_kprobe();
977                         return 1;
978                 }
979         } else if (kprobe_is_ss(kcb)) {
980                 p = kprobe_running();
981                 if ((unsigned long)p->ainsn.insn < regs->ip &&
982                     (unsigned long)p->ainsn.insn + MAX_INSN_SIZE > regs->ip) {
983                         /* Most provably this is the second int3 for singlestep */
984                         resume_singlestep(p, regs, kcb);
985                         kprobe_post_process(p, regs, kcb);
986                         return 1;
987                 }
988         }
989
990         if (*addr != INT3_INSN_OPCODE) {
991                 /*
992                  * The breakpoint instruction was removed right
993                  * after we hit it.  Another cpu has removed
994                  * either a probepoint or a debugger breakpoint
995                  * at this address.  In either case, no further
996                  * handling of this interrupt is appropriate.
997                  * Back up over the (now missing) int3 and run
998                  * the original instruction.
999                  */
1000                 regs->ip = (unsigned long)addr;
1001                 return 1;
1002         } /* else: not a kprobe fault; let the kernel handle it */
1003
1004         return 0;
1005 }
1006 NOKPROBE_SYMBOL(kprobe_int3_handler);
1007
1008 int kprobe_fault_handler(struct pt_regs *regs, int trapnr)
1009 {
1010         struct kprobe *cur = kprobe_running();
1011         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
1012
1013         if (unlikely(regs->ip == (unsigned long)cur->ainsn.insn)) {
1014                 /* This must happen on single-stepping */
1015                 WARN_ON(kcb->kprobe_status != KPROBE_HIT_SS &&
1016                         kcb->kprobe_status != KPROBE_REENTER);
1017                 /*
1018                  * We are here because the instruction being single
1019                  * stepped caused a page fault. We reset the current
1020                  * kprobe and the ip points back to the probe address
1021                  * and allow the page fault handler to continue as a
1022                  * normal page fault.
1023                  */
1024                 regs->ip = (unsigned long)cur->addr;
1025
1026                 /*
1027                  * If the IF flag was set before the kprobe hit,
1028                  * don't touch it:
1029                  */
1030                 regs->flags |= kcb->kprobe_old_flags;
1031
1032                 if (kcb->kprobe_status == KPROBE_REENTER)
1033                         restore_previous_kprobe(kcb);
1034                 else
1035                         reset_current_kprobe();
1036         }
1037
1038         return 0;
1039 }
1040 NOKPROBE_SYMBOL(kprobe_fault_handler);
1041
1042 int __init arch_populate_kprobe_blacklist(void)
1043 {
1044         return kprobe_add_area_blacklist((unsigned long)__entry_text_start,
1045                                          (unsigned long)__entry_text_end);
1046 }
1047
1048 int __init arch_init_kprobes(void)
1049 {
1050         return 0;
1051 }
1052
1053 int arch_trampoline_kprobe(struct kprobe *p)
1054 {
1055         return 0;
1056 }