[FIX] kretprobe_trampoline() for x86
[kernel/swap-modules.git] / kprobe / arch / asm-x86 / dbi_kprobes.c
1 /*
2  *  Kernel Probes (KProbes)
3  *  arch/x86/kernel/kprobes.c
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  *
19  * Copyright (C) IBM Corporation, 2002, 2004
20  */
21
22 /*
23  *  Dynamic Binary Instrumentation Module based on KProbes
24  *  modules/kprobe/arch/asm-x86/dbi_kprobes.c
25  *
26  * This program is free software; you can redistribute it and/or modify
27  * it under the terms of the GNU General Public License as published by
28  * the Free Software Foundation; either version 2 of the License, or
29  * (at your option) any later version.
30  *
31  * This program is distributed in the hope that it will be useful,
32  * but WITHOUT ANY WARRANTY; without even the implied warranty of
33  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
34  * GNU General Public License for more details.
35  *
36  * You should have received a copy of the GNU General Public License
37  * along with this program; if not, write to the Free Software
38  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
39  *
40  * Copyright (C) Samsung Electronics, 2006-2010
41  *
42  * 2008-2009    Alexey Gerenkov <a.gerenkov@samsung.com> User-Space
43  *              Probes initial implementation; Support x86/ARM/MIPS for both user and kernel spaces.
44  * 2010         Ekaterina Gorelkina <e.gorelkina@samsung.com>: redesign module for separating core and arch parts
45  * 2012         Stanislav Andreev <s.andreev@samsung.com>: added time debug profiling support; BUG() message fix
46  */
47
48 #include<linux/module.h>
49 #include <linux/kdebug.h>
50
51 #include "dbi_kprobes.h"
52 #include "../dbi_kprobes.h"
53 #include "../../dbi_kprobes.h"
54
55 #include "../../dbi_kdebug.h"
56 #include "../../dbi_insn_slots.h"
57 #include "../../dbi_kprobes_deps.h"
58 #define SUPRESS_BUG_MESSAGES
59
60 extern struct kprobe * per_cpu__current_kprobe;
61
62 extern struct kprobe * per_cpu__current_kprobe;
63
64 extern struct kprobe * current_kprobe;
65
66 #define SAVE_REGS_STRING                \
67         /* Skip cs, ip, orig_ax. */     \
68         "       subq $24, %rsp\n"       \
69         "       pushq %rdi\n"           \
70         "       pushq %rsi\n"           \
71         "       pushq %rdx\n"           \
72         "       pushq %rcx\n"           \
73         "       pushq %rax\n"           \
74         "       pushq %r8\n"            \
75         "       pushq %r9\n"            \
76         "       pushq %r10\n"           \
77         "       pushq %r11\n"           \
78         "       pushq %rbx\n"           \
79         "       pushq %rbp\n"           \
80         "       pushq %r12\n"           \
81         "       pushq %r13\n"           \
82         "       pushq %r14\n"           \
83         "       pushq %r15\n"
84 #define RESTORE_REGS_STRING             \
85         "       popq %r15\n"            \
86         "       popq %r14\n"            \
87         "       popq %r13\n"            \
88         "       popq %r12\n"            \
89         "       popq %rbp\n"            \
90         "       popq %rbx\n"            \
91         "       popq %r11\n"            \
92         "       popq %r10\n"            \
93         "       popq %r9\n"             \
94         "       popq %r8\n"             \
95         "       popq %rax\n"            \
96         "       popq %rcx\n"            \
97         "       popq %rdx\n"            \
98         "       popq %rsi\n"            \
99         "       popq %rdi\n"            \
100         /* Skip orig_ax, ip, cs */      \
101         "       addq $24, %rsp\n"
102
103 DECLARE_MOD_FUNC_DEP(module_alloc, void *, unsigned long size);
104 DECLARE_MOD_FUNC_DEP(module_free, void, struct module *mod, void *module_region);
105 DECLARE_MOD_FUNC_DEP(fixup_exception, int, struct pt_regs * regs);
106
107 DECLARE_MOD_FUNC_DEP(freeze_processes, int, void);
108 DECLARE_MOD_FUNC_DEP(thaw_processes, void, void);
109
110 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26))
111 DECLARE_MOD_FUNC_DEP(text_poke, void, void *addr, unsigned char *opcode, int len);
112 #else
113 DECLARE_MOD_FUNC_DEP(text_poke, void *, void *addr, const void *opcode, size_t len);
114 #endif
115 DECLARE_MOD_FUNC_DEP(show_registers, void, struct pt_regs * regs);
116
117 DECLARE_MOD_DEP_WRAPPER (module_alloc, void *, unsigned long size)
118 IMP_MOD_DEP_WRAPPER (module_alloc, size)
119
120 DECLARE_MOD_DEP_WRAPPER (module_free, void, struct module *mod, void *module_region)
121 IMP_MOD_DEP_WRAPPER (module_free, mod, module_region)
122
123 DECLARE_MOD_DEP_WRAPPER (fixup_exception, int, struct pt_regs * regs)
124 IMP_MOD_DEP_WRAPPER (fixup_exception, regs)
125
126 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26))
127 DECLARE_MOD_DEP_WRAPPER(text_poke, \
128                         void, void *addr, unsigned char *opcode, int len)
129 #else
130 DECLARE_MOD_DEP_WRAPPER(text_poke, \
131                         void *, void *addr, const void *opcode, size_t len)
132 #endif
133 IMP_MOD_DEP_WRAPPER(text_poke, addr, opcode, len)
134
135 DECLARE_MOD_DEP_WRAPPER(show_registers, void, struct pt_regs * regs)
136 IMP_MOD_DEP_WRAPPER(show_registers, regs)
137
138 /*
139  * Function return probe trampoline:
140  *      - init_kprobes() establishes a probepoint here
141  *      - When the probed function returns, this probe
142  *        causes the handlers to fire
143  */
144 static __used void kretprobe_trampoline_holder(void)
145 {
146         asm volatile(".global kretprobe_trampoline\n"
147                         "kretprobe_trampoline:\n"
148                         "       pushf\n"
149                         /* skip cs, ip, orig_ax and gs. */
150                         "       subl $16, %esp\n"
151                         "       pushl %fs\n"
152                         "       pushl %es\n"
153                         "       pushl %ds\n"
154                         "       pushl %eax\n"
155                         "       pushl %ebp\n"
156                         "       pushl %edi\n"
157                         "       pushl %esi\n"
158                         "       pushl %edx\n"
159                         "       pushl %ecx\n"
160                         "       pushl %ebx\n"
161                         "       movl %esp, %eax\n"
162                         "       call trampoline_probe_handler_x86\n"
163                         /* move eflags to cs */
164                         "       movl 56(%esp), %edx\n"
165                         "       movl %edx, 52(%esp)\n"
166                         /* replace saved flags with true return address. */
167                         "       movl %eax, 56(%esp)\n"
168                         "       popl %ebx\n" ""
169                         "       popl %ecx\n"
170                         "       popl %edx\n"
171                         "       popl %esi\n"
172                         "       popl %edi\n"
173                         "       popl %ebp\n"
174                         "       popl %eax\n"
175                         /* skip eip, orig_eax, es, ds, fs */
176                         "       addl $20, %esp\n"
177                         "       popf\n"
178                         "       ret\n");
179 }
180
181 void kretprobe_trampoline(void);
182
183 struct kprobe trampoline_p =
184 {
185         .addr = (kprobe_opcode_t *) & kretprobe_trampoline,
186         .pre_handler = trampoline_probe_handler
187 };
188
189 /* insert a jmp code */
190 static __always_inline void set_jmp_op (void *from, void *to)
191 {
192         struct __arch_jmp_op
193         {
194                 char op;
195                 long raddr;
196         } __attribute__ ((packed)) * jop;
197         jop = (struct __arch_jmp_op *) from;
198         jop->raddr = (long) (to) - ((long) (from) + 5);
199         jop->op = RELATIVEJUMP_INSTRUCTION;
200 }
201
202 static void set_user_jmp_op (void *from, void *to)
203 {
204         struct __arch_jmp_op
205         {
206                 char op;
207                 long raddr;
208         } __attribute__ ((packed)) jop;
209         //jop = (struct __arch_jmp_op *) from;
210         jop.raddr = (long) (to) - ((long) (from) + 5);
211         jop.op = RELATIVEJUMP_INSTRUCTION;
212         if (!write_proc_vm_atomic (current, (unsigned long)from, &jop, sizeof(jop)))
213                 panic ("failed to write jump opcode to user space %p!\n", from);
214 }
215
216 /*
217  * returns non-zero if opcodes can be boosted.
218  */
219 int can_boost(kprobe_opcode_t *opcodes)
220 {
221 #define W(row,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,ba,bb,bc,bd,be,bf)                \
222         (((b0##UL << 0x0)|(b1##UL << 0x1)|(b2##UL << 0x2)|(b3##UL << 0x3) |   \
223           (b4##UL << 0x4)|(b5##UL << 0x5)|(b6##UL << 0x6)|(b7##UL << 0x7) |   \
224           (b8##UL << 0x8)|(b9##UL << 0x9)|(ba##UL << 0xa)|(bb##UL << 0xb) |   \
225           (bc##UL << 0xc)|(bd##UL << 0xd)|(be##UL << 0xe)|(bf##UL << 0xf))    \
226          << (row % 32))
227         /*
228          * Undefined/reserved opcodes, conditional jump, Opcode Extension
229          * Groups, and some special opcodes can not be boost.
230          */
231         static const unsigned long twobyte_is_boostable[256 / 32] = {
232                 /*      0 1 2 3 4 5 6 7 8 9 a b c d e f         */
233                 /*      -------------------------------         */
234                 W (0x00, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0) |      /* 00 */
235                         W (0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),       /* 10 */
236                 W (0x20, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) |      /* 20 */
237                         W (0x30, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),       /* 30 */
238                 W (0x40, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) |      /* 40 */
239                         W (0x50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),       /* 50 */
240                 W (0x60, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1) |      /* 60 */
241                         W (0x70, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1),       /* 70 */
242                 W (0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) |      /* 80 */
243                         W (0x90, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),       /* 90 */
244                 W (0xa0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) |      /* a0 */
245                         W (0xb0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1),       /* b0 */
246                 W (0xc0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1) |      /* c0 */
247                         W (0xd0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1),       /* d0 */
248                 W (0xe0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) |      /* e0 */
249                         W (0xf0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0)        /* f0 */
250                         /*      -------------------------------         */
251                         /*      0 1 2 3 4 5 6 7 8 9 a b c d e f         */
252         };
253 #undef W
254         kprobe_opcode_t opcode;
255         kprobe_opcode_t *orig_opcodes = opcodes;
256 retry:
257         if (opcodes - orig_opcodes > MAX_INSN_SIZE - 1)
258                 return 0;
259         opcode = *(opcodes++);
260
261         /* 2nd-byte opcode */
262         if (opcode == 0x0f)
263         {
264                 if (opcodes - orig_opcodes > MAX_INSN_SIZE - 1)
265                         return 0;
266                 return test_bit (*opcodes, twobyte_is_boostable);
267         }
268
269         switch (opcode & 0xf0)
270         {
271                 case 0x60:
272                         if (0x63 < opcode && opcode < 0x67)
273                                 goto retry;     /* prefixes */
274                         /* can't boost Address-size override and bound */
275                         return (opcode != 0x62 && opcode != 0x67);
276                 case 0x70:
277                         return 0;       /* can't boost conditional jump */
278                 case 0xc0:
279                         /* can't boost software-interruptions */
280                         return (0xc1 < opcode && opcode < 0xcc) || opcode == 0xcf;
281                 case 0xd0:
282                         /* can boost AA* and XLAT */
283                         return (opcode == 0xd4 || opcode == 0xd5 || opcode == 0xd7);
284                 case 0xe0:
285                         /* can boost in/out and absolute jmps */
286                         return ((opcode & 0x04) || opcode == 0xea);
287                 case 0xf0:
288                         if ((opcode & 0x0c) == 0 && opcode != 0xf1)
289                                 goto retry;     /* lock/rep(ne) prefix */
290                         /* clear and set flags can be boost */
291                         return (opcode == 0xf5 || (0xf7 < opcode && opcode < 0xfe));
292                 default:
293                         if (opcode == 0x26 || opcode == 0x36 || opcode == 0x3e)
294                                 goto retry;     /* prefixes */
295                         /* can't boost CS override and call */
296                         return (opcode != 0x2e && opcode != 0x9a);
297         }
298 }
299 EXPORT_SYMBOL_GPL(can_boost);
300
301 /*
302  * returns non-zero if opcode modifies the interrupt flag.
303  */
304 static int is_IF_modifier (kprobe_opcode_t opcode)
305 {
306         switch (opcode)
307         {
308                 case 0xfa:              /* cli */
309                 case 0xfb:              /* sti */
310                 case 0xcf:              /* iret/iretd */
311                 case 0x9d:              /* popf/popfd */
312                         return 1;
313         }
314         return 0;
315 }
316
317 int arch_prepare_kprobe(struct kprobe *p, struct slot_manager *sm)
318 {
319         kprobe_opcode_t insns[KPROBES_TRAMP_LEN];
320
321         int ret = 0;
322
323         if ((unsigned long) p->addr & 0x01)
324         {
325                 DBPRINTF ("Attempt to register kprobe at an unaligned address\n");
326                 //ret = -EINVAL;
327         }
328
329
330         if (!ret)
331         {
332                 kprobe_opcode_t insn[MAX_INSN_SIZE];
333                 struct arch_specific_insn ainsn;
334                 /* insn: must be on special executable page on i386. */
335                 p->ainsn.insn = alloc_insn_slot(sm);
336                 if (!p->ainsn.insn)
337                         return -ENOMEM;
338                 memcpy (insn, p->addr, MAX_INSN_SIZE * sizeof (kprobe_opcode_t));
339                 ainsn.insn = insn;
340                 ret = arch_check_insn (&ainsn);
341                 if (!ret)
342                 {
343                         p->opcode = *p->addr;
344                 }
345
346                 if (can_boost (p->addr))
347                         p->ainsn.boostable = 0;
348                 else
349                         p->ainsn.boostable = -1;
350                 memcpy (p->ainsn.insn, insn, MAX_INSN_SIZE * sizeof (kprobe_opcode_t));
351         }
352         else
353         {
354                 free_insn_slot(sm, p->ainsn.insn);
355         }
356
357         return ret;
358 }
359
360 void prepare_singlestep (struct kprobe *p, struct pt_regs *regs)
361 {
362         if(p->ss_addr)
363         {
364                 regs->EREG (ip) = (unsigned long)p->ss_addr;
365                 p->ss_addr = NULL;
366         }
367         else
368         {
369                 regs->EREG (flags) |= TF_MASK;
370                 regs->EREG (flags) &= ~IF_MASK;
371                 /*single step inline if the instruction is an int3 */
372                 if (p->opcode == BREAKPOINT_INSTRUCTION){
373                         regs->EREG (ip) = (unsigned long) p->addr;
374                         //printk("break_insn!!!\n");
375                 }
376                 else
377                         regs->EREG (ip) = (unsigned long) p->ainsn.insn;
378         }
379 }
380 EXPORT_SYMBOL_GPL(prepare_singlestep);
381
382 void save_previous_kprobe (struct kprobe_ctlblk *kcb, struct kprobe *cur_p)
383 {
384         if (kcb->prev_kprobe.kp != NULL)
385         {
386                 panic("no space to save new probe[]: task = %d/%s, prev %p, current %p, new %p,",
387                                 current->pid, current->comm, kcb->prev_kprobe.kp->addr,
388                                 kprobe_running()->addr, cur_p->addr);
389         }
390
391
392         kcb->prev_kprobe.kp = kprobe_running();
393         kcb->prev_kprobe.status = kcb->kprobe_status;
394
395 }
396
397 void restore_previous_kprobe (struct kprobe_ctlblk *kcb)
398 {
399         __get_cpu_var (current_kprobe) = kcb->prev_kprobe.kp;
400         kcb->kprobe_status = kcb->prev_kprobe.status;
401         kcb->prev_kprobe.kp = NULL;
402         kcb->prev_kprobe.status = 0;
403 }
404
405 void set_current_kprobe (struct kprobe *p, struct pt_regs *regs, struct kprobe_ctlblk *kcb)
406 {
407         __get_cpu_var (current_kprobe) = p;
408         DBPRINTF ("set_current_kprobe[]: p=%p addr=%p\n", p, p->addr);
409         kcb->kprobe_saved_eflags = kcb->kprobe_old_eflags = (regs->EREG (flags) & (TF_MASK | IF_MASK));
410         if (is_IF_modifier (p->opcode))
411                 kcb->kprobe_saved_eflags &= ~IF_MASK;
412 }
413
414 int kprobe_handler (struct pt_regs *regs)
415 {
416         struct kprobe *p = 0;
417         int ret = 0, reenter = 0;
418         kprobe_opcode_t *addr = NULL;
419         struct kprobe_ctlblk *kcb;
420 #ifdef SUPRESS_BUG_MESSAGES
421         int swap_oops_in_progress;
422 #endif
423
424         /* We're in an interrupt, but this is clear and BUG()-safe. */
425         addr = (kprobe_opcode_t *) (regs->EREG (ip) - sizeof (kprobe_opcode_t));
426         DBPRINTF ("KPROBE: regs->eip = 0x%lx addr = 0x%p\n", regs->EREG (ip), addr);
427 #ifdef SUPRESS_BUG_MESSAGES
428         // oops_in_progress used to avoid BUG() messages that slow down kprobe_handler() execution
429         swap_oops_in_progress = oops_in_progress;
430         oops_in_progress = 1;
431 #endif
432         preempt_disable ();
433
434         kcb = get_kprobe_ctlblk ();
435
436         /* Check we're not actually recursing */
437         if (kprobe_running()) {
438                 p = get_kprobe(addr);
439                 if (p) {
440                         if (kcb->kprobe_status == KPROBE_HIT_SS && *p->ainsn.insn == BREAKPOINT_INSTRUCTION) {
441                                 regs->EREG(flags) &= ~TF_MASK;
442                                 regs->EREG(flags) |= kcb->kprobe_saved_eflags;
443                                 goto no_kprobe;
444                         }
445
446
447                         /* We have reentered the kprobe_handler(), since
448                          * another probe was hit while within the handler.
449                          * We here save the original kprobes variables and
450                          * just single step on the instruction of the new probe
451                          * without calling any user handlers.
452                          */
453                         save_previous_kprobe (kcb, p);
454                         set_current_kprobe (p, regs, kcb);
455                         kprobes_inc_nmissed_count (p);
456                         prepare_singlestep (p, regs);
457                         kcb->kprobe_status = KPROBE_REENTER;
458                         // FIXME should we enable preemption here??...
459                         //preempt_enable_no_resched ();
460 #ifdef SUPRESS_BUG_MESSAGES
461                         oops_in_progress = swap_oops_in_progress;
462 #endif
463                         return 1;
464                 } else {
465                         if (*addr != BREAKPOINT_INSTRUCTION) {
466                                 /* The breakpoint instruction was removed by
467                                  * another cpu right after we hit, no further
468                                  * handling of this interrupt is appropriate
469                                  */
470                                 regs->EREG(ip) -= sizeof(kprobe_opcode_t);
471                                 ret = 1;
472                                 goto no_kprobe;
473                         }
474
475                         p = __get_cpu_var(current_kprobe);
476                         if (p->break_handler && p->break_handler(p, regs))
477                                 goto ss_probe;
478
479                         goto no_kprobe;
480                 }
481         }
482
483         DBPRINTF ("get_kprobe %p", addr);
484         if (!p)
485                 p = get_kprobe(addr);
486
487         if (!p) {
488                 if (*addr != BREAKPOINT_INSTRUCTION) {
489                         /*
490                          * The breakpoint instruction was removed right
491                          * after we hit it.  Another cpu has removed
492                          * either a probepoint or a debugger breakpoint
493                          * at this address.  In either case, no further
494                          * handling of this interrupt is appropriate.
495                          * Back up over the (now missing) int3 and run
496                          * the original instruction.
497                          */
498                         regs->EREG(ip) -= sizeof(kprobe_opcode_t);
499                         ret = 1;
500                 }
501
502                 if (!p) {
503                         /* Not one of ours: let kernel handle it */
504                         DBPRINTF ("no_kprobe");
505                         goto no_kprobe;
506                 }
507         }
508
509         set_current_kprobe (p, regs, kcb);
510
511         if(!reenter)
512                 kcb->kprobe_status = KPROBE_HIT_ACTIVE;
513
514         if (p->pre_handler)
515                 ret = p->pre_handler(p, regs);
516
517         if (ret)
518         {
519                 if (ret == 2) { // we have alreadyc called the handler, so just single step the instruction
520                         DBPRINTF ("p->pre_handler[] 2");
521                         goto ss_probe;
522                 }
523                 DBPRINTF ("p->pre_handler[] 1");
524                 // FIXME should we enable preemption here??...
525                 //preempt_enable_no_resched ();
526 #ifdef SUPRESS_BUG_MESSAGES
527                 oops_in_progress = swap_oops_in_progress;
528 #endif
529                 /* handler has already set things up, so skip ss setup */
530                 prepare_singlestep(p, regs);
531                 return 1;
532         }
533         DBPRINTF ("p->pre_handler[] 0");
534
535 ss_probe:
536         DBPRINTF ("p = %p\n", p);
537         DBPRINTF ("p->opcode = 0x%lx *p->addr = 0x%lx p->addr = 0x%p\n", (unsigned long) p->opcode, p->tgid ? 0 : (unsigned long) (*p->addr), p->addr);
538
539 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PM)
540         if (p->ainsn.boostable == 1 && !p->post_handler)
541         {
542                 /* Boost up -- we can execute copied instructions directly */
543                 reset_current_kprobe ();
544                 regs->EREG (ip) = (unsigned long) p->ainsn.insn;
545                 preempt_enable_no_resched ();
546 #ifdef SUPRESS_BUG_MESSAGES
547                 oops_in_progress = swap_oops_in_progress;
548 #endif
549                 return 1;
550         }
551 #endif // !CONFIG_PREEMPT
552         prepare_singlestep (p, regs);
553         kcb->kprobe_status = KPROBE_HIT_SS;
554         // FIXME should we enable preemption here??...
555         //preempt_enable_no_resched ();
556 #ifdef SUPRESS_BUG_MESSAGES
557         oops_in_progress = swap_oops_in_progress;
558 #endif
559         return 1;
560
561 no_kprobe:
562
563         preempt_enable_no_resched ();
564 #ifdef SUPRESS_BUG_MESSAGES
565         oops_in_progress = swap_oops_in_progress;
566 #endif
567         return ret;
568 }
569
570 int setjmp_pre_handler (struct kprobe *p, struct pt_regs *regs)
571 {
572         struct jprobe *jp = container_of (p, struct jprobe, kp);
573         kprobe_pre_entry_handler_t pre_entry;
574         entry_point_t entry;
575
576         unsigned long addr, args[6];
577         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
578
579         DBPRINTF ("setjmp_pre_handler %p:%d", p->addr, p->tgid);
580         pre_entry = (kprobe_pre_entry_handler_t) jp->pre_entry;
581         entry = (entry_point_t) jp->entry;
582
583         /* handle __switch_to probe */
584         if ((p->addr == sched_addr) && sched_rp) {
585                 /* FIXME: Actually 2nd parameter is not used for x86 */
586                 patch_suspended_task(sched_rp, (struct task_struct *)regs->dx, regs);
587         }
588
589         kcb->jprobe_saved_regs = *regs;
590         kcb->jprobe_saved_esp = &regs->EREG(sp);
591         addr = (unsigned long)(kcb->jprobe_saved_esp);
592
593         /* TBD: As Linus pointed out, gcc assumes that the callee
594          * owns the argument space and could overwrite it, e.g.
595          * tailcall optimization. So, to be absolutely safe
596          * we also save and restore enough stack bytes to cover
597          * the argument area. */
598         memcpy(kcb->jprobes_stack, (kprobe_opcode_t *)addr, MIN_STACK_SIZE (addr));
599         regs->EREG(flags) &= ~IF_MASK;
600 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 18)
601         trace_hardirqs_off();
602 #endif
603         if (pre_entry)
604                 p->ss_addr = pre_entry(jp->priv_arg, regs);
605
606         regs->EREG(ip) = (unsigned long)(jp->entry);
607
608         return 1;
609 }
610
611 void dbi_jprobe_return (void)
612 {
613         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
614
615         asm volatile("       xchgl   %%ebx,%%esp     \n"
616                         "       int3                    \n"
617                         "       .globl dbi_jprobe_return_end    \n"
618                         "       dbi_jprobe_return_end:  \n"
619                         "       nop                     \n"::"b" (kcb->jprobe_saved_esp):"memory");
620 }
621
622 void arch_ujprobe_return(void)
623 {
624 }
625
626 /*
627  * Called after single-stepping.  p->addr is the address of the
628  * instruction whose first byte has been replaced by the "int 3"
629  * instruction.  To avoid the SMP problems that can occur when we
630  * temporarily put back the original opcode to single-step, we
631  * single-stepped a copy of the instruction.  The address of this
632  * copy is p->ainsn.insn.
633  *
634  * This function prepares to return from the post-single-step
635  * interrupt.  We have to fix up the stack as follows:
636  *
637  * 0) Except in the case of absolute or indirect jump or call instructions,
638  * the new eip is relative to the copied instruction.  We need to make
639  * it relative to the original instruction.
640  *
641  * 1) If the single-stepped instruction was pushfl, then the TF and IF
642  * flags are set in the just-pushed eflags, and may need to be cleared.
643  *
644  * 2) If the single-stepped instruction was a call, the return address
645  * that is atop the stack is the address following the copied instruction.
646  * We need to make it the address following the original instruction.
647  *
648  * This function also checks instruction size for preparing direct execution.
649  */
650 static void resume_execution (struct kprobe *p, struct pt_regs *regs, struct kprobe_ctlblk *kcb)
651 {
652         unsigned long *tos, tos_dword = 0;
653         unsigned long copy_eip = (unsigned long) p->ainsn.insn;
654         unsigned long orig_eip = (unsigned long) p->addr;
655         kprobe_opcode_t insns[2];
656
657         regs->EREG (flags) &= ~TF_MASK;
658
659         tos = (unsigned long *)&regs->EREG(sp);
660         insns[0] = p->ainsn.insn[0];
661         insns[1] = p->ainsn.insn[1];
662
663         switch (insns[0])
664         {
665                 case 0x9c:              /* pushfl */
666                         *tos &= ~(TF_MASK | IF_MASK);
667                         *tos |= kcb->kprobe_old_eflags;
668                         break;
669                 case 0xc2:              /* iret/ret/lret */
670                 case 0xc3:
671                 case 0xca:
672                 case 0xcb:
673                 case 0xcf:
674                 case 0xea:              /* jmp absolute -- eip is correct */
675                         /* eip is already adjusted, no more changes required */
676                         p->ainsn.boostable = 1;
677                         goto no_change;
678                 case 0xe8:              /* call relative - Fix return addr */
679                         *tos = orig_eip + (*tos - copy_eip);
680                         break;
681                 case 0x9a:              /* call absolute -- same as call absolute, indirect */
682                         *tos = orig_eip + (*tos - copy_eip);
683                         goto no_change;
684                 case 0xff:
685                         if ((insns[1] & 0x30) == 0x10)
686                         {
687                                 /*
688                                  * call absolute, indirect
689                                  * Fix return addr; eip is correct.
690                                  * But this is not boostable
691                                  */
692                                 *tos = orig_eip + (*tos - copy_eip);
693                                 goto no_change;
694                         }
695                         else if (((insns[1] & 0x31) == 0x20) || /* jmp near, absolute indirect */
696                                         ((insns[1] & 0x31) == 0x21))
697                         {               /* jmp far, absolute indirect */
698                                 /* eip is correct. And this is boostable */
699                                 p->ainsn.boostable = 1;
700                                 goto no_change;
701                         }
702                 default:
703                         break;
704         }
705
706         if (p->ainsn.boostable == 0)
707         {
708                 if ((regs->EREG (ip) > copy_eip) && (regs->EREG (ip) - copy_eip) + 5 < MAX_INSN_SIZE)
709                 {
710                         /*
711                          * These instructions can be executed directly if it
712                          * jumps back to correct address.
713                          */
714                         set_jmp_op((void *)regs->EREG(ip), (void *)orig_eip + (regs->EREG(ip) - copy_eip));
715                         p->ainsn.boostable = 1;
716                 }
717                 else
718                 {
719                         p->ainsn.boostable = -1;
720                 }
721         }
722
723         regs->EREG (ip) = orig_eip + (regs->EREG (ip) - copy_eip);
724
725 no_change:
726         return;
727 }
728
729 /*
730  * Interrupts are disabled on entry as trap1 is an interrupt gate and they
731  * remain disabled thoroughout this function.
732  */
733 static int post_kprobe_handler (struct pt_regs *regs)
734 {
735         struct kprobe *cur = kprobe_running ();
736         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
737
738         if (!cur)
739                 return 0;
740         if ((kcb->kprobe_status != KPROBE_REENTER) && cur->post_handler)
741         {
742                 kcb->kprobe_status = KPROBE_HIT_SSDONE;
743                 cur->post_handler (cur, regs, 0);
744         }
745
746         resume_execution (cur, regs, kcb);
747         regs->EREG (flags) |= kcb->kprobe_saved_eflags;
748 #ifndef CONFIG_X86
749         trace_hardirqs_fixup_flags (regs->EREG (flags));
750 #endif // CONFIG_X86
751         /*Restore back the original saved kprobes variables and continue. */
752         if (kcb->kprobe_status == KPROBE_REENTER)
753         {
754                 restore_previous_kprobe (kcb);
755                 goto out;
756         }
757         reset_current_kprobe ();
758 out:
759         preempt_enable_no_resched ();
760
761         /*
762          * if somebody else is singlestepping across a probe point, eflags
763          * will have TF set, in which case, continue the remaining processing
764          * of do_debug, as if this is not a probe hit.
765          */
766         if (regs->EREG (flags) & TF_MASK)
767                 return 0;
768
769         return 1;
770 }
771
772 int kprobe_fault_handler (struct pt_regs *regs, int trapnr)
773 {
774         struct kprobe *cur = kprobe_running ();
775         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
776
777         switch (kcb->kprobe_status)
778         {
779                 case KPROBE_HIT_SS:
780                 case KPROBE_REENTER:
781                         /*
782                          * We are here because the instruction being single
783                          * stepped caused a page fault. We reset the current
784                          * kprobe and the eip points back to the probe address
785                          * and allow the page fault handler to continue as a
786                          * normal page fault.
787                          */
788                         regs->EREG (ip) = (unsigned long) cur->addr;
789                         regs->EREG (flags) |= kcb->kprobe_old_eflags;
790                         if (kcb->kprobe_status == KPROBE_REENTER)
791                                 restore_previous_kprobe (kcb);
792                         else
793                                 reset_current_kprobe ();
794                         preempt_enable_no_resched ();
795                         break;
796                 case KPROBE_HIT_ACTIVE:
797                 case KPROBE_HIT_SSDONE:
798                         /*
799                          * We increment the nmissed count for accounting,
800                          * we can also use npre/npostfault count for accouting
801                          * these specific fault cases.
802                          */
803                         kprobes_inc_nmissed_count (cur);
804
805                         /*
806                          * We come here because instructions in the pre/post
807                          * handler caused the page_fault, this could happen
808                          * if handler tries to access user space by
809                          * copy_from_user(), get_user() etc. Let the
810                          * user-specified handler try to fix it first.
811                          */
812                         if (cur->fault_handler && cur->fault_handler (cur, regs, trapnr))
813                                 return 1;
814
815                         /*
816                          * In case the user-specified fault handler returned
817                          * zero, try to fix up.
818                          */
819                         if (fixup_exception (regs))
820                                 return 1;
821
822                         /*
823                          * fixup_exception() could not handle it,
824                          * Let do_page_fault() fix it.
825                          */
826                         break;
827                 default:
828                         break;
829         }
830         return 0;
831 }
832
833 int kprobe_exceptions_notify (struct notifier_block *self, unsigned long val, void *data)
834 {
835         struct die_args *args = (struct die_args *) data;
836         int ret = NOTIFY_DONE;
837
838         DBPRINTF ("val = %ld, data = 0x%X", val, (unsigned int) data);
839
840         if (args->regs && user_mode_vm(args->regs))
841                 return ret;
842
843         DBPRINTF ("switch (val) %lu %d %d", val, DIE_INT3, DIE_TRAP);
844         switch (val)
845         {
846 #ifdef CONFIG_KPROBES
847                 case DIE_INT3:
848 #else
849                 case DIE_TRAP:
850 #endif
851                         DBPRINTF ("before kprobe_handler ret=%d %p", ret, args->regs);
852                         if (kprobe_handler (args->regs))
853                                 ret = NOTIFY_STOP;
854                         DBPRINTF ("after kprobe_handler ret=%d %p", ret, args->regs);
855                         break;
856                 case DIE_DEBUG:
857                         if (post_kprobe_handler (args->regs))
858                                 ret = NOTIFY_STOP;
859                         break;
860                 case DIE_GPF:
861                         // kprobe_running() needs smp_processor_id()
862                         preempt_disable ();
863                         if (kprobe_running () && kprobe_fault_handler (args->regs, args->trapnr))
864                                 ret = NOTIFY_STOP;
865                         preempt_enable ();
866                         break;
867                 default:
868                         break;
869         }
870         DBPRINTF ("ret=%d", ret);
871         /* if(ret == NOTIFY_STOP) */
872         /*      handled_exceptions++; */
873
874         return ret;
875 }
876
877 static struct notifier_block kprobe_exceptions_nb = {
878         .notifier_call = kprobe_exceptions_notify,
879         .priority = INT_MAX
880 };
881
882 int longjmp_break_handler (struct kprobe *p, struct pt_regs *regs)
883 {
884         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
885         u8 *addr = (u8 *) (regs->EREG (ip) - 1);
886         unsigned long stack_addr = (unsigned long) (kcb->jprobe_saved_esp);
887         struct jprobe *jp = container_of (p, struct jprobe, kp);
888
889         DBPRINTF ("p = %p\n", p);
890
891         if ((addr > (u8 *) dbi_jprobe_return) && (addr < (u8 *) dbi_jprobe_return_end))
892         {
893                 if ((unsigned long *)(&regs->EREG(sp)) != kcb->jprobe_saved_esp)
894                 {
895                         struct pt_regs *saved_regs = &kcb->jprobe_saved_regs;
896                         printk ("current esp %p does not match saved esp %p\n", &regs->EREG (sp), kcb->jprobe_saved_esp);
897                         printk ("Saved registers for jprobe %p\n", jp);
898                         show_registers (saved_regs);
899                         printk ("Current registers\n");
900                         show_registers (regs);
901                         panic("BUG");
902                         //BUG ();
903                 }
904                 *regs = kcb->jprobe_saved_regs;
905                 memcpy ((kprobe_opcode_t *) stack_addr, kcb->jprobes_stack, MIN_STACK_SIZE (stack_addr));
906                 preempt_enable_no_resched ();
907                 return 1;
908         }
909 }
910
911 void arch_arm_kprobe (struct kprobe *p)
912 {
913         text_poke (p->addr, ((unsigned char[])
914                                 {BREAKPOINT_INSTRUCTION}), 1);
915 }
916
917 void arch_disarm_kprobe (struct kprobe *p)
918 {
919         text_poke (p->addr, &p->opcode, 1);
920 }
921
922 static __used void *trampoline_probe_handler_x86(struct pt_regs *regs)
923 {
924         return (void *)trampoline_probe_handler(NULL, regs);
925 }
926
927 void arch_prepare_kretprobe(struct kretprobe_instance *ri, struct pt_regs *regs)
928 {
929         unsigned long *sara = (unsigned long *)&regs->EREG(sp);
930         ri->ret_addr = (kprobe_opcode_t *)*sara;
931         ri->sp = &regs->EREG(sp);
932
933         /* Replace the return addr with trampoline addr */
934         *sara = (unsigned long)&kretprobe_trampoline;
935 }
936
937 int arch_init_module_deps()
938 {
939         INIT_MOD_DEP_VAR(module_alloc, module_alloc);
940         INIT_MOD_DEP_VAR(module_free, module_free);
941         INIT_MOD_DEP_VAR(fixup_exception, fixup_exception);
942 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 23)
943 # error this kernel version has no text_poke function which is necessaryf for x86 ach!!!
944 #else
945         INIT_MOD_DEP_VAR(text_poke, text_poke);
946 #endif
947         INIT_MOD_DEP_VAR(show_registers, show_registers);
948 #if defined(CONFIG_PREEMPT) && defined(CONFIG_PM)
949         INIT_MOD_DEP_VAR(freeze_processes, freeze_processes);
950         INIT_MOD_DEP_VAR(thaw_processes, thaw_processes);
951 #endif
952
953         return 0;
954 }
955
956 int arch_init_kprobes(void)
957 {
958         return register_die_notifier (&kprobe_exceptions_nb);
959 }
960
961 void arch_exit_kprobes(void)
962 {
963         unregister_die_notifier (&kprobe_exceptions_nb);
964 }