14dc364a6b9fc72917bbc58fccb832a584002f1f
[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 #include "../../dbi_uprobes.h"
59
60 #ifdef OVERHEAD_DEBUG
61 #include <linux/time.h>
62 #endif
63
64 #define SUPRESS_BUG_MESSAGES
65
66 extern unsigned long sched_addr;
67 extern unsigned long exit_addr;
68 extern unsigned long fork_addr;
69
70 extern struct kprobe * per_cpu__current_kprobe;
71
72 extern struct kprobe * per_cpu__current_kprobe;
73 extern spinlock_t kretprobe_lock;
74 extern struct kretprobe *sched_rp;
75
76 extern struct hlist_head kprobe_insn_pages;
77 extern struct hlist_head uprobe_insn_pages;
78
79 extern spinlock_t kretprobe_lock;
80
81 extern unsigned long (*kallsyms_search) (const char *name);
82
83 extern struct kprobe *kprobe_running (void);
84 extern struct kprobe_ctlblk *get_kprobe_ctlblk (void);
85 extern void reset_current_kprobe (void);
86 extern struct kprobe * current_kprobe;
87
88 #ifdef OVERHEAD_DEBUG
89 unsigned long swap_sum_time = 0;
90 unsigned long swap_sum_hit = 0;
91 EXPORT_SYMBOL_GPL (swap_sum_time);
92 EXPORT_SYMBOL_GPL (swap_sum_hit);
93 #endif
94
95 #define SAVE_REGS_STRING                \
96         /* Skip cs, ip, orig_ax. */     \
97         "       subq $24, %rsp\n"       \
98         "       pushq %rdi\n"           \
99         "       pushq %rsi\n"           \
100         "       pushq %rdx\n"           \
101         "       pushq %rcx\n"           \
102         "       pushq %rax\n"           \
103         "       pushq %r8\n"            \
104         "       pushq %r9\n"            \
105         "       pushq %r10\n"           \
106         "       pushq %r11\n"           \
107         "       pushq %rbx\n"           \
108         "       pushq %rbp\n"           \
109         "       pushq %r12\n"           \
110         "       pushq %r13\n"           \
111         "       pushq %r14\n"           \
112         "       pushq %r15\n"
113 #define RESTORE_REGS_STRING             \
114         "       popq %r15\n"            \
115         "       popq %r14\n"            \
116         "       popq %r13\n"            \
117         "       popq %r12\n"            \
118         "       popq %rbp\n"            \
119         "       popq %rbx\n"            \
120         "       popq %r11\n"            \
121         "       popq %r10\n"            \
122         "       popq %r9\n"             \
123         "       popq %r8\n"             \
124         "       popq %rax\n"            \
125         "       popq %rcx\n"            \
126         "       popq %rdx\n"            \
127         "       popq %rsi\n"            \
128         "       popq %rdi\n"            \
129         /* Skip orig_ax, ip, cs */      \
130         "       addq $24, %rsp\n"
131
132 DECLARE_MOD_FUNC_DEP(module_alloc, void *, unsigned long size);
133 DECLARE_MOD_FUNC_DEP(module_free, void, struct module *mod, void *module_region);
134 DECLARE_MOD_FUNC_DEP(fixup_exception, int, struct pt_regs * regs);
135
136 DECLARE_MOD_FUNC_DEP(freeze_processes, int, void);
137 DECLARE_MOD_FUNC_DEP(thaw_processes, void, void);
138
139 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26))
140 DECLARE_MOD_FUNC_DEP(text_poke, void, void *addr, unsigned char *opcode, int len);
141 #else
142 DECLARE_MOD_FUNC_DEP(text_poke, void *, void *addr, const void *opcode, size_t len);
143 #endif
144 DECLARE_MOD_FUNC_DEP(show_registers, void, struct pt_regs * regs);
145
146 DECLARE_MOD_DEP_WRAPPER (module_alloc, void *, unsigned long size)
147 IMP_MOD_DEP_WRAPPER (module_alloc, size)
148
149 DECLARE_MOD_DEP_WRAPPER (module_free, void, struct module *mod, void *module_region)
150 IMP_MOD_DEP_WRAPPER (module_free, mod, module_region)
151
152 DECLARE_MOD_DEP_WRAPPER (fixup_exception, int, struct pt_regs * regs)
153 IMP_MOD_DEP_WRAPPER (fixup_exception, regs)
154
155 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26))
156 DECLARE_MOD_DEP_WRAPPER(text_poke, \
157                         void, void *addr, unsigned char *opcode, int len)
158 #else
159 DECLARE_MOD_DEP_WRAPPER(text_poke, \
160                         void *, void *addr, const void *opcode, size_t len)
161 #endif
162 IMP_MOD_DEP_WRAPPER(text_poke, addr, opcode, len)
163
164 DECLARE_MOD_DEP_WRAPPER(show_registers, void, struct pt_regs * regs)
165 IMP_MOD_DEP_WRAPPER(show_registers, regs)
166
167 /*
168  * Function return probe trampoline:
169  *      - init_kprobes() establishes a probepoint here
170  *      - When the probed function returns, this probe
171  *              causes the handlers to fire
172  */
173 void kretprobe_trampoline_holder (void)
174 {
175         asm volatile (".global kretprobe_trampoline\n"
176                         "kretprobe_trampoline:\n"
177                         "       pushf\n"
178                         /* skip cs, eip, orig_eax */
179                         "       subl $12, %esp\n"
180                         "       pushl %fs\n"
181                         "       pushl %ds\n"
182                         "       pushl %es\n"
183                         "       pushl %eax\n"
184                         "       pushl %ebp\n"
185                         "       pushl %edi\n"
186                         "       pushl %esi\n"
187                         "       pushl %edx\n"
188                         "       pushl %ecx\n"
189                         "       pushl %ebx\n"
190                         "       movl %esp, %eax\n"
191                         "       call trampoline_probe_handler_x86\n"
192                         /* move eflags to cs */
193                         "       movl 52(%esp), %edx\n"
194                         "       movl %edx, 48(%esp)\n"
195                         /* save true return address on eflags */
196                         "       movl %eax, 52(%esp)\n"
197                         "       popl %ebx\n" ""
198                         "       popl %ecx\n"
199                         "       popl %edx\n"
200                         "       popl %esi\n"
201                         "       popl %edi\n"
202                         "       popl %ebp\n"
203                         "       popl %eax\n"
204                         /* skip eip, orig_eax, es, ds, fs */
205                         "       addl $20, %esp\n"
206                         "       popf\n"
207
208                         "       ret\n");
209 }
210
211
212 struct kprobe trampoline_p =
213 {
214         .addr = (kprobe_opcode_t *) & kretprobe_trampoline,
215         .pre_handler = trampoline_probe_handler
216 };
217
218 /* insert a jmp code */
219 static __always_inline void set_jmp_op (void *from, void *to)
220 {
221         struct __arch_jmp_op
222         {
223                 char op;
224                 long raddr;
225         } __attribute__ ((packed)) * jop;
226         jop = (struct __arch_jmp_op *) from;
227         jop->raddr = (long) (to) - ((long) (from) + 5);
228         jop->op = RELATIVEJUMP_INSTRUCTION;
229 }
230
231 static void set_user_jmp_op (void *from, void *to)
232 {
233         struct __arch_jmp_op
234         {
235                 char op;
236                 long raddr;
237         } __attribute__ ((packed)) jop;
238         //jop = (struct __arch_jmp_op *) from;
239         jop.raddr = (long) (to) - ((long) (from) + 5);
240         jop.op = RELATIVEJUMP_INSTRUCTION;
241         if (!write_proc_vm_atomic (current, (unsigned long)from, &jop, sizeof(jop)))
242                 panic ("failed to write jump opcode to user space %p!\n", from);
243 }
244
245 /*
246  * returns non-zero if opcodes can be boosted.
247  */
248 static __always_inline int can_boost (kprobe_opcode_t * opcodes)
249 {
250 #define W(row,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,ba,bb,bc,bd,be,bf)                \
251         (((b0##UL << 0x0)|(b1##UL << 0x1)|(b2##UL << 0x2)|(b3##UL << 0x3) |   \
252           (b4##UL << 0x4)|(b5##UL << 0x5)|(b6##UL << 0x6)|(b7##UL << 0x7) |   \
253           (b8##UL << 0x8)|(b9##UL << 0x9)|(ba##UL << 0xa)|(bb##UL << 0xb) |   \
254           (bc##UL << 0xc)|(bd##UL << 0xd)|(be##UL << 0xe)|(bf##UL << 0xf))    \
255          << (row % 32))
256         /*
257          * Undefined/reserved opcodes, conditional jump, Opcode Extension
258          * Groups, and some special opcodes can not be boost.
259          */
260         static const unsigned long twobyte_is_boostable[256 / 32] = {
261                 /*      0 1 2 3 4 5 6 7 8 9 a b c d e f         */
262                 /*      -------------------------------         */
263                 W (0x00, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0) |      /* 00 */
264                         W (0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),       /* 10 */
265                 W (0x20, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) |      /* 20 */
266                         W (0x30, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),       /* 30 */
267                 W (0x40, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) |      /* 40 */
268                         W (0x50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),       /* 50 */
269                 W (0x60, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1) |      /* 60 */
270                         W (0x70, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1),       /* 70 */
271                 W (0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) |      /* 80 */
272                         W (0x90, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),       /* 90 */
273                 W (0xa0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) |      /* a0 */
274                         W (0xb0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1),       /* b0 */
275                 W (0xc0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1) |      /* c0 */
276                         W (0xd0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1),       /* d0 */
277                 W (0xe0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) |      /* e0 */
278                         W (0xf0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0)        /* f0 */
279                         /*      -------------------------------         */
280                         /*      0 1 2 3 4 5 6 7 8 9 a b c d e f         */
281         };
282 #undef W
283         kprobe_opcode_t opcode;
284         kprobe_opcode_t *orig_opcodes = opcodes;
285 retry:
286         if (opcodes - orig_opcodes > MAX_INSN_SIZE - 1)
287                 return 0;
288         opcode = *(opcodes++);
289
290         /* 2nd-byte opcode */
291         if (opcode == 0x0f)
292         {
293                 if (opcodes - orig_opcodes > MAX_INSN_SIZE - 1)
294                         return 0;
295                 return test_bit (*opcodes, twobyte_is_boostable);
296         }
297
298         switch (opcode & 0xf0)
299         {
300                 case 0x60:
301                         if (0x63 < opcode && opcode < 0x67)
302                                 goto retry;     /* prefixes */
303                         /* can't boost Address-size override and bound */
304                         return (opcode != 0x62 && opcode != 0x67);
305                 case 0x70:
306                         return 0;       /* can't boost conditional jump */
307                 case 0xc0:
308                         /* can't boost software-interruptions */
309                         return (0xc1 < opcode && opcode < 0xcc) || opcode == 0xcf;
310                 case 0xd0:
311                         /* can boost AA* and XLAT */
312                         return (opcode == 0xd4 || opcode == 0xd5 || opcode == 0xd7);
313                 case 0xe0:
314                         /* can boost in/out and absolute jmps */
315                         return ((opcode & 0x04) || opcode == 0xea);
316                 case 0xf0:
317                         if ((opcode & 0x0c) == 0 && opcode != 0xf1)
318                                 goto retry;     /* lock/rep(ne) prefix */
319                         /* clear and set flags can be boost */
320                         return (opcode == 0xf5 || (0xf7 < opcode && opcode < 0xfe));
321                 default:
322                         if (opcode == 0x26 || opcode == 0x36 || opcode == 0x3e)
323                                 goto retry;     /* prefixes */
324                         /* can't boost CS override and call */
325                         return (opcode != 0x2e && opcode != 0x9a);
326         }
327 }
328
329 /*
330  * returns non-zero if opcode modifies the interrupt flag.
331  */
332 static int is_IF_modifier (kprobe_opcode_t opcode)
333 {
334         switch (opcode)
335         {
336                 case 0xfa:              /* cli */
337                 case 0xfb:              /* sti */
338                 case 0xcf:              /* iret/iretd */
339                 case 0x9d:              /* popf/popfd */
340                         return 1;
341         }
342         return 0;
343 }
344
345 int arch_check_insn (struct arch_specific_insn *ainsn)
346 {
347         DBPRINTF("Warrning: arch_check_insn is not implemented for x86\n");
348         return 0;
349 }
350
351 int arch_prepare_kretprobe (struct kretprobe *p)
352 {
353         DBPRINTF("Warrning: arch_prepare_kretprobe is not implemented\n");
354         return 0;
355 }
356
357
358 int arch_prepare_kprobe (struct kprobe *p)
359 {
360         kprobe_opcode_t insns[KPROBES_TRAMP_LEN];
361
362         int ret = 0;
363
364         if ((unsigned long) p->addr & 0x01)
365         {
366                 DBPRINTF ("Attempt to register kprobe at an unaligned address\n");
367                 //ret = -EINVAL;
368         }
369
370
371         if (!ret)
372         {
373                 kprobe_opcode_t insn[MAX_INSN_SIZE];
374                 struct arch_specific_insn ainsn;
375                 /* insn: must be on special executable page on i386. */
376                 p->ainsn.insn = get_insn_slot (NULL, 0);
377                 if (!p->ainsn.insn)
378                         return -ENOMEM;
379                 memcpy (insn, p->addr, MAX_INSN_SIZE * sizeof (kprobe_opcode_t));
380                 ainsn.insn = insn;
381                 ret = arch_check_insn (&ainsn);
382                 if (!ret)
383                 {
384                         p->opcode = *p->addr;
385                 }
386
387                 if (can_boost (p->addr))
388                         p->ainsn.boostable = 0;
389                 else
390                         p->ainsn.boostable = -1;
391                 memcpy (p->ainsn.insn, insn, MAX_INSN_SIZE * sizeof (kprobe_opcode_t));
392         }
393         else
394         {
395                 free_insn_slot(&kprobe_insn_pages, NULL, p->ainsn.insn);
396         }
397
398         return ret;
399 }
400
401 int arch_prepare_uprobe (struct kprobe *p, struct task_struct *task, int atomic)
402 {
403         int ret = 0;
404         kprobe_opcode_t insns[UPROBES_TRAMP_LEN];
405
406         if (!ret)
407         {
408                 kprobe_opcode_t insn[MAX_INSN_SIZE];
409                 struct arch_specific_insn ainsn;
410
411                 if (!read_proc_vm_atomic (task, (unsigned long) p->addr, &insn, MAX_INSN_SIZE * sizeof(kprobe_opcode_t)))
412                         panic ("failed to read memory %p!\n", p->addr);
413                 ainsn.insn = insn;
414                 ret = arch_check_insn (&ainsn);
415                 if (!ret)
416                 {
417                         p->opcode = insn[0];
418                         p->ainsn.insn = get_insn_slot(task, atomic);
419                         if (!p->ainsn.insn)
420                                 return -ENOMEM;
421                         if (can_boost (insn))
422                                 p->ainsn.boostable = 0;
423                         else
424                                 p->ainsn.boostable = -1;
425                         memcpy (&insns[UPROBES_TRAMP_INSN_IDX], insn, MAX_INSN_SIZE*sizeof(kprobe_opcode_t));
426                         insns[UPROBES_TRAMP_RET_BREAK_IDX] = BREAKPOINT_INSTRUCTION;
427
428                         if (!write_proc_vm_atomic (task, (unsigned long) p->ainsn.insn, insns, sizeof (insns)))
429                         {
430                                 panic("failed to write memory %p!\n", p->ainsn.insn);
431                                 DBPRINTF ("failed to write insn slot to process memory: insn %p, addr %p, probe %p!", insn, p->ainsn.insn, p->addr);
432                                 free_insn_slot(&uprobe_insn_pages, task, p->ainsn.insn);
433                                 return -EINVAL;
434                         }
435                 }
436         }
437
438         return ret;
439 }
440
441 int arch_prepare_uretprobe (struct kretprobe *p, struct task_struct *task)
442 {
443         DBPRINTF("Warrning: arch_prepare_uretprobe is not implemented\n");
444         return 0;
445 }
446
447 void prepare_singlestep (struct kprobe *p, struct pt_regs *regs)
448 {
449         if(p->ss_addr)
450         {
451                 regs->EREG (ip) = (unsigned long)p->ss_addr;
452                 p->ss_addr = NULL;
453         }
454         else
455         {
456                 regs->EREG (flags) |= TF_MASK;
457                 regs->EREG (flags) &= ~IF_MASK;
458                 /*single step inline if the instruction is an int3 */
459                 if (p->opcode == BREAKPOINT_INSTRUCTION){
460                         regs->EREG (ip) = (unsigned long) p->addr;
461                         //printk("break_insn!!!\n");
462                 }
463                 else
464                         regs->EREG (ip) = (unsigned long) p->ainsn.insn;
465         }
466 }
467
468
469 void save_previous_kprobe (struct kprobe_ctlblk *kcb, struct kprobe *cur_p)
470 {
471         if (kcb->prev_kprobe.kp != NULL)
472         {
473                 panic ("no space to save new probe[]: task = %d/%s, prev %d/%p, current %d/%p, new %d/%p,",
474                                 current->pid, current->comm, kcb->prev_kprobe.kp->tgid, kcb->prev_kprobe.kp->addr,
475                                 kprobe_running()->tgid, kprobe_running()->addr, cur_p->tgid, cur_p->addr);
476         }
477
478
479         kcb->prev_kprobe.kp = kprobe_running();
480         kcb->prev_kprobe.status = kcb->kprobe_status;
481
482 }
483
484 void restore_previous_kprobe (struct kprobe_ctlblk *kcb)
485 {
486         __get_cpu_var (current_kprobe) = kcb->prev_kprobe.kp;
487         kcb->kprobe_status = kcb->prev_kprobe.status;
488         kcb->prev_kprobe.kp = NULL;
489         kcb->prev_kprobe.status = 0;
490 }
491
492 void set_current_kprobe (struct kprobe *p, struct pt_regs *regs, struct kprobe_ctlblk *kcb)
493 {
494         __get_cpu_var (current_kprobe) = p;
495         DBPRINTF ("set_current_kprobe[]: p=%p addr=%p\n", p, p->addr);
496         kcb->kprobe_saved_eflags = kcb->kprobe_old_eflags = (regs->EREG (flags) & (TF_MASK | IF_MASK));
497         if (is_IF_modifier (p->opcode))
498                 kcb->kprobe_saved_eflags &= ~IF_MASK;
499 }
500
501 int kprobe_handler (struct pt_regs *regs)
502 {
503         struct kprobe *p = 0;
504         int ret = 0, pid = 0, retprobe = 0, reenter = 0;
505         kprobe_opcode_t *addr = NULL;
506         struct kprobe_ctlblk *kcb;
507 #ifdef OVERHEAD_DEBUG
508         struct timeval swap_tv1;
509         struct timeval swap_tv2;
510 #endif
511 #ifdef SUPRESS_BUG_MESSAGES
512         int swap_oops_in_progress;
513 #endif
514
515         /* We're in an interrupt, but this is clear and BUG()-safe. */
516         addr = (kprobe_opcode_t *) (regs->EREG (ip) - sizeof (kprobe_opcode_t));
517         DBPRINTF ("KPROBE: regs->eip = 0x%lx addr = 0x%p\n", regs->EREG (ip), addr);
518 #ifdef SUPRESS_BUG_MESSAGES
519         // oops_in_progress used to avoid BUG() messages that slow down kprobe_handler() execution
520         swap_oops_in_progress = oops_in_progress;
521         oops_in_progress = 1;
522 #endif
523 #ifdef OVERHEAD_DEBUG
524 #define USEC_IN_SEC_NUM                         1000000
525         do_gettimeofday(&swap_tv1);
526 #endif
527         preempt_disable ();
528
529         kcb = get_kprobe_ctlblk ();
530
531         if (user_mode_vm(regs))
532         {
533                 //printk("exception[%lu] from user mode %s/%u/%u addr %p.\n", nCount, current->comm, current->pid, current->tgid, addr);
534                 pid = current->tgid;
535         }
536
537         /* Check we're not actually recursing */
538         if (kprobe_running ())
539         {
540                 DBPRINTF ("lock???");
541                 p = get_kprobe(addr, pid);
542                 if (p)
543                 {
544                         DBPRINTF ("reenter p = %p", p);
545                         if(!pid){
546                                 if (kcb->kprobe_status == KPROBE_HIT_SS && *p->ainsn.insn == BREAKPOINT_INSTRUCTION)
547                                 {
548                                         regs->EREG (flags) &= ~TF_MASK;
549                                         regs->EREG (flags) |= kcb->kprobe_saved_eflags;
550                                         goto no_kprobe;
551                                 }
552                         }
553                         else {
554                                 //#warning BREAKPOINT_INSTRUCTION user mode handling is missed!!!
555                         }
556
557                         /* We have reentered the kprobe_handler(), since
558                          * another probe was hit while within the handler.
559                          * We here save the original kprobes variables and
560                          * just single step on the instruction of the new probe
561                          * without calling any user handlers.
562                          */
563                         save_previous_kprobe (kcb, p);
564                         set_current_kprobe (p, regs, kcb);
565                         kprobes_inc_nmissed_count (p);
566                         prepare_singlestep (p, regs);
567                         kcb->kprobe_status = KPROBE_REENTER;
568                         // FIXME should we enable preemption here??...
569                         //preempt_enable_no_resched ();
570 #ifdef OVERHEAD_DEBUG
571                         do_gettimeofday(&swap_tv2);
572                         swap_sum_hit++;
573                         swap_sum_time += ((swap_tv2.tv_sec - swap_tv1.tv_sec) * USEC_IN_SEC_NUM +
574                                 (swap_tv2.tv_usec - swap_tv1.tv_usec));
575 #endif
576 #ifdef SUPRESS_BUG_MESSAGES
577                         oops_in_progress = swap_oops_in_progress;
578 #endif
579                         return 1;
580                 }
581                 else
582                 {
583                         if(!pid){
584                                 if (*addr != BREAKPOINT_INSTRUCTION)
585                                 {
586                                         /* The breakpoint instruction was removed by
587                                          * another cpu right after we hit, no further
588                                          * handling of this interrupt is appropriate
589                                          */
590                                         regs->EREG (ip) -= sizeof (kprobe_opcode_t);
591                                         ret = 1;
592                                         goto no_kprobe;
593                                 }
594                         }
595                         else {
596                                 //#warning BREAKPOINT_INSTRUCTION user mode handling is missed!!!
597                                 //we can reenter probe upon uretprobe exception
598                                 DBPRINTF ("check for UNDEF_INSTRUCTION %p\n", addr);
599                                 // UNDEF_INSTRUCTION from user space
600                                 p = get_kprobe_by_insn_slot (addr-UPROBES_TRAMP_RET_BREAK_IDX, pid, current);
601                                 if (p) {
602                                         save_previous_kprobe (kcb, p);
603                                         kcb->kprobe_status = KPROBE_REENTER;
604                                         reenter = 1;
605                                         retprobe = 1;
606                                         DBPRINTF ("uretprobe %p\n", addr);
607                                 }
608                         }
609                         if(!p){
610                                 p = __get_cpu_var (current_kprobe);
611                                 if(p->tgid)
612                                         panic("after uhandler");
613                                 DBPRINTF ("kprobe_running !!! p = 0x%p p->break_handler = 0x%p", p, p->break_handler);
614                                 if (p->break_handler && p->break_handler (p, regs))
615                                 {
616                                         DBPRINTF ("kprobe_running !!! goto ss");
617                                         goto ss_probe;
618                                 }
619                                 DBPRINTF ("kprobe_running !!! goto no");
620                                 DBPRINTF ("no_kprobe");
621                                 goto no_kprobe;
622                         }
623                 }
624         }
625
626         DBPRINTF ("get_kprobe %p", addr);
627         if (!p)
628                 p = get_kprobe(addr, pid);
629         if (!p)
630         {
631                 if(!pid){
632                         if (*addr != BREAKPOINT_INSTRUCTION)
633                         {
634                                 /*
635                                  * The breakpoint instruction was removed right
636                                  * after we hit it.  Another cpu has removed
637                                  * either a probepoint or a debugger breakpoint
638                                  * at this address.  In either case, no further
639                                  * handling of this interrupt is appropriate.
640                                  * Back up over the (now missing) int3 and run
641                                  * the original instruction.
642                                  */
643                                 regs->EREG (ip) -= sizeof (kprobe_opcode_t);
644                                 ret = 1;
645                         }
646                 }
647                 else {
648                         //#warning BREAKPOINT_INSTRUCTION user mode handling is missed!!!
649                         DBPRINTF ("search UNDEF_INSTRUCTION %p\n", addr);
650                         // UNDEF_INSTRUCTION from user space
651                         p = get_kprobe_by_insn_slot (addr-UPROBES_TRAMP_RET_BREAK_IDX, pid, current);
652                         if (!p) {
653                                 // Not one of ours: let kernel handle it
654                                 DBPRINTF ("no_kprobe");
655                                 //printk("no_kprobe2 ret = %d\n", ret);
656                                 goto no_kprobe;
657                         }
658                         retprobe = 1;
659                         DBPRINTF ("uretprobe %p\n", addr);
660                 }
661                 if(!p) {
662                         /* Not one of ours: let kernel handle it */
663                         DBPRINTF ("no_kprobe");
664                         goto no_kprobe;
665                 }
666         }
667         set_current_kprobe (p, regs, kcb);
668         if(!reenter)
669                 kcb->kprobe_status = KPROBE_HIT_ACTIVE;
670
671         if (retprobe)           //(einsn == UNDEF_INSTRUCTION)
672                 ret = trampoline_probe_handler (p, regs);
673         else if (p->pre_handler)
674                 ret = p->pre_handler (p, regs);
675
676         if (ret)
677         {
678                 if (ret == 2) { // we have alreadyc called the handler, so just single step the instruction
679                         DBPRINTF ("p->pre_handler[] 2");
680                         goto ss_probe;
681                 }
682                 DBPRINTF ("p->pre_handler[] 1");
683                 // FIXME should we enable preemption here??...
684                 //preempt_enable_no_resched ();
685 #ifdef OVERHEAD_DEBUG
686                 do_gettimeofday(&swap_tv2);
687                 swap_sum_hit++;
688                 swap_sum_time += ((swap_tv2.tv_sec - swap_tv1.tv_sec) * USEC_IN_SEC_NUM +
689                         (swap_tv2.tv_usec - swap_tv1.tv_usec));
690 #endif
691 #ifdef SUPRESS_BUG_MESSAGES
692                 oops_in_progress = swap_oops_in_progress;
693 #endif
694                 /* handler has already set things up, so skip ss setup */
695                 return 1;
696         }
697         DBPRINTF ("p->pre_handler[] 0");
698
699 ss_probe:
700         DBPRINTF ("p = %p\n", p);
701         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);
702
703 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PM)
704         if (p->ainsn.boostable == 1 && !p->post_handler)
705         {
706                 /* Boost up -- we can execute copied instructions directly */
707                 reset_current_kprobe ();
708                 regs->EREG (ip) = (unsigned long) p->ainsn.insn;
709                 preempt_enable_no_resched ();
710 #ifdef OVERHEAD_DEBUG
711                 do_gettimeofday(&swap_tv2);
712                 swap_sum_hit++;
713                 swap_sum_time += ((swap_tv2.tv_sec - swap_tv1.tv_sec) *  USEC_IN_SEC_NUM +
714                         (swap_tv2.tv_usec - swap_tv1.tv_usec));
715 #endif
716 #ifdef SUPRESS_BUG_MESSAGES
717                 oops_in_progress = swap_oops_in_progress;
718 #endif
719                 return 1;
720         }
721 #endif // !CONFIG_PREEMPT
722         prepare_singlestep (p, regs);
723         kcb->kprobe_status = KPROBE_HIT_SS;
724         // FIXME should we enable preemption here??...
725         //preempt_enable_no_resched ();
726 #ifdef OVERHEAD_DEBUG
727         do_gettimeofday(&swap_tv2);
728         swap_sum_hit++;
729         swap_sum_time += ((swap_tv2.tv_sec - swap_tv1.tv_sec) *  USEC_IN_SEC_NUM +
730                 (swap_tv2.tv_usec - swap_tv1.tv_usec));
731 #endif
732 #ifdef SUPRESS_BUG_MESSAGES
733         oops_in_progress = swap_oops_in_progress;
734 #endif
735         return 1;
736
737 no_kprobe:
738
739         preempt_enable_no_resched ();
740 #ifdef OVERHEAD_DEBUG
741         do_gettimeofday(&swap_tv2);
742         swap_sum_hit++;
743         swap_sum_time += ((swap_tv2.tv_sec - swap_tv1.tv_sec) *  USEC_IN_SEC_NUM +
744                 (swap_tv2.tv_usec - swap_tv1.tv_usec));
745 #endif
746 #ifdef SUPRESS_BUG_MESSAGES
747         oops_in_progress = swap_oops_in_progress;
748 #endif
749         return ret;
750 }
751
752 int setjmp_pre_handler (struct kprobe *p, struct pt_regs *regs)
753 {
754         struct jprobe *jp = container_of (p, struct jprobe, kp);
755         kprobe_pre_entry_handler_t pre_entry;
756         entry_point_t entry;
757
758         unsigned long addr, args[6];
759         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
760
761         DBPRINTF ("setjmp_pre_handler %p:%d", p->addr, p->tgid);
762         pre_entry = (kprobe_pre_entry_handler_t) jp->pre_entry;
763         entry = (entry_point_t) jp->entry;
764
765         if (!p->tgid || (p->tgid == current->tgid)) {
766                 /* handle __switch_to probe */
767                 if(!p->tgid && (p->addr == sched_addr) && sched_rp) {
768                         patch_suspended_all_task_ret_addr(sched_rp);
769                 }
770         }
771
772         if (p->tgid) {
773                 /* FIXME some user space apps crash if we clean interrupt bit */
774                 //regs->EREG(flags) &= ~IF_MASK;
775 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 18)
776                 trace_hardirqs_off ();
777 #endif
778                 if (p->tgid == current->tgid) {
779                         // read first 6 args from stack
780                         if (!read_proc_vm_atomic (current, regs->EREG(sp) + 4, args, sizeof(args)))
781                                 panic ("failed to read user space func arguments %lx!\n", regs->EREG(sp)+4);
782                         if (pre_entry)
783                                 p->ss_addr = pre_entry (jp->priv_arg, regs);
784                         if (entry)
785                                 entry (args[0], args[1], args[2], args[3], args[4], args[5]);
786                 } else {
787                         dbi_arch_uprobe_return();
788                 }
789
790                 return 2;
791         } else {
792                 kcb->jprobe_saved_regs = *regs;
793                 kcb->jprobe_saved_esp = &regs->EREG(sp);
794                 addr = (unsigned long) (kcb->jprobe_saved_esp);
795
796                 /* TBD: As Linus pointed out, gcc assumes that the callee
797                  * owns the argument space and could overwrite it, e.g.
798                  * tailcall optimization. So, to be absolutely safe
799                  * we also save and restore enough stack bytes to cover
800                  * the argument area. */
801                 memcpy (kcb->jprobes_stack, (kprobe_opcode_t *)addr, MIN_STACK_SIZE (addr));
802                 regs->EREG (flags) &= ~IF_MASK;
803 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 18)
804                 trace_hardirqs_off ();
805 #endif
806                 if (pre_entry)
807                         p->ss_addr = pre_entry(jp->priv_arg, regs);
808                 regs->EREG(ip) = (unsigned long) (jp->entry);
809         }
810
811         return 1;
812
813 #if 0 /* initial version */
814         struct jprobe *jp = container_of (p, struct jprobe, kp);
815         kprobe_pre_entry_handler_t pre_entry;
816         entry_point_t entry;
817
818         unsigned long addr, args[6];
819         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
820
821         DBPRINTF ("setjmp_pre_handler %p:%d", p->addr, p->tgid);
822         pre_entry = (kprobe_pre_entry_handler_t) jp->pre_entry;
823         entry = (entry_point_t) jp->entry;
824         if(p->tgid) {
825                 regs->EREG (flags) &= ~IF_MASK;
826 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 18)
827                 trace_hardirqs_off ();
828 #endif
829                 if (p->tgid == current->tgid)
830                 {
831                         // read first 6 args from stack
832                         if (!read_proc_vm_atomic (current, regs->EREG(sp)+4, args, sizeof(args)))
833                                 panic ("failed to read user space func arguments %lx!\n", regs->EREG(sp)+4);
834                         if (pre_entry)
835                                 p->ss_addr = pre_entry (jp->priv_arg, regs);
836                         if (entry)
837                                 entry (args[0], args[1], args[2], args[3], args[4], args[5]);
838                 }
839                 else
840                         dbi_arch_uprobe_return ();
841
842                 return 2;
843         }
844         else {
845                 kcb->jprobe_saved_regs = *regs;
846                 kcb->jprobe_saved_esp = &regs->EREG (sp);
847                 addr = (unsigned long) (kcb->jprobe_saved_esp);
848
849                 /*
850                  * TBD: As Linus pointed out, gcc assumes that the callee
851                  * owns the argument space and could overwrite it, e.g.
852                  * tailcall optimization. So, to be absolutely safe
853                  * we also save and restore enough stack bytes to cover
854                  * the argument area.
855                  */
856                 memcpy (kcb->jprobes_stack, (kprobe_opcode_t *) addr, MIN_STACK_SIZE (addr));
857                 regs->EREG (flags) &= ~IF_MASK;
858 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 18)
859                 trace_hardirqs_off ();
860 #endif
861                 if (pre_entry)
862                         p->ss_addr = pre_entry (jp->priv_arg, regs);
863                 regs->EREG (ip) = (unsigned long) (jp->entry);
864         }
865
866         return 1;
867 #endif /* 0 */
868 }
869
870 void dbi_jprobe_return (void)
871 {
872         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
873
874         asm volatile("       xchgl   %%ebx,%%esp     \n"
875                         "       int3                    \n"
876                         "       .globl dbi_jprobe_return_end    \n"
877                         "       dbi_jprobe_return_end:  \n"
878                         "       nop                     \n"::"b" (kcb->jprobe_saved_esp):"memory");
879 }
880
881 void dbi_arch_uprobe_return (void)
882 {
883         DBPRINTF("dbi_arch_uprobe_return (void) is empty");
884 }
885
886 /*
887  * Called after single-stepping.  p->addr is the address of the
888  * instruction whose first byte has been replaced by the "int 3"
889  * instruction.  To avoid the SMP problems that can occur when we
890  * temporarily put back the original opcode to single-step, we
891  * single-stepped a copy of the instruction.  The address of this
892  * copy is p->ainsn.insn.
893  *
894  * This function prepares to return from the post-single-step
895  * interrupt.  We have to fix up the stack as follows:
896  *
897  * 0) Except in the case of absolute or indirect jump or call instructions,
898  * the new eip is relative to the copied instruction.  We need to make
899  * it relative to the original instruction.
900  *
901  * 1) If the single-stepped instruction was pushfl, then the TF and IF
902  * flags are set in the just-pushed eflags, and may need to be cleared.
903  *
904  * 2) If the single-stepped instruction was a call, the return address
905  * that is atop the stack is the address following the copied instruction.
906  * We need to make it the address following the original instruction.
907  *
908  * This function also checks instruction size for preparing direct execution.
909  */
910 static void resume_execution (struct kprobe *p, struct pt_regs *regs, struct kprobe_ctlblk *kcb)
911 {
912         unsigned long *tos, tos_dword = 0;
913         unsigned long copy_eip = (unsigned long) p->ainsn.insn;
914         unsigned long orig_eip = (unsigned long) p->addr;
915         kprobe_opcode_t insns[2];
916
917         regs->EREG (flags) &= ~TF_MASK;
918
919         if(p->tgid){
920                 tos = (unsigned long *) &tos_dword;
921                 if (!read_proc_vm_atomic (current, regs->EREG (sp), &tos_dword, sizeof(tos_dword)))
922                         panic ("failed to read dword from top of the user space stack %lx!\n", regs->EREG (sp));
923                 if (!read_proc_vm_atomic (current, (unsigned long)p->ainsn.insn, insns, 2*sizeof(kprobe_opcode_t)))
924                         panic ("failed to read first 2 opcodes of instruction copy from user space %p!\n", p->ainsn.insn);
925         }
926         else {
927                 tos = (unsigned long *) &regs->EREG (sp);
928                 insns[0] = p->ainsn.insn[0];
929                 insns[1] = p->ainsn.insn[1];
930         }
931
932         switch (insns[0])
933         {
934                 case 0x9c:              /* pushfl */
935                         *tos &= ~(TF_MASK | IF_MASK);
936                         *tos |= kcb->kprobe_old_eflags;
937                         break;
938                 case 0xc2:              /* iret/ret/lret */
939                 case 0xc3:
940                 case 0xca:
941                 case 0xcb:
942                 case 0xcf:
943                 case 0xea:              /* jmp absolute -- eip is correct */
944                         /* eip is already adjusted, no more changes required */
945                         p->ainsn.boostable = 1;
946                         goto no_change;
947                 case 0xe8:              /* call relative - Fix return addr */
948                         *tos = orig_eip + (*tos - copy_eip);
949                         break;
950                 case 0x9a:              /* call absolute -- same as call absolute, indirect */
951                         *tos = orig_eip + (*tos - copy_eip);
952                         if(p->tgid){
953                                 if (!write_proc_vm_atomic (current, regs->EREG (sp), &tos_dword, sizeof(tos_dword)))
954                                         panic ("failed to write dword to top of the user space stack %lx!\n", regs->EREG (sp));
955                         }
956                         goto no_change;
957                 case 0xff:
958                         if ((insns[1] & 0x30) == 0x10)
959                         {
960                                 /*
961                                  * call absolute, indirect
962                                  * Fix return addr; eip is correct.
963                                  * But this is not boostable
964                                  */
965                                 *tos = orig_eip + (*tos - copy_eip);
966                                 if(p->tgid){
967                                         if (!write_proc_vm_atomic (current, regs->EREG (sp), &tos_dword, sizeof(tos_dword)))
968                                                 panic ("failed to write dword to top of the user space stack %lx!\n", regs->EREG (sp));
969                                 }
970                                 goto no_change;
971                         }
972                         else if (((insns[1] & 0x31) == 0x20) || /* jmp near, absolute indirect */
973                                         ((insns[1] & 0x31) == 0x21))
974                         {               /* jmp far, absolute indirect */
975                                 /* eip is correct. And this is boostable */
976                                 p->ainsn.boostable = 1;
977                                 goto no_change;
978                         }
979                 default:
980                         break;
981         }
982
983         if(p->tgid){
984                 if (!write_proc_vm_atomic (current, regs->EREG (sp), &tos_dword, sizeof(tos_dword)))
985                         panic ("failed to write dword to top of the user space stack %lx!\n", regs->EREG (sp));
986         }
987
988         if (p->ainsn.boostable == 0)
989         {
990                 if ((regs->EREG (ip) > copy_eip) && (regs->EREG (ip) - copy_eip) + 5 < MAX_INSN_SIZE)
991                 {
992                         /*
993                          * These instructions can be executed directly if it
994                          * jumps back to correct address.
995                          */
996                         if(p->tgid)
997                                 set_user_jmp_op ((void *) regs->EREG (ip), (void *) orig_eip + (regs->EREG (ip) - copy_eip));
998                         else
999                                 set_jmp_op ((void *) regs->EREG (ip), (void *) orig_eip + (regs->EREG (ip) - copy_eip));
1000                         p->ainsn.boostable = 1;
1001                 }
1002                 else
1003                 {
1004                         p->ainsn.boostable = -1;
1005                 }
1006         }
1007
1008         regs->EREG (ip) = orig_eip + (regs->EREG (ip) - copy_eip);
1009
1010 no_change:
1011         return;
1012 }
1013
1014 /*
1015  * Interrupts are disabled on entry as trap1 is an interrupt gate and they
1016  * remain disabled thoroughout this function.
1017  */
1018 static int post_kprobe_handler (struct pt_regs *regs)
1019 {
1020         struct kprobe *cur = kprobe_running ();
1021         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
1022
1023         if (!cur)
1024                 return 0;
1025         if ((kcb->kprobe_status != KPROBE_REENTER) && cur->post_handler)
1026         {
1027                 kcb->kprobe_status = KPROBE_HIT_SSDONE;
1028                 cur->post_handler (cur, regs, 0);
1029         }
1030
1031         resume_execution (cur, regs, kcb);
1032         regs->EREG (flags) |= kcb->kprobe_saved_eflags;
1033 #ifndef CONFIG_X86
1034         trace_hardirqs_fixup_flags (regs->EREG (flags));
1035 #endif // CONFIG_X86
1036         /*Restore back the original saved kprobes variables and continue. */
1037         if (kcb->kprobe_status == KPROBE_REENTER)
1038         {
1039                 restore_previous_kprobe (kcb);
1040                 goto out;
1041         }
1042         reset_current_kprobe ();
1043 out:
1044         preempt_enable_no_resched ();
1045
1046         /*
1047          * if somebody else is singlestepping across a probe point, eflags
1048          * will have TF set, in which case, continue the remaining processing
1049          * of do_debug, as if this is not a probe hit.
1050          */
1051         if (regs->EREG (flags) & TF_MASK)
1052                 return 0;
1053
1054         return 1;
1055 }
1056
1057 int kprobe_fault_handler (struct pt_regs *regs, int trapnr)
1058 {
1059         struct kprobe *cur = kprobe_running ();
1060         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
1061
1062         switch (kcb->kprobe_status)
1063         {
1064                 case KPROBE_HIT_SS:
1065                 case KPROBE_REENTER:
1066                         /*
1067                          * We are here because the instruction being single
1068                          * stepped caused a page fault. We reset the current
1069                          * kprobe and the eip points back to the probe address
1070                          * and allow the page fault handler to continue as a
1071                          * normal page fault.
1072                          */
1073                         regs->EREG (ip) = (unsigned long) cur->addr;
1074                         regs->EREG (flags) |= kcb->kprobe_old_eflags;
1075                         if (kcb->kprobe_status == KPROBE_REENTER)
1076                                 restore_previous_kprobe (kcb);
1077                         else
1078                                 reset_current_kprobe ();
1079                         preempt_enable_no_resched ();
1080                         break;
1081                 case KPROBE_HIT_ACTIVE:
1082                 case KPROBE_HIT_SSDONE:
1083                         /*
1084                          * We increment the nmissed count for accounting,
1085                          * we can also use npre/npostfault count for accouting
1086                          * these specific fault cases.
1087                          */
1088                         kprobes_inc_nmissed_count (cur);
1089
1090                         /*
1091                          * We come here because instructions in the pre/post
1092                          * handler caused the page_fault, this could happen
1093                          * if handler tries to access user space by
1094                          * copy_from_user(), get_user() etc. Let the
1095                          * user-specified handler try to fix it first.
1096                          */
1097                         if (cur->fault_handler && cur->fault_handler (cur, regs, trapnr))
1098                                 return 1;
1099
1100                         /*
1101                          * In case the user-specified fault handler returned
1102                          * zero, try to fix up.
1103                          */
1104                         if (fixup_exception (regs))
1105                                 return 1;
1106
1107                         /*
1108                          * fixup_exception() could not handle it,
1109                          * Let do_page_fault() fix it.
1110                          */
1111                         break;
1112                 default:
1113                         break;
1114         }
1115         return 0;
1116 }
1117
1118 int kprobe_exceptions_notify (struct notifier_block *self, unsigned long val, void *data)
1119 {
1120         struct die_args *args = (struct die_args *) data;
1121         int ret = NOTIFY_DONE;
1122
1123         DBPRINTF ("val = %ld, data = 0x%X", val, (unsigned int) data);
1124
1125         /*if (args->regs && user_mode_vm (args->regs))
1126           return ret;*/
1127
1128         DBPRINTF ("switch (val) %lu %d %d", val, DIE_INT3, DIE_TRAP);
1129         switch (val)
1130         {
1131 #ifdef CONFIG_KPROBES
1132                 case DIE_INT3:
1133 #else
1134                 case DIE_TRAP:
1135 #endif
1136                         DBPRINTF ("before kprobe_handler ret=%d %p", ret, args->regs);
1137                         if (kprobe_handler (args->regs))
1138                                 ret = NOTIFY_STOP;
1139                         DBPRINTF ("after kprobe_handler ret=%d %p", ret, args->regs);
1140                         break;
1141                 case DIE_DEBUG:
1142                         if (post_kprobe_handler (args->regs))
1143                                 ret = NOTIFY_STOP;
1144                         break;
1145                 case DIE_GPF:
1146                         // kprobe_running() needs smp_processor_id()
1147                         preempt_disable ();
1148                         if (kprobe_running () && kprobe_fault_handler (args->regs, args->trapnr))
1149                                 ret = NOTIFY_STOP;
1150                         preempt_enable ();
1151                         break;
1152                 default:
1153                         break;
1154         }
1155         DBPRINTF ("ret=%d", ret);
1156         /* if(ret == NOTIFY_STOP) */
1157         /*      handled_exceptions++; */
1158
1159         return ret;
1160 }
1161
1162 static struct notifier_block kprobe_exceptions_nb = {
1163         .notifier_call = kprobe_exceptions_notify,
1164         .priority = INT_MAX
1165 };
1166
1167 int longjmp_break_handler (struct kprobe *p, struct pt_regs *regs)
1168 {
1169         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
1170         u8 *addr = (u8 *) (regs->EREG (ip) - 1);
1171         unsigned long stack_addr = (unsigned long) (kcb->jprobe_saved_esp);
1172         struct jprobe *jp = container_of (p, struct jprobe, kp);
1173
1174         DBPRINTF ("p = %p\n", p);
1175
1176         if ((addr > (u8 *) dbi_jprobe_return) && (addr < (u8 *) dbi_jprobe_return_end))
1177         {
1178                 if ((unsigned long *)(&regs->EREG(sp)) != kcb->jprobe_saved_esp)
1179                 {
1180                         struct pt_regs *saved_regs = &kcb->jprobe_saved_regs;
1181                         printk ("current esp %p does not match saved esp %p\n", &regs->EREG (sp), kcb->jprobe_saved_esp);
1182                         printk ("Saved registers for jprobe %p\n", jp);
1183                         show_registers (saved_regs);
1184                         printk ("Current registers\n");
1185                         show_registers (regs);
1186                         panic("BUG");
1187                         //BUG ();
1188                 }
1189                 *regs = kcb->jprobe_saved_regs;
1190                 memcpy ((kprobe_opcode_t *) stack_addr, kcb->jprobes_stack, MIN_STACK_SIZE (stack_addr));
1191                 preempt_enable_no_resched ();
1192                 return 1;
1193         }
1194 }
1195
1196 void arch_arm_kprobe (struct kprobe *p)
1197 {
1198         text_poke (p->addr, ((unsigned char[])
1199                                 {BREAKPOINT_INSTRUCTION}), 1);
1200 }
1201
1202 void arch_disarm_kprobe (struct kprobe *p)
1203 {
1204         text_poke (p->addr, &p->opcode, 1);
1205 }
1206
1207 void * trampoline_probe_handler_x86 (struct pt_regs *regs)
1208 {
1209         return (void *)trampoline_probe_handler(NULL, regs);
1210 }
1211
1212
1213
1214
1215 /*
1216  * Called when the probe at kretprobe trampoline is hit
1217  */
1218 int trampoline_probe_handler (struct kprobe *p, struct pt_regs *regs)
1219 {
1220         struct kretprobe_instance *ri = NULL;
1221         struct hlist_head *head, empty_rp;
1222         struct hlist_node *node, *tmp;
1223         unsigned long flags, orig_ret_address = 0;
1224         unsigned long trampoline_address = (unsigned long) &kretprobe_trampoline;
1225         struct kretprobe *crp = NULL;
1226         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
1227
1228         DBPRINTF ("start");
1229
1230         if (p && p->tgid){
1231                 // in case of user space retprobe trampoline is at the Nth instruction of US tramp
1232                 trampoline_address = (unsigned long)(p->ainsn.insn + UPROBES_TRAMP_RET_BREAK_IDX);
1233         }
1234
1235         INIT_HLIST_HEAD (&empty_rp);
1236         spin_lock_irqsave (&kretprobe_lock, flags);
1237         /*
1238          * We are using different hash keys (current and mm) for finding kernel
1239          * space and user space probes.  Kernel space probes can change mm field in
1240          * task_struct.  User space probes can be shared between threads of one
1241          * process so they have different current but same mm.
1242          */
1243         if (p && p->tgid) {
1244                 head = kretprobe_inst_table_head(current->mm);
1245         } else {
1246                 head = kretprobe_inst_table_head(current);
1247         }
1248
1249         if(!p){ // X86 kernel space
1250                 DBPRINTF ("regs %p", regs);
1251                 /* fixup registers */
1252                 regs->XREG (cs) = __KERNEL_CS | get_kernel_rpl ();
1253                 regs->EREG (ip) = trampoline_address;
1254                 regs->ORIG_EAX_REG = 0xffffffff;
1255         }
1256
1257         /*
1258          * It is possible to have multiple instances associated with a given
1259          * task either because an multiple functions in the call path
1260          * have a return probe installed on them, and/or more then one
1261          * return probe was registered for a target function.
1262          *
1263          * We can handle this because:
1264          *     - instances are always inserted at the head of the list
1265          *     - when multiple return probes are registered for the same
1266          *       function, the first instance's ret_addr will point to the
1267          *       real return address, and all the rest will point to
1268          *       kretprobe_trampoline
1269          */
1270         hlist_for_each_entry_safe (ri, node, tmp, head, hlist)
1271         {
1272                 if (ri->task != current)
1273                         /* another task is sharing our hash bucket */
1274                         continue;
1275                 if (ri->rp && ri->rp->handler){
1276
1277                         if(!p){ // X86 kernel space
1278                                 __get_cpu_var (current_kprobe) = &ri->rp->kp;
1279                                 get_kprobe_ctlblk ()->kprobe_status = KPROBE_HIT_ACTIVE;
1280                         }
1281
1282                         ri->rp->handler (ri, regs, ri->rp->priv_arg);
1283
1284                         if(!p) // X86 kernel space
1285                                 __get_cpu_var (current_kprobe) = NULL;
1286
1287                 }
1288
1289                 orig_ret_address = (unsigned long) ri->ret_addr;
1290                 recycle_rp_inst (ri);
1291                 if (orig_ret_address != trampoline_address)
1292                         /*
1293                          * This is the real return address. Any other
1294                          * instances associated with this task are for
1295                          * other calls deeper on the call stack
1296                          */
1297                         break;
1298         }
1299         kretprobe_assert (ri, orig_ret_address, trampoline_address);
1300         //BUG_ON(!orig_ret_address || (orig_ret_address == trampoline_address));
1301         if (trampoline_address != (unsigned long) &kretprobe_trampoline){
1302                 if (ri->rp2) BUG_ON (ri->rp2->kp.tgid == 0);
1303                 if (ri->rp) BUG_ON (ri->rp->kp.tgid == 0);
1304                 else if (ri->rp2) BUG_ON (ri->rp2->kp.tgid == 0);
1305         }
1306         if ((ri->rp && ri->rp->kp.tgid) || (ri->rp2 && ri->rp2->kp.tgid))
1307                 BUG_ON (trampoline_address == (unsigned long) &kretprobe_trampoline);
1308
1309         if(p){ // X86 user space
1310                 regs->EREG(ip) = orig_ret_address;
1311                 //printk (" uretprobe regs->eip = 0x%lx\n", regs->EREG(ip));
1312         }
1313
1314         if(p){ // ARM, MIPS, X86 user space
1315                 if (kcb->kprobe_status == KPROBE_REENTER)
1316                         restore_previous_kprobe (kcb);
1317                 else
1318                         reset_current_kprobe ();
1319
1320                 //TODO: test - enter function, delete us retprobe, exit function
1321                 // for user space retprobes only - deferred deletion
1322                 if (trampoline_address != (unsigned long) &kretprobe_trampoline)
1323                 {
1324                         // if we are not at the end of the list and current retprobe should be disarmed
1325                         if (node && ri->rp2)
1326                         {
1327                                 struct hlist_node *current_node = node;
1328                                 crp = ri->rp2;
1329                                 /*sprintf(die_msg, "deferred disarm p->addr = %p [%lx %lx %lx]\n",
1330                                   crp->kp.addr, *kaddrs[0], *kaddrs[1], *kaddrs[2]);
1331                                   DIE(die_msg, regs); */
1332                                 // look for other instances for the same retprobe
1333                                 hlist_for_each_entry_safe (ri, node, tmp, head, hlist)
1334                                 {
1335                                         /*
1336                                          * Trying to find another retprobe instance associated with
1337                                          * the same retprobe.
1338                                          */
1339                                         if (ri->rp2 == crp && node != current_node)
1340                                                 break;
1341                                 }
1342                                 if (!node)
1343                                 {       // if there are no more instances for this retprobe
1344                                         // delete retprobe
1345                                         DBPRINTF ("defered retprobe deletion p->addr = %p", crp->kp.addr);
1346                                         /*
1347                                           If there is no any retprobe instances of this retprobe
1348                                           we can free the resources related to the probe.
1349                                          */
1350                                         struct kprobe *is_p = &crp->kp;
1351                                         if (!(hlist_unhashed(&is_p->is_hlist))) {
1352                                                 hlist_del_rcu(&is_p->is_hlist);
1353                                         }
1354                                         unregister_uprobe (&crp->kp, current, 1);
1355                                         kfree (crp);
1356                                 }
1357                                 hlist_del(current_node);
1358                         }
1359                 }
1360         }
1361
1362         hlist_for_each_entry_safe (ri, node, tmp, &empty_rp, hlist)
1363         {
1364                 hlist_del (&ri->hlist);
1365                 kfree (ri);
1366         }
1367         spin_unlock_irqrestore (&kretprobe_lock, flags);
1368
1369         if(!p) // X86 kernel space
1370                 return (int)orig_ret_address;
1371
1372         preempt_enable_no_resched ();
1373         /*
1374          * By returning a non-zero value, we are telling
1375          * kprobe_handler() that we don't want the post_handler
1376          * to run (and have re-enabled preemption)
1377          */
1378         return 1;
1379 }
1380
1381 void __arch_prepare_kretprobe (struct kretprobe *rp, struct pt_regs *regs)
1382 {
1383         struct kretprobe_instance *ri;
1384
1385         DBPRINTF ("start\n");
1386         //TODO: test - remove retprobe after func entry but before its exit
1387         if ((ri = get_free_rp_inst (rp)) != NULL)
1388         {
1389                 ri->rp = rp;
1390                 ri->rp2 = NULL;
1391                 ri->task = current;
1392
1393                 /* Replace the return addr with trampoline addr */
1394                 if (rp->kp.tgid){
1395                         unsigned long ra = (unsigned long) (rp->kp.ainsn.insn + UPROBES_TRAMP_RET_BREAK_IDX);/*, stack[6];
1396                                                                                                                if (!read_proc_vm_atomic (current, regs->EREG(sp), stack, sizeof(stack)))
1397                                                                                                                panic ("failed to read user space func stack %lx!\n", regs->EREG(sp));
1398                                                                                                                printk("stack: %lx %lx %lx %lx %lx %lx\n", stack[0], stack[1], stack[2], stack[3], stack[4], stack[5]);*/
1399                         if (!read_proc_vm_atomic (current, regs->EREG(sp), &(ri->ret_addr), sizeof(ri->ret_addr)))
1400                                 panic ("failed to read user space func ra %lx!\n", regs->EREG(sp));
1401                         if (!write_proc_vm_atomic (current, regs->EREG(sp), &ra, sizeof(ra)))
1402                                 panic ("failed to write user space func ra %lx!\n", regs->EREG(sp));
1403                         //printk("__arch_prepare_kretprobe: ra %lx %p->%lx\n",regs->EREG(sp), ri->ret_addr, ra);
1404                 }
1405                 else {
1406                         unsigned long *sara = (unsigned long *)&regs->EREG(sp);
1407                         ri->ret_addr = (kprobe_opcode_t *)*sara;
1408                         *sara = (unsigned long)&kretprobe_trampoline;
1409                         DBPRINTF ("ra loc %p, origr_ra %p new ra %lx\n", sara, ri->ret_addr, *sara);
1410                 }
1411
1412                 add_rp_inst (ri);
1413         }
1414         else {
1415                 DBPRINTF ("WARNING: missed retprobe %p\n", rp->kp.addr);
1416                 rp->nmissed++;
1417         }
1418 }
1419
1420
1421 int asm_init_module_dependencies()
1422 {
1423         INIT_MOD_DEP_VAR(module_alloc, module_alloc);
1424         INIT_MOD_DEP_VAR(module_free, module_free);
1425         INIT_MOD_DEP_VAR(fixup_exception, fixup_exception);
1426 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 23)
1427 # error this kernel version has no text_poke function which is necessaryf for x86 ach!!!
1428 #else
1429         INIT_MOD_DEP_VAR(text_poke, text_poke);
1430 #endif
1431         INIT_MOD_DEP_VAR(show_registers, show_registers);
1432 #if defined(CONFIG_PREEMPT) && defined(CONFIG_PM)
1433         INIT_MOD_DEP_VAR(freeze_processes, freeze_processes);
1434         INIT_MOD_DEP_VAR(thaw_processes, thaw_processes);
1435 #endif
1436
1437         return 0;
1438 }
1439
1440 int __init arch_init_kprobes (void)
1441 {
1442         if (arch_init_module_dependencies())
1443         {
1444                 DBPRINTF ("Unable to init module dependencies\n");
1445                 return -1;
1446         }
1447
1448         return register_die_notifier (&kprobe_exceptions_nb);
1449 }
1450
1451 void __exit dbi_arch_exit_kprobes (void)
1452 {
1453         unregister_die_notifier (&kprobe_exceptions_nb);
1454 }
1455
1456 //EXPORT_SYMBOL_GPL (dbi_arch_uprobe_return);
1457 //EXPORT_SYMBOL_GPL (dbi_arch_exit_kprobes);