[REFACTOR] move register undef_hook for US in uprobe module
[kernel/swap-modules.git] / kprobe / arch / asm-arm / dbi_kprobes.c
1 /*
2  *  Dynamic Binary Instrumentation Module based on KProbes
3  *  modules/kprobe/arch/asm-arm/dbi_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) Samsung Electronics, 2006-2010
20  *
21  * 2006-2007    Ekaterina Gorelkina <e.gorelkina@samsung.com>: initial implementation for ARM/MIPS
22  * 2008-2009    Alexey Gerenkov <a.gerenkov@samsung.com> User-Space
23  *              Probes initial implementation; Support x86.
24  * 2010         Ekaterina Gorelkina <e.gorelkina@samsung.com>: redesign module for separating core and arch parts
25  * 2010-2011    Alexander Shirshikov <a.shirshikov@samsung.com>: initial implementation for Thumb
26  * 2012         Stanislav Andreev <s.andreev@samsung.com>: added time debug profiling support; BUG() message fix
27  * 2012         Stanislav Andreev <s.andreev@samsung.com>: redesign of kprobe functionality -
28  *              kprobe_handler() now called via undefined instruction hooks
29  * 2012         Stanislav Andreev <s.andreev@samsung.com>: hash tables search implemented for uprobes
30  */
31
32 #include <linux/module.h>
33 #include <linux/mm.h>
34
35 #include "dbi_kprobes.h"
36 #include "dbi_kprobes_arm.h"
37 #include "dbi_kprobes_thumb.h"
38 #include "../dbi_kprobes.h"
39 #include "../../dbi_kprobes.h"
40
41 #include "../../dbi_kdebug.h"
42 #include "../../dbi_insn_slots.h"
43 #include "../../dbi_kprobes_deps.h"
44 #include <ksyms.h>
45
46 #include <asm/cacheflush.h>
47
48 #ifdef TRAP_OVERHEAD_DEBUG
49 #include <linux/pid.h>
50 #include <linux/signal.h>
51 #endif
52
53 #ifdef OVERHEAD_DEBUG
54 #include <linux/time.h>
55 #endif
56
57 #include <asm/traps.h>
58 #include <asm/ptrace.h>
59 #include <linux/list.h>
60 #include <linux/hash.h>
61
62 #define SUPRESS_BUG_MESSAGES
63
64 extern struct kprobe * per_cpu__current_kprobe;
65 extern struct hlist_head kprobe_table[KPROBE_TABLE_SIZE];
66
67 static void (*__swap_register_undef_hook)(struct undef_hook *hook);
68 static void (*__swap_unregister_undef_hook)(struct undef_hook *hook);
69
70 #ifdef OVERHEAD_DEBUG
71 unsigned long swap_sum_time = 0;
72 unsigned long swap_sum_hit = 0;
73 EXPORT_SYMBOL_GPL (swap_sum_time);
74 EXPORT_SYMBOL_GPL (swap_sum_hit);
75 #endif
76
77 static unsigned int arr_traps_template[] = {
78                 0xe1a0c00d,    // mov          ip, sp
79                 0xe92dd800,    // stmdb        sp!, {fp, ip, lr, pc}
80                 0xe24cb004,    // sub          fp, ip, #4      ; 0x4
81                 0x00000000,    // b
82                 0xe3500000,    // cmp          r0, #0  ; 0x0
83                 0xe89da800,    // ldmia        sp, {fp, sp, pc}
84                 0x00000000,    // nop
85                 0xffffffff     // end
86 };
87
88
89 static struct kprobe trampoline_p =
90 {
91         .addr = (kprobe_opcode_t *) & kretprobe_trampoline,
92         .pre_handler = trampoline_probe_handler
93 };
94
95 // is instruction Thumb2 and NOT a branch, etc...
96 int isThumb2(kprobe_opcode_t insn)
97 {
98         if((    (insn & 0xf800) == 0xe800 ||
99                 (insn & 0xf800) == 0xf000 ||
100                 (insn & 0xf800) == 0xf800)) return 1;
101         return 0;
102 }
103 EXPORT_SYMBOL_GPL(isThumb2);
104
105 int prep_pc_dep_insn_execbuf(kprobe_opcode_t *insns, kprobe_opcode_t insn, int uregs)
106 {
107         int i;
108
109         if (uregs & 0x10)
110         {
111                 int reg_mask = 0x1;
112                 //search in reg list
113                 for (i = 0; i < 13; i++, reg_mask <<= 1)
114                 {
115                         if (!(insn & reg_mask))
116                                 break;
117                 }
118         }
119         else
120         {
121                 for (i = 0; i < 13; i++)
122                 {
123                         if ((uregs & 0x1) && (ARM_INSN_REG_RN (insn) == i))
124                                 continue;
125                         if ((uregs & 0x2) && (ARM_INSN_REG_RD (insn) == i))
126                                 continue;
127                         if ((uregs & 0x4) && (ARM_INSN_REG_RS (insn) == i))
128                                 continue;
129                         if ((uregs & 0x8) && (ARM_INSN_REG_RM (insn) == i))
130                                 continue;
131                         break;
132                 }
133         }
134         if (i == 13)
135         {
136                 DBPRINTF ("there are no free register %x in insn %lx!", uregs, insn);
137                 return -EINVAL;
138         }
139         DBPRINTF ("prep_pc_dep_insn_execbuf: using R%d, changing regs %x", i, uregs);
140
141         // set register to save
142         ARM_INSN_REG_SET_RD (insns[0], i);
143         // set register to load address to
144         ARM_INSN_REG_SET_RD (insns[1], i);
145         // set instruction to execute and patch it
146         if (uregs & 0x10)
147         {
148                 ARM_INSN_REG_CLEAR_MR (insn, 15);
149                 ARM_INSN_REG_SET_MR (insn, i);
150         }
151         else
152         {
153                 if ((uregs & 0x1) && (ARM_INSN_REG_RN (insn) == 15))
154                         ARM_INSN_REG_SET_RN (insn, i);
155                 if ((uregs & 0x2) && (ARM_INSN_REG_RD (insn) == 15))
156                         ARM_INSN_REG_SET_RD (insn, i);
157                 if ((uregs & 0x4) && (ARM_INSN_REG_RS (insn) == 15))
158                         ARM_INSN_REG_SET_RS (insn, i);
159                 if ((uregs & 0x8) && (ARM_INSN_REG_RM (insn) == 15))
160                         ARM_INSN_REG_SET_RM (insn, i);
161         }
162         insns[UPROBES_TRAMP_INSN_IDX] = insn;
163         // set register to restore
164         ARM_INSN_REG_SET_RD (insns[3], i);
165         return 0;
166 }
167 EXPORT_SYMBOL_GPL(prep_pc_dep_insn_execbuf);
168
169 int arch_check_insn_arm(struct arch_specific_insn *ainsn)
170 {
171         int ret = 0;
172
173         // check instructions that can change PC by nature
174         if (
175 //              ARM_INSN_MATCH (UNDEF, ainsn->insn_arm[0]) ||
176                 ARM_INSN_MATCH (AUNDEF, ainsn->insn_arm[0]) ||
177                 ARM_INSN_MATCH (SWI, ainsn->insn_arm[0]) ||
178                 ARM_INSN_MATCH (BREAK, ainsn->insn_arm[0]) ||
179                 ARM_INSN_MATCH (BL, ainsn->insn_arm[0]) ||
180                 ARM_INSN_MATCH (BLX1, ainsn->insn_arm[0]) ||
181                 ARM_INSN_MATCH (BLX2, ainsn->insn_arm[0]) ||
182                 ARM_INSN_MATCH (BX, ainsn->insn_arm[0]) ||
183                 ARM_INSN_MATCH (BXJ, ainsn->insn_arm[0]))
184         {
185                 DBPRINTF ("Bad insn arch_check_insn_arm: %lx\n", ainsn->insn_arm[0]);
186                 ret = -EFAULT;
187         }
188 #ifndef CONFIG_CPU_V7
189         // check instructions that can write result to PC
190         else if ((ARM_INSN_MATCH (DPIS, ainsn->insn_arm[0]) ||
191                                 ARM_INSN_MATCH (DPRS, ainsn->insn_arm[0]) ||
192                                 ARM_INSN_MATCH (DPI, ainsn->insn_arm[0]) ||
193                                 ARM_INSN_MATCH (LIO, ainsn->insn_arm[0]) ||
194                                 ARM_INSN_MATCH (LRO, ainsn->insn_arm[0])) &&
195                         (ARM_INSN_REG_RD (ainsn->insn_arm[0]) == 15))
196         {
197                 DBPRINTF ("Bad arch_check_insn_arm: %lx\n", ainsn->insn_arm[0]);
198                 ret = -EFAULT;
199         }
200 #endif // CONFIG_CPU_V7
201         // check special instruction loads store multiple registers
202         else if ((ARM_INSN_MATCH (LM, ainsn->insn_arm[0]) || ARM_INSN_MATCH (SM, ainsn->insn_arm[0])) &&
203                         // store pc or load to pc
204                         (ARM_INSN_REG_MR (ainsn->insn_arm[0], 15) ||
205                          // store/load with pc update
206                          ((ARM_INSN_REG_RN (ainsn->insn_arm[0]) == 15) && (ainsn->insn_arm[0] & 0x200000))))
207         {
208                 DBPRINTF ("Bad insn arch_check_insn_arm: %lx\n", ainsn->insn_arm[0]);
209                 ret = -EFAULT;
210         }
211         return ret;
212 }
213 EXPORT_SYMBOL_GPL(arch_check_insn_arm);
214
215 int arch_prepare_kretprobe (struct kretprobe *p)
216 {
217         DBPRINTF("Warrning: arch_prepare_kretprobe is not implemented\n");
218         return 0;
219 }
220
221 int arch_prepare_kprobe (struct kprobe *p)
222 {
223         kprobe_opcode_t insns[KPROBES_TRAMP_LEN];
224         int uregs, pc_dep, ret = 0;
225     kprobe_opcode_t insn[MAX_INSN_SIZE];
226     struct arch_specific_insn ainsn;
227
228     /* insn: must be on special executable page on i386. */
229     p->ainsn.insn = get_insn_slot (NULL, 0);
230     if (!p->ainsn.insn)
231         return -ENOMEM;
232
233     memcpy (insn, p->addr, MAX_INSN_SIZE * sizeof (kprobe_opcode_t));
234     ainsn.insn_arm = ainsn.insn = insn;
235     ret = arch_check_insn_arm (&ainsn);
236     if (!ret)
237     {
238         p->opcode = *p->addr;
239         uregs = pc_dep = 0;
240
241         // Rn, Rm ,Rd
242         if(ARM_INSN_MATCH (DPIS, insn[0]) || ARM_INSN_MATCH (LRO, insn[0]) ||
243            ARM_INSN_MATCH (SRO, insn[0]))
244         {
245             uregs = 0xb;
246             if( (ARM_INSN_REG_RN (insn[0]) == 15) || (ARM_INSN_REG_RM (insn[0]) == 15) ||
247                 (ARM_INSN_MATCH (SRO, insn[0]) && (ARM_INSN_REG_RD (insn[0]) == 15)) )
248             {
249                 DBPRINTF ("Unboostable insn %lx, DPIS/LRO/SRO\n", insn[0]);
250                 pc_dep = 1;
251             }
252         }
253         // Rn ,Rd
254         else if(ARM_INSN_MATCH (DPI, insn[0]) || ARM_INSN_MATCH (LIO, insn[0]) ||
255                 ARM_INSN_MATCH (SIO, insn[0]))
256         {
257             uregs = 0x3;
258             if ((ARM_INSN_REG_RN (insn[0]) == 15) || (ARM_INSN_MATCH (SIO, insn[0]) &&
259                         (ARM_INSN_REG_RD (insn[0]) == 15)))
260             {
261                 pc_dep = 1;
262                 DBPRINTF ("Unboostable insn %lx/%p, DPI/LIO/SIO\n", insn[0], p);
263             }
264         }
265         // Rn, Rm, Rs
266         else if(ARM_INSN_MATCH (DPRS, insn[0]))
267         {
268             uregs = 0xd;
269             if ((ARM_INSN_REG_RN (insn[0]) == 15) || (ARM_INSN_REG_RM (insn[0]) == 15) ||
270                 (ARM_INSN_REG_RS (insn[0]) == 15))
271             {
272                 pc_dep = 1;
273                 DBPRINTF ("Unboostable insn %lx, DPRS\n", insn[0]);
274             }
275         }
276         // register list
277         else if(ARM_INSN_MATCH (SM, insn[0]))
278         {
279             uregs = 0x10;
280             if (ARM_INSN_REG_MR (insn[0], 15))
281             {
282                 DBPRINTF ("Unboostable insn %lx, SM\n", insn[0]);
283                 pc_dep = 1;
284             }
285         }
286         // check instructions that can write result to SP andu uses PC
287         if (pc_dep  && (ARM_INSN_REG_RD (ainsn.insn[0]) == 13))
288         {
289             free_insn_slot(&kprobe_insn_pages, NULL, p->ainsn.insn);
290             ret = -EFAULT;
291         }
292         else
293         {
294             if (uregs && pc_dep)
295             {
296                 memcpy (insns, pc_dep_insn_execbuf, sizeof (insns));
297                 if (prep_pc_dep_insn_execbuf (insns, insn[0], uregs) != 0)
298                 {
299                     DBPRINTF ("failed to prepare exec buffer for insn %lx!", insn[0]);
300                     free_insn_slot(&kprobe_insn_pages, NULL, p->ainsn.insn);
301                     return -EINVAL;
302                 }
303                 insns[6] = (kprobe_opcode_t) (p->addr + 2);
304             }
305             else
306             {
307                 memcpy (insns, gen_insn_execbuf, sizeof (insns));
308                 insns[KPROBES_TRAMP_INSN_IDX] = insn[0];
309             }
310             insns[7] = (kprobe_opcode_t) (p->addr + 1);
311             DBPRINTF ("arch_prepare_kprobe: insn %lx", insn[0]);
312             DBPRINTF ("arch_prepare_kprobe: to %p - %lx %lx %lx %lx %lx %lx %lx %lx %lx",
313                     p->ainsn.insn, insns[0], insns[1], insns[2], insns[3], insns[4],
314                     insns[5], insns[6], insns[7], insns[8]);
315             memcpy (p->ainsn.insn, insns, sizeof(insns));
316             flush_icache_range((long unsigned)p->ainsn.insn, (long unsigned)(p->ainsn.insn) + sizeof(insns));
317 #ifdef BOARD_tegra
318             flush_cache_all();
319 #endif
320         }
321     }
322     else
323     {
324         free_insn_slot(&kprobe_insn_pages, NULL, p->ainsn.insn);
325         printk("arch_prepare_kprobe: instruction 0x%lx not instrumentation, addr=0x%p\n", insn[0], p->addr);
326     }
327
328     return ret;
329 }
330
331 static unsigned int arch_construct_brunch (unsigned int base, unsigned int addr, int link)
332 {
333         kprobe_opcode_t insn;
334         unsigned int bpi = (unsigned int) base - (unsigned int) addr - 8;
335
336         insn = bpi >> 2;
337         DBPRINTF ("base=%x addr=%x base-addr-8=%x\n", base, addr, bpi);
338         if (abs (insn & 0xffffff) > 0xffffff)
339         {
340                 DBPRINTF ("ERROR: kprobe address out of range\n");
341                 BUG ();
342         }
343         insn = insn & 0xffffff;
344         insn = insn | ((link != 0) ? 0xeb000000 : 0xea000000);
345         DBPRINTF ("insn=%lX\n", insn);
346         return (unsigned int) insn;
347 }
348
349 int arch_prepare_uretprobe (struct kretprobe *p, struct task_struct *task)
350 {
351         DBPRINTF("Warrning: arch_prepare_uretprobe is not implemented\n");
352         return 0;
353 }
354 EXPORT_SYMBOL_GPL(arch_prepare_uretprobe);
355
356 void prepare_singlestep (struct kprobe *p, struct pt_regs *regs)
357 {
358         if (p->ss_addr) {
359                 regs->ARM_pc = (unsigned long)p->ss_addr;
360                 p->ss_addr = NULL;
361         } else {
362                 regs->ARM_pc = (unsigned long)p->ainsn.insn;
363         }
364 }
365
366 void save_previous_kprobe(struct kprobe_ctlblk *kcb, struct kprobe *p_run)
367 {
368         if (p_run == NULL) {
369                 panic("arm_save_previous_kprobe: p_run == NULL\n");
370         }
371
372         if (kcb->prev_kprobe.kp != NULL) {
373                 DBPRINTF ("no space to save new probe[]: task = %d/%s", current->pid, current->comm);
374         }
375
376         kcb->prev_kprobe.kp = p_run;
377         kcb->prev_kprobe.status = kcb->kprobe_status;
378 }
379
380 void restore_previous_kprobe(struct kprobe_ctlblk *kcb)
381 {
382         set_current_kprobe(kcb->prev_kprobe.kp, NULL, NULL);
383         kcb->kprobe_status = kcb->prev_kprobe.status;
384         kcb->prev_kprobe.kp = NULL;
385         kcb->prev_kprobe.status = 0;
386 }
387
388 void set_current_kprobe(struct kprobe *p, struct pt_regs *regs, struct kprobe_ctlblk *kcb)
389 {
390         __get_cpu_var(current_kprobe) = p;
391         DBPRINTF ("set_current_kprobe: p=%p addr=%p\n", p, p->addr);
392 }
393
394 static int check_validity_insn(struct kprobe *p, struct pt_regs *regs, struct task_struct *task)
395 {
396         struct kprobe *kp;
397
398         if (unlikely(thumb_mode(regs))) {
399                 if (p->safe_thumb != -1) {
400                         p->ainsn.insn = p->ainsn.insn_thumb;
401                         list_for_each_entry_rcu(kp, &p->list, list) {
402                                 kp->ainsn.insn = p->ainsn.insn_thumb;
403                         }
404                 } else {
405                         printk("Error in %s at %d: we are in thumb mode (!) and check instruction was fail \
406                                 (%0lX instruction at %p address)!\n", __FILE__, __LINE__, p->opcode, p->addr);
407                         // Test case when we do our actions on already running application
408                         arch_disarm_uprobe(p, task);
409                         return -1;
410                 }
411         } else {
412                 if (p->safe_arm != -1) {
413                         p->ainsn.insn = p->ainsn.insn_arm;
414                         list_for_each_entry_rcu(kp, &p->list, list) {
415                                 kp->ainsn.insn = p->ainsn.insn_arm;
416                         }
417                 } else {
418                         printk("Error in %s at %d: we are in arm mode (!) and check instruction was fail \
419                                 (%0lX instruction at %p address)!\n", __FILE__, __LINE__, p->opcode, p->addr);
420                         // Test case when we do our actions on already running application
421                         arch_disarm_uprobe(p, task);
422                         return -1;
423                 }
424         }
425
426         return 0;
427 }
428
429 #ifdef TRAP_OVERHEAD_DEBUG
430 static unsigned long trap_handler_counter_debug = 0;
431 #define SAMPLING_COUNTER                               100000
432 #endif
433
434 static int kprobe_handler(struct pt_regs *regs)
435 {
436         int err_out = 0;
437         char *msg_out = NULL;
438         unsigned long user_m = user_mode(regs);
439         pid_t tgid = (user_m) ? current->tgid : 0;
440         kprobe_opcode_t *addr = (kprobe_opcode_t *) (regs->ARM_pc);
441
442         struct kprobe *p = NULL, *p_run = NULL;
443         int ret = 0, retprobe = 0, reenter = 0;
444         kprobe_opcode_t *ssaddr = NULL;
445         struct kprobe_ctlblk *kcb;
446
447 #ifdef SUPRESS_BUG_MESSAGES
448         int swap_oops_in_progress;
449         // oops_in_progress used to avoid BUG() messages that slow down kprobe_handler() execution
450         swap_oops_in_progress = oops_in_progress;
451         oops_in_progress = 1;
452 #endif
453 #ifdef TRAP_OVERHEAD_DEBUG
454         trap_handler_counter_debug++;
455         if ( trap_handler_counter_debug < SAMPLING_COUNTER ) {
456                 err_out = 0;
457         }
458         else {
459                 // XXX NOTE - user must care about catching signal via signal handler to avoid hanging!
460                 printk("Trap %ld reached - send SIGUSR1\n", trap_handler_counter_debug);
461                 kill_pid(get_task_pid(current, PIDTYPE_PID), SIGUSR1, 1);
462                 trap_handler_counter_debug = 0;
463                 err_out = 0;
464         }
465         return err_out;
466 #endif
467 #ifdef OVERHEAD_DEBUG
468         struct timeval swap_tv1;
469         struct timeval swap_tv2;
470 #define USEC_IN_SEC_NUM                         1000000
471         do_gettimeofday(&swap_tv1);
472 #endif
473         preempt_disable();
474
475 //      printk("### kprobe_handler: task[tgid=%u (%s)] addr=%p\n", tgid, current->comm, addr);
476         p = get_kprobe(addr, tgid);
477
478         if (user_m && p && (check_validity_insn(p, regs, current) != 0)) {
479                 goto no_kprobe_live;
480         }
481
482         /* We're in an interrupt, but this is clear and BUG()-safe. */
483         kcb = get_kprobe_ctlblk ();
484
485         /* Check we're not actually recursing */
486         // TODO: event is not saving in trace
487         p_run = kprobe_running();
488         if (p_run)
489         {
490                 DBPRINTF("lock???");
491                 if (p)
492                 {
493                         if (!tgid && (addr == (kprobe_opcode_t *)kretprobe_trampoline)) {
494                                 save_previous_kprobe(kcb, p_run);
495                                 kcb->kprobe_status = KPROBE_REENTER;
496                                 reenter = 1;
497                         } else {
498                                 /* We have reentered the kprobe_handler(), since
499                                  * another probe was hit while within the handler.
500                                  * We here save the original kprobes variables and
501                                  * just single step on the instruction of the new probe
502                                  * without calling any user handlers.
503                                  */
504                                 kprobes_inc_nmissed_count (p);
505                                 prepare_singlestep (p, regs);
506
507                                 err_out = 0;
508                                 goto out;
509                         }
510                 } else {
511                         if(tgid) { //we can reenter probe upon uretprobe exception
512                                 DBPRINTF ("check for UNDEF_INSTRUCTION %p\n", addr);
513                                 // UNDEF_INSTRUCTION from user space
514
515                                 p = get_kprobe_by_insn_slot(addr, tgid, regs);
516                                 if (p) {
517                                         save_previous_kprobe(kcb, p_run);
518                                         kcb->kprobe_status = KPROBE_REENTER;
519                                         reenter = 1;
520                                         retprobe = 1;
521                                         DBPRINTF ("uretprobe %p\n", addr);
522                                 }
523                         }
524                         if(!p) {
525                                 p = p_run;
526                                 DBPRINTF ("kprobe_running !!! p = 0x%p p->break_handler = 0x%p", p, p->break_handler);
527                                 /*if (p->break_handler && p->break_handler(p, regs)) {
528                                   DBPRINTF("kprobe_running !!! goto ss");
529                                   goto ss_probe;
530                                   } */
531                                 DBPRINTF ("unknown uprobe at %p cur at %p/%p\n", addr, p->addr, p->ainsn.insn);
532                                 if (tgid)
533                                         ssaddr = p->ainsn.insn + UPROBES_TRAMP_SS_BREAK_IDX;
534                                 else
535                                         ssaddr = p->ainsn.insn + KPROBES_TRAMP_SS_BREAK_IDX;
536                                 if (addr == ssaddr) {
537                                         regs->ARM_pc = (unsigned long) (p->addr + 1);
538                                         DBPRINTF ("finish step at %p cur at %p/%p, redirect to %lx\n", addr, p->addr, p->ainsn.insn, regs->ARM_pc);
539                                         if (kcb->kprobe_status == KPROBE_REENTER) {
540                                                 restore_previous_kprobe(kcb);
541                                         } else {
542                                                 reset_current_kprobe();
543                                         }
544                                 }
545                                 DBPRINTF ("kprobe_running !!! goto no");
546                                 ret = 1;
547                                 /* If it's not ours, can't be delete race, (we hold lock). */
548                                 DBPRINTF ("no_kprobe");
549                                 goto no_kprobe;
550                         }
551                 }
552         }
553
554         if (!p) {
555                 if (tgid) {
556                         DBPRINTF ("search UNDEF_INSTRUCTION %p\n", addr);
557                         // UNDEF_INSTRUCTION from user space
558
559                         p = get_kprobe_by_insn_slot(addr, tgid, regs);
560                         if (!p) {
561                                 /* Not one of ours: let kernel handle it */
562                                 DBPRINTF ("no_kprobe");
563                                 goto no_kprobe;
564                         }
565                         retprobe = 1;
566                         DBPRINTF ("uretprobe %p\n", addr);
567                 } else {
568                         /* Not one of ours: let kernel handle it */
569                         DBPRINTF ("no_kprobe");
570                         goto no_kprobe;
571                 }
572         }
573         // restore opcode for thumb app
574         if (user_mode( regs ) && thumb_mode( regs )) {
575                 if (!isThumb2(p->opcode)) {
576                         unsigned long tmp = p->opcode >> 16;
577                         write_proc_vm_atomic(current, (unsigned long)((unsigned short*)p->addr + 1), &tmp, 2);
578
579                         // "2*sizeof(kprobe_opcode_t)" - strange. Should be "sizeof(kprobe_opcode_t)", need to test
580                         flush_icache_range((unsigned int) p->addr, ((unsigned int)p->addr) + (2 * sizeof(kprobe_opcode_t)));
581                 }
582         }
583         set_current_kprobe(p, NULL, NULL);
584         if(!reenter)
585                 kcb->kprobe_status = KPROBE_HIT_ACTIVE;
586         if (retprobe) {         //(einsn == UNDEF_INSTRUCTION)
587                 ret = trampoline_probe_handler (p, regs);
588         } else if (p->pre_handler) {
589                 ret = p->pre_handler (p, regs);
590                 if(p->pre_handler != trampoline_probe_handler) {
591                         reset_current_kprobe();
592                 }
593         }
594
595         if (ret) {
596                 /* handler has already set things up, so skip ss setup */
597                 err_out = 0;
598                 goto out;
599         }
600
601 no_kprobe:
602         msg_out = "no_kprobe\n";
603         err_out = 1;            // return with death
604         goto out;
605
606 no_kprobe_live:
607         msg_out = "no_kprobe live\n";
608         err_out = 0;            // ok - life is life
609         goto out;
610
611 out:
612         preempt_enable_no_resched();
613 #ifdef OVERHEAD_DEBUG
614         do_gettimeofday(&swap_tv2);
615         swap_sum_hit++;
616         swap_sum_time += ((swap_tv2.tv_sec - swap_tv1.tv_sec) *  USEC_IN_SEC_NUM +
617                 (swap_tv2.tv_usec - swap_tv1.tv_usec));
618 #endif
619 #ifdef SUPRESS_BUG_MESSAGES
620         oops_in_progress = swap_oops_in_progress;
621 #endif
622
623         if(msg_out) {
624                 printk(msg_out);
625         }
626
627         return err_out;
628 }
629
630 int kprobe_trap_handler(struct pt_regs *regs, unsigned int instr)
631 {
632         int ret;
633         unsigned long flags;
634         local_irq_save(flags);
635         ret = kprobe_handler(regs);
636         local_irq_restore(flags);
637         return ret;
638 }
639 EXPORT_SYMBOL_GPL(kprobe_trap_handler);
640
641 int setjmp_pre_handler (struct kprobe *p, struct pt_regs *regs)
642 {
643         struct jprobe *jp = container_of (p, struct jprobe, kp);
644         kprobe_pre_entry_handler_t pre_entry;
645         entry_point_t entry;
646
647 # ifdef REENTER
648 //      p = kprobe_running(regs);
649 # endif
650
651         DBPRINTF ("pjp = 0x%p jp->entry = 0x%p", jp, jp->entry);
652         entry = (entry_point_t) jp->entry;
653         pre_entry = (kprobe_pre_entry_handler_t) jp->pre_entry;
654         //if(!entry)
655         //      DIE("entry NULL", regs)
656         DBPRINTF ("entry = 0x%p jp->entry = 0x%p", entry, jp->entry);
657
658         //call handler for all kernel probes and user space ones which belong to current tgid
659         if (!p->tgid || (p->tgid == current->tgid))
660         {
661                 if(!p->tgid && ((unsigned int)p->addr == sched_addr) && sched_rp) {
662                         struct thread_info *tinfo = (struct thread_info *)regs->ARM_r2;
663                         patch_suspended_task(sched_rp, tinfo->task);
664                 }
665                 if (pre_entry)
666                         p->ss_addr = (void *)pre_entry (jp->priv_arg, regs);
667                 if (entry){
668                         entry (regs->ARM_r0, regs->ARM_r1, regs->ARM_r2, regs->ARM_r3, regs->ARM_r4, regs->ARM_r5);
669                 }
670                 else {
671                         if (p->tgid)
672                                 dbi_arch_uprobe_return ();
673                         else
674                                 dbi_jprobe_return ();
675                 }
676         }
677         else if (p->tgid)
678                 dbi_arch_uprobe_return ();
679
680         prepare_singlestep (p, regs);
681
682         return 1;
683 }
684 EXPORT_SYMBOL_GPL(setjmp_pre_handler);
685
686 void dbi_jprobe_return (void)
687 {
688 }
689
690 void dbi_arch_uprobe_return (void)
691 {
692 }
693 EXPORT_SYMBOL_GPL(dbi_arch_uprobe_return);
694
695 int longjmp_break_handler (struct kprobe *p, struct pt_regs *regs)
696 {
697 # ifndef REENTER
698         //kprobe_opcode_t insn = BREAKPOINT_INSTRUCTION;
699         kprobe_opcode_t insns[2];
700
701         if (p->pid)
702         {
703                 insns[0] = BREAKPOINT_INSTRUCTION;
704                 insns[1] = p->opcode;
705                 //p->opcode = *p->addr;
706                 if (read_proc_vm_atomic (current, (unsigned long) (p->addr), &(p->opcode), sizeof (p->opcode)) < sizeof (p->opcode))
707                 {
708                         printk ("ERROR[%lu]: failed to read vm of proc %s/%u addr %p.", nCount, current->comm, current->pid, p->addr);
709                         return -1;
710                 }
711                 //*p->addr = BREAKPOINT_INSTRUCTION;
712                 //*(p->addr+1) = p->opcode;
713                 if (write_proc_vm_atomic (current, (unsigned long) (p->addr), insns, sizeof (insns)) < sizeof (insns))
714                 {
715                         printk ("ERROR[%lu]: failed to write vm of proc %s/%u addr %p.", nCount, current->comm, current->pid, p->addr);
716                         return -1;
717                 }
718         }
719         else
720         {
721                 DBPRINTF ("p->opcode = 0x%lx *p->addr = 0x%lx p->addr = 0x%p\n", p->opcode, *p->addr, p->addr);
722                 *(p->addr + 1) = p->opcode;
723                 p->opcode = *p->addr;
724                 *p->addr = BREAKPOINT_INSTRUCTION;
725
726                 flush_icache_range ((unsigned int) p->addr, (unsigned int) (((unsigned int) p->addr) + (sizeof (kprobe_opcode_t) * 2)));
727         }
728
729         reset_current_kprobe();
730
731 #endif //REENTER
732
733         return 0;
734 }
735 EXPORT_SYMBOL_GPL(longjmp_break_handler);
736
737 void arch_arm_kprobe (struct kprobe *p)
738 {
739         *p->addr = BREAKPOINT_INSTRUCTION;
740         flush_icache_range ((unsigned long) p->addr, (unsigned long) p->addr + sizeof (kprobe_opcode_t));
741 }
742
743 void arch_disarm_kprobe (struct kprobe *p)
744 {
745         *p->addr = p->opcode;
746         flush_icache_range ((unsigned long) p->addr, (unsigned long) p->addr + sizeof (kprobe_opcode_t));
747 }
748
749
750 int trampoline_probe_handler (struct kprobe *p, struct pt_regs *regs)
751 {
752         struct kretprobe_instance *ri = NULL;
753         struct hlist_head *head;
754         struct hlist_node *node, *tmp;
755         unsigned long flags, orig_ret_address = 0;
756         unsigned long trampoline_address = (unsigned long) &kretprobe_trampoline;
757
758         struct kretprobe *crp = NULL;
759         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
760
761         DBPRINTF ("start");
762
763         if (p && p->tgid){
764                 // in case of user space retprobe trampoline is at the Nth instruction of US tramp
765                 if (!thumb_mode( regs ))
766                         trampoline_address = (unsigned long)(p->ainsn.insn + UPROBES_TRAMP_RET_BREAK_IDX);
767                 else
768                         trampoline_address = (unsigned long)(p->ainsn.insn) + 0x1b;
769         }
770
771         spin_lock_irqsave (&kretprobe_lock, flags);
772
773         /*
774          * We are using different hash keys (current and mm) for finding kernel
775          * space and user space probes.  Kernel space probes can change mm field in
776          * task_struct.  User space probes can be shared between threads of one
777          * process so they have different current but same mm.
778          */
779         if (p && p->tgid) {
780                 head = kretprobe_inst_table_head(current->mm);
781         } else {
782                 head = kretprobe_inst_table_head(current);
783         }
784
785         /*
786          * It is possible to have multiple instances associated with a given
787          * task either because an multiple functions in the call path
788          * have a return probe installed on them, and/or more then one
789          * return probe was registered for a target function.
790          *
791          * We can handle this because:
792          *     - instances are always inserted at the head of the list
793          *     - when multiple return probes are registered for the same
794          *       function, the first instance's ret_addr will point to the
795          *       real return address, and all the rest will point to
796          *       kretprobe_trampoline
797          */
798         hlist_for_each_entry_safe (ri, node, tmp, head, hlist)
799         {
800                 if (ri->task != current)
801                         /* another task is sharing our hash bucket */
802                         continue;
803                 if (ri->rp && ri->rp->handler){
804                         ri->rp->handler (ri, regs, ri->rp->priv_arg);
805                 }
806
807                 orig_ret_address = (unsigned long) ri->ret_addr;
808                 recycle_rp_inst (ri);
809                 if (orig_ret_address != trampoline_address)
810                         /*
811                          * This is the real return address. Any other
812                          * instances associated with this task are for
813                          * other calls deeper on the call stack
814                          */
815                         break;
816         }
817         kretprobe_assert (ri, orig_ret_address, trampoline_address);
818         //BUG_ON(!orig_ret_address || (orig_ret_address == trampoline_address));
819         //E.G. Check this code in case of __switch_to function instrumentation -- currently this code generates dump in this case
820         //if (trampoline_address != (unsigned long) &kretprobe_trampoline){
821         //if (ri->rp2) BUG_ON (ri->rp2->kp.tgid == 0);
822         //if (ri->rp) BUG_ON (ri->rp->kp.tgid == 0);
823         //else if (ri->rp2) BUG_ON (ri->rp2->kp.tgid == 0);
824         //}
825         if ((ri->rp && ri->rp->kp.tgid) || (ri->rp2 && ri->rp2->kp.tgid))
826                 BUG_ON (trampoline_address == (unsigned long) &kretprobe_trampoline);
827
828         regs->uregs[14] = orig_ret_address;
829         DBPRINTF ("regs->uregs[14] = 0x%lx\n", regs->uregs[14]);
830         DBPRINTF ("regs->uregs[15] = 0x%lx\n", regs->uregs[15]);
831
832         if (trampoline_address != (unsigned long) &kretprobe_trampoline)
833         {
834                 regs->uregs[15] = orig_ret_address;
835         }else{
836                 if (!thumb_mode( regs )) regs->uregs[15] += 4;
837                 else regs->uregs[15] += 2;
838         }
839
840         DBPRINTF ("regs->uregs[15] = 0x%lx\n", regs->uregs[15]);
841
842         if(p){ // ARM, MIPS, X86 user space
843                 if (thumb_mode( regs ) && !(regs->uregs[14] & 0x01))
844                 {
845                         regs->ARM_cpsr &= 0xFFFFFFDF;
846                 }else{
847                         if (user_mode( regs ) && (regs->uregs[14] & 0x01))
848                         {
849                                 regs->ARM_cpsr |= 0x20;
850                         }
851                 }
852
853                 //TODO: test - enter function, delete us retprobe, exit function
854                 // for user space retprobes only - deferred deletion
855
856                 if (trampoline_address != (unsigned long) &kretprobe_trampoline)
857                 {
858                         // if we are not at the end of the list and current retprobe should be disarmed
859                         if (node && ri->rp2)
860                         {
861                                 struct hlist_node *current_node = node;
862                                 crp = ri->rp2;
863                                 /*sprintf(die_msg, "deferred disarm p->addr = %p [%lx %lx %lx]\n",
864                                   crp->kp.addr, *kaddrs[0], *kaddrs[1], *kaddrs[2]);
865                                   DIE(die_msg, regs); */
866                                 // look for other instances for the same retprobe
867                                 hlist_for_each_entry_safe (ri, node, tmp, head, hlist)
868                                 {
869                                         /*
870                                          * Trying to find another retprobe instance associated with
871                                          * the same retprobe.
872                                          */
873                                         if (ri->rp2 == crp && node != current_node)
874                                                 break;
875                                 }
876
877                                 if (!node)
878                                 {
879                                         // if there are no more instances for this retprobe
880                                         // delete retprobe
881                                         struct kprobe *is_p = &crp->kp;
882                                         DBPRINTF ("defered retprobe deletion p->addr = %p", crp->kp.addr);
883                                         /*
884                                           If there is no any retprobe instances of this retprobe
885                                           we can free the resources related to the probe.
886                                          */
887                                         if (!(hlist_unhashed(&is_p->is_hlist_arm))) {
888                                                 hlist_del_rcu(&is_p->is_hlist_arm);
889                                         }
890                                         if (!(hlist_unhashed(&is_p->is_hlist_thumb))) {
891                                                 hlist_del_rcu(&is_p->is_hlist_thumb);
892                                         }
893
894                                         dbi_unregister_kprobe(&crp->kp, current);
895                                         kfree (crp);
896                                 }
897                                 hlist_del(current_node);
898                         }
899                 }
900
901                 if (kcb->kprobe_status == KPROBE_REENTER) {
902                         restore_previous_kprobe(kcb);
903                 } else {
904                         reset_current_kprobe();
905                 }
906         }
907
908         spin_unlock_irqrestore (&kretprobe_lock, flags);
909
910         /*
911          * By returning a non-zero value, we are telling
912          * kprobe_handler() that we don't want the post_handler
913          * to run (and have re-enabled preemption)
914          */
915
916         return 1;
917 }
918
919 void  __arch_prepare_kretprobe (struct kretprobe *rp, struct pt_regs *regs)
920 {
921         struct kretprobe_instance *ri;
922
923         DBPRINTF ("start\n");
924         //TODO: test - remove retprobe after func entry but before its exit
925         if ((ri = get_free_rp_inst (rp)) != NULL)
926         {
927                 ri->rp = rp;
928                 ri->rp2 = NULL;
929                 ri->task = current;
930                 ri->ret_addr = (kprobe_opcode_t *) regs->uregs[14];
931                 ri->sp = (kprobe_opcode_t *)regs->ARM_sp; //uregs[13];
932
933                 if (rp->kp.tgid)
934                         if (!thumb_mode( regs ))
935                                 regs->uregs[14] = (unsigned long) (rp->kp.ainsn.insn + UPROBES_TRAMP_RET_BREAK_IDX);
936                         else
937                                 regs->uregs[14] = (unsigned long) (rp->kp.ainsn.insn) + 0x1b;
938
939                 else    /* Replace the return addr with trampoline addr */
940                         regs->uregs[14] = (unsigned long) &kretprobe_trampoline;
941
942 //              DBPRINTF ("ret addr set to %p->%lx\n", ri->ret_addr, regs->uregs[14]);
943                 add_rp_inst (ri);
944         }
945         else {
946                 DBPRINTF ("WARNING: missed retprobe %p\n", rp->kp.addr);
947                 rp->nmissed++;
948         }
949 }
950
951
952 int asm_init_module_dependencies(void)
953 {
954         //No module dependencies
955         return 0;
956 }
957
958 void swap_register_undef_hook(struct undef_hook *hook)
959 {
960         __swap_register_undef_hook(hook);
961 }
962 EXPORT_SYMBOL_GPL(swap_register_undef_hook);
963
964 void swap_unregister_undef_hook(struct undef_hook *hook)
965 {
966         __swap_unregister_undef_hook(hook);
967 }
968 EXPORT_SYMBOL_GPL(swap_unregister_undef_hook);
969
970 // kernel probes hook
971 static struct undef_hook undef_ho_k = {
972     .instr_mask = 0xffffffff,
973     .instr_val  = BREAKPOINT_INSTRUCTION,
974     .cpsr_mask  = MODE_MASK,
975     .cpsr_val   = SVC_MODE,
976     .fn         = kprobe_trap_handler
977 };
978
979 int __init arch_init_kprobes (void)
980 {
981         unsigned int do_bp_handler = 0;
982         int ret = 0;
983
984         if (arch_init_module_dependencies())
985         {
986                 DBPRINTF ("Unable to init module dependencies\n");
987                 return -1;
988         }
989
990         do_bp_handler = swap_ksyms("do_undefinstr");
991         if (do_bp_handler == 0) {
992                 DBPRINTF("no do_undefinstr symbol found!");
993                 return -1;
994         }
995         arr_traps_template[NOTIFIER_CALL_CHAIN_INDEX] = arch_construct_brunch ((unsigned int)kprobe_handler, do_bp_handler + NOTIFIER_CALL_CHAIN_INDEX * 4, 1);
996         // Register hooks (kprobe_handler)
997         __swap_register_undef_hook = swap_ksyms("register_undef_hook");
998         if (__swap_register_undef_hook == NULL) {
999                 printk("no register_undef_hook symbol found!\n");
1000                 return -1;
1001         }
1002
1003         // Unregister hooks (kprobe_handler)
1004         __swap_unregister_undef_hook = swap_ksyms("unregister_undef_hook");
1005         if (__swap_unregister_undef_hook == NULL) {
1006                 printk("no unregister_undef_hook symbol found!\n");
1007                 return -1;
1008         }
1009
1010         swap_register_undef_hook(&undef_ho_k);
1011         if ((ret = dbi_register_kprobe (&trampoline_p)) != 0) {
1012                 //dbi_unregister_jprobe(&do_exit_p, 0);
1013                 return ret;
1014         }
1015         return ret;
1016 }
1017
1018 void __exit dbi_arch_exit_kprobes (void)
1019 {
1020         swap_unregister_undef_hook(&undef_ho_k);
1021 }
1022
1023 //EXPORT_SYMBOL_GPL (dbi_arch_uprobe_return);
1024 //EXPORT_SYMBOL_GPL (dbi_arch_exit_kprobes);