[IMPROVE] split into uprobe core handlers (for x86)
[kernel/swap-modules.git] / uprobe / arch / x86 / swap-asm / swap_uprobes.c
1 /**
2  * uprobe/arch/asm-x86/swap_uprobes.c
3  * @author Alexey Gerenkov <a.gerenkov@samsung.com> User-Space Probes initial
4  * implementation; Support x86/ARM/MIPS for both user and kernel spaces.
5  * @author Ekaterina Gorelkina <e.gorelkina@samsung.com>: redesign module for
6  * separating core and arch parts
7  *
8  * @section LICENSE
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23  *
24  * @section COPYRIGHT
25  *
26  * Copyright (C) Samsung Electronics, 2006-2010
27  *
28  * @section DESCRIPTION
29  *
30  * Arch-dependent uprobe interface implementation for x86.
31  */
32
33
34 #include <linux/kdebug.h>
35
36 #include <kprobe/swap_slots.h>
37 #include <kprobe/swap_td_raw.h>
38 #include <uprobe/swap_uprobes.h>
39
40 #include "swap_uprobes.h"
41
42
43 struct save_context {
44         struct pt_regs save_regs;
45         struct pt_regs *ptr_regs;
46         unsigned long val;
47         int (*handler)(struct uprobe *, struct pt_regs *);
48 };
49
50 /**
51  * @struct uprobe_ctlblk
52  * @brief Uprobe control block
53  */
54 struct uprobe_ctlblk {
55         unsigned long flags;            /**< Flags */
56         struct uprobe *p;               /**< Pointer to the uprobe */
57
58         struct save_context ctx;
59 };
60
61
62 static struct td_raw td_raw;
63
64
65 static unsigned long trampoline_addr(struct uprobe *up)
66 {
67         return (unsigned long)(up->ainsn.insn +
68                                UPROBES_TRAMP_RET_BREAK_IDX);
69 }
70
71 unsigned long arch_tramp_by_ri(struct uretprobe_instance *ri)
72 {
73         return trampoline_addr(&ri->rp->up);
74 }
75
76 static struct uprobe_ctlblk *current_ucb(void)
77 {
78         return (struct uprobe_ctlblk *)swap_td_raw(&td_raw, current);
79 }
80
81 static struct save_context *current_ctx(void)
82 {
83         return &current_ucb()->ctx;
84 }
85
86 static struct uprobe *get_current_probe(void)
87 {
88         return current_ucb()->p;
89 }
90
91 static void set_current_probe(struct uprobe *p)
92 {
93         current_ucb()->p = p;
94 }
95
96 static void save_current_flags(struct pt_regs *regs)
97 {
98         current_ucb()->flags = regs->flags;
99 }
100
101 static void restore_current_flags(struct pt_regs *regs, unsigned long flags)
102 {
103         regs->flags &= ~IF_MASK;
104         regs->flags |= flags & IF_MASK;
105 }
106
107 /**
108  * @brief Prepares uprobe for x86.
109  *
110  * @param up Pointer to the uprobe.
111  * @return 0 on success,\n
112  * -1 on error.
113  */
114 int arch_prepare_uprobe(struct uprobe *p)
115 {
116         struct task_struct *task = p->task;
117         u8 tramp[UPROBES_TRAMP_LEN + BP_INSN_SIZE];     /* BP for uretprobe */
118         enum { call_relative_opcode = 0xe8 };
119
120         if (!read_proc_vm_atomic(task, (unsigned long)p->addr,
121                                  tramp, MAX_INSN_SIZE)) {
122                 printk(KERN_ERR "failed to read memory %p!\n", p->addr);
123                 return -EINVAL;
124         }
125         /* TODO: this is a workaround */
126         if (tramp[0] == call_relative_opcode) {
127                 printk(KERN_INFO "cannot install probe: 1st instruction is call\n");
128                 return -EINVAL;
129         }
130
131         tramp[UPROBES_TRAMP_RET_BREAK_IDX] = BREAKPOINT_INSTRUCTION;
132
133         p->opcode = tramp[0];
134         p->ainsn.boostable = swap_can_boost(tramp) ? 0 : -1;
135
136         p->ainsn.insn = swap_slot_alloc(p->sm);
137         if (p->ainsn.insn == NULL) {
138                 printk(KERN_ERR "trampoline out of memory\n");
139                 return -ENOMEM;
140         }
141
142         if (!write_proc_vm_atomic(task, (unsigned long)p->ainsn.insn,
143                                   tramp, sizeof(tramp))) {
144                 swap_slot_free(p->sm, p->ainsn.insn);
145                 printk(KERN_INFO "failed to write memory %p!\n", tramp);
146                 return -EINVAL;
147         }
148
149         /* for uretprobe */
150         add_uprobe_table(p);
151
152         return 0;
153 }
154
155 /**
156  * @brief Jump pre-handler.
157  *
158  * @param p Pointer to the uprobe.
159  * @param regs Pointer to CPU register data.
160  * @return 0.
161  */
162 int setjmp_upre_handler(struct uprobe *p, struct pt_regs *regs)
163 {
164         struct ujprobe *jp = container_of(p, struct ujprobe, up);
165         entry_point_t entry = (entry_point_t)jp->entry;
166         unsigned long args[6];
167
168         /* FIXME some user space apps crash if we clean interrupt bit */
169         /* regs->EREG(flags) &= ~IF_MASK; */
170 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 18)
171         trace_hardirqs_off();
172 #endif
173
174         /* read first 6 args from stack */
175         if (!read_proc_vm_atomic(current, regs->EREG(sp) + 4,
176                                  args, sizeof(args)))
177                 printk(KERN_WARNING
178                        "failed to read user space func arguments %lx!\n",
179                        regs->sp + 4);
180
181         if (entry)
182                 entry(args[0], args[1], args[2], args[3], args[4], args[5]);
183         else
184                 arch_ujprobe_return();
185
186         return 0;
187 }
188
189 /**
190  * @brief Prepares uretprobe for x86.
191  *
192  * @param ri Pointer to the uretprobe instance.
193  * @param regs Pointer to CPU register data.
194  * @return Void.
195  */
196 int arch_prepare_uretprobe(struct uretprobe_instance *ri, struct pt_regs *regs)
197 {
198         /* Replace the return addr with trampoline addr */
199         unsigned long ra = trampoline_addr(&ri->rp->up);
200         unsigned long ret_addr;
201         ri->sp = (kprobe_opcode_t *)regs->sp;
202
203         if (get_user(ret_addr, (unsigned long *)regs->sp)) {
204                 pr_err("failed to read user space func ra %lx addr=%p!\n",
205                        regs->sp, ri->rp->up.addr);
206                 return -EINVAL;
207         }
208
209         if (put_user(ra, (unsigned long *)regs->sp)) {
210                 pr_err("failed to write user space func ra %lx!\n", regs->sp);
211                 return -EINVAL;
212         }
213
214         ri->ret_addr = (uprobe_opcode_t *)ret_addr;
215
216         return 0;
217 }
218
219 static bool get_long(struct task_struct *task,
220                      unsigned long vaddr, unsigned long *val)
221 {
222         return sizeof(*val) != read_proc_vm_atomic(task, vaddr,
223                                                    val, sizeof(*val));
224 }
225
226 static bool put_long(struct task_struct *task,
227                      unsigned long vaddr, unsigned long *val)
228 {
229         return sizeof(*val) != write_proc_vm_atomic(task, vaddr,
230                                                     val, sizeof(*val));
231 }
232
233 /**
234  * @brief Disarms uretprobe on x86 arch.
235  *
236  * @param ri Pointer to the uretprobe instance.
237  * @param task Pointer to the task for which the probe.
238  * @return 0 on success,\n
239  * negative error code on error.
240  */
241 int arch_disarm_urp_inst(struct uretprobe_instance *ri,
242                          struct task_struct *task, unsigned long tr)
243 {
244         unsigned long ret_addr;
245         unsigned long sp = (unsigned long)ri->sp;
246         unsigned long tramp_addr;
247
248         if (tr == 0)
249                 tramp_addr = arch_tramp_by_ri(ri);
250         else
251                 tramp_addr = tr; /* ri - invalid */
252
253         if (get_long(task, sp, &ret_addr)) {
254                 printk(KERN_INFO "---> %s (%d/%d): failed to read stack from %08lx\n",
255                        task->comm, task->tgid, task->pid, sp);
256                 return -EFAULT;
257         }
258
259         if (tramp_addr == ret_addr) {
260                 if (put_long(task, sp, (unsigned long *)&ri->ret_addr)) {
261                         printk(KERN_INFO "---> %s (%d/%d): failed to write "
262                                "orig_ret_addr to %08lx",
263                                task->comm, task->tgid, task->pid, sp);
264                         return -EFAULT;
265                 }
266         } else {
267                 printk(KERN_INFO "---> %s (%d/%d): trampoline NOT found at sp = %08lx\n",
268                        task->comm, task->tgid, task->pid, sp);
269                 return -ENOENT;
270         }
271
272         return 0;
273 }
274
275 /**
276  * @brief Gets trampoline address.
277  *
278  * @param p Pointer to the uprobe.
279  * @param regs Pointer to CPU register data.
280  * @return Trampoline address.
281  */
282 unsigned long arch_get_trampoline_addr(struct uprobe *p, struct pt_regs *regs)
283 {
284         return trampoline_addr(p);
285 }
286
287 /**
288  * @brief Restores return address.
289  *
290  * @param orig_ret_addr Original return address.
291  * @param regs Pointer to CPU register data.
292  * @return Void.
293  */
294 void arch_set_orig_ret_addr(unsigned long orig_ret_addr, struct pt_regs *regs)
295 {
296         regs->EREG(ip) = orig_ret_addr;
297 }
298
299 /**
300  * @brief Removes uprobe.
301  *
302  * @param up Pointer to the target uprobe.
303  * @return Void.
304  */
305 void arch_remove_uprobe(struct uprobe *p)
306 {
307         swap_slot_free(p->sm, p->ainsn.insn);
308 }
309
310 int arch_arm_uprobe(struct uprobe *p)
311 {
312         int ret;
313         uprobe_opcode_t insn = BREAKPOINT_INSTRUCTION;
314         unsigned long vaddr = (unsigned long)p->addr;
315
316         ret = write_proc_vm_atomic(p->task, vaddr, &insn, sizeof(insn));
317         if (!ret) {
318                 pr_err("arch_arm_uprobe: failed to write memory tgid=%u vaddr=%08lx\n",
319                        p->task->tgid, vaddr);
320
321                 return -EACCES;
322         }
323
324         return 0;
325 }
326
327 void arch_disarm_uprobe(struct uprobe *p, struct task_struct *task)
328 {
329         int ret;
330         unsigned long vaddr = (unsigned long)p->addr;
331
332         ret = write_proc_vm_atomic(task, vaddr, &p->opcode, sizeof(p->opcode));
333         if (!ret) {
334                 pr_err("arch_disarm_uprobe: failed to write memory tgid=%u, vaddr=%08lx\n",
335                        task->tgid, vaddr);
336         }
337 }
338
339 static void set_user_jmp_op(void *from, void *to)
340 {
341         struct __arch_jmp_op {
342                 char op;
343                 long raddr;
344         } __packed jop;
345
346         jop.raddr = (long)(to) - ((long)(from) + 5);
347         jop.op = RELATIVEJUMP_INSTRUCTION;
348
349         if (put_user(jop.op, (char *)from) ||
350             put_user(jop.raddr, (long *)(from + 1)))
351                 pr_err("failed to write jump opcode to user space %p\n", from);
352 }
353
354 static void resume_execution(struct uprobe *p,
355                              struct pt_regs *regs,
356                              unsigned long flags)
357 {
358         unsigned long *tos, tos_dword = 0;
359         unsigned long copy_eip = (unsigned long)p->ainsn.insn;
360         unsigned long orig_eip = (unsigned long)p->addr;
361         uprobe_opcode_t insns[2];
362
363         regs->EREG(flags) &= ~TF_MASK;
364
365         tos = (unsigned long *)&tos_dword;
366         if (get_user(tos_dword, (unsigned long *)regs->sp)) {
367                 pr_err("failed to read from user space sp=%lx!\n", regs->sp);
368                 return;
369         }
370
371         if (get_user(*(unsigned short *)insns, (unsigned short *)p->ainsn.insn)) {
372                 pr_err("failed to read first 2 opcodes %p!\n", p->ainsn.insn);
373                 return;
374         }
375
376         switch (insns[0]) {
377         case 0x9c: /* pushfl */
378                 *tos &= ~(TF_MASK | IF_MASK);
379                 *tos |= flags & (TF_MASK | IF_MASK);
380                 break;
381         case 0xc2: /* iret/ret/lret */
382         case 0xc3:
383         case 0xca:
384         case 0xcb:
385         case 0xcf:
386         case 0xea: /* jmp absolute -- eip is correct */
387                 /* eip is already adjusted, no more changes required */
388                 p->ainsn.boostable = 1;
389                 goto no_change;
390         case 0xe8: /* call relative - Fix return addr */
391                 *tos = orig_eip + (*tos - copy_eip);
392                 break;
393         case 0x9a: /* call absolute -- same as call absolute, indirect */
394                 *tos = orig_eip + (*tos - copy_eip);
395
396                 if (put_user(tos_dword, (unsigned long *)regs->sp)) {
397                         pr_err("failed to write dword to sp=%lx\n", regs->sp);
398                         return;
399                 }
400
401                 goto no_change;
402         case 0xff:
403                 if ((insns[1] & 0x30) == 0x10) {
404                         /*
405                          * call absolute, indirect
406                          * Fix return addr; eip is correct.
407                          * But this is not boostable
408                          */
409                         *tos = orig_eip + (*tos - copy_eip);
410
411                         if (put_user(tos_dword, (unsigned long *)regs->sp)) {
412                                 pr_err("failed to write dword to sp=%lx\n", regs->sp);
413                                 return;
414                         }
415
416                         goto no_change;
417                 } else if (((insns[1] & 0x31) == 0x20) || /* jmp near, absolute
418                                                            * indirect */
419                            ((insns[1] & 0x31) == 0x21)) {
420                         /* jmp far, absolute indirect */
421                         /* eip is correct. And this is boostable */
422                         p->ainsn.boostable = 1;
423                         goto no_change;
424                 }
425         case 0xf3:
426                 if (insns[1] == 0xc3)
427                         /* repz ret special handling: no more changes */
428                         goto no_change;
429                 break;
430         default:
431                 break;
432         }
433
434         if (put_user(tos_dword, (unsigned long *)regs->sp)) {
435                 pr_err("failed to write dword to sp=%lx\n", regs->sp);
436                 return;
437         }
438
439         if (p->ainsn.boostable == 0) {
440                 if ((regs->EREG(ip) > copy_eip) && (regs->EREG(ip) - copy_eip) +
441                     5 < MAX_INSN_SIZE) {
442                         /*
443                          * These instructions can be executed directly if it
444                          * jumps back to correct address.
445                          */
446                         set_user_jmp_op((void *) regs->EREG(ip),
447                                         (void *)orig_eip +
448                                         (regs->EREG(ip) - copy_eip));
449                         p->ainsn.boostable = 1;
450                 } else {
451                         p->ainsn.boostable = -1;
452                 }
453         }
454
455         regs->EREG(ip) = orig_eip + (regs->EREG(ip) - copy_eip);
456
457 no_change:
458         return;
459 }
460
461 static void prepare_tramp(struct uprobe *p, struct pt_regs *regs)
462 {
463         regs->ip = (unsigned long)p->ainsn.insn;
464 }
465
466 static void prepare_ss(struct pt_regs *regs)
467 {
468         /* set single step mode */
469         regs->flags |= TF_MASK;
470         regs->flags &= ~IF_MASK;
471 }
472
473
474 static unsigned long resume_userspace_addr;
475
476 static void __used __up_handler(void)
477 {
478         struct pt_regs *regs = current_ctx()->ptr_regs;
479         struct thread_info *tinfo = current_thread_info();
480         struct uprobe *p = current_ucb()->p;
481
482         /* restore KS regs */
483         *regs = current_ctx()->save_regs;
484
485         /* call handler */
486         current_ctx()->handler(p, regs);
487
488         /* resume_userspace */
489         asm volatile (
490                 "movl %0, %%esp\n"
491                 "movl %1, %%ebp\n"
492                 "jmpl *%2\n"
493                 : /* No outputs. */
494                 : "r" (regs), "r" (tinfo) , "r" (resume_userspace_addr)
495         );
496 }
497
498 void up_handler(void);
499 __asm(
500         "up_handler:\n"
501         /* skip hex tractor-driver bytes to make some free space (skip regs) */
502         "sub $0x300, %esp\n"
503         "jmp __up_handler\n"
504 );
505
506 static int exceptions_handler(struct pt_regs *regs,
507                               int (*handler)(struct uprobe *, struct pt_regs *))
508 {
509         /* save regs */
510         current_ctx()->save_regs = *regs;
511         current_ctx()->ptr_regs = regs;
512
513         /* set handler */
514         current_ctx()->handler = handler;
515
516         /* setup regs to return to KS */
517         regs->ip = (unsigned long)up_handler;
518         regs->ds = __USER_DS;
519         regs->es = __USER_DS;
520         regs->fs = __KERNEL_PERCPU;
521         regs->cs = __KERNEL_CS | get_kernel_rpl();
522         regs->gs = 0;
523         regs->flags = X86_EFLAGS_IF | X86_EFLAGS_FIXED;
524
525         return 1;
526 }
527
528 static int uprobe_handler_part2(struct uprobe *p, struct pt_regs *regs)
529 {
530         if (!p->pre_handler(p, regs)) {
531                 prepare_tramp(p, regs);
532                 if (p->ainsn.boostable == 1 && !p->post_handler)
533                         return 1;
534
535                 save_current_flags(regs);
536                 set_current_probe(p);
537                 prepare_ss(regs);
538         }
539
540         return 1;
541 }
542
543 static int uprobe_handler_atomic(struct pt_regs *regs)
544 {
545         pid_t tgid = current->tgid;
546         unsigned long vaddr = regs->ip - 1;
547         struct uprobe *p = get_uprobe((void *)vaddr, tgid);
548
549         if (p) {
550                 if (p->pre_handler) {
551                         set_current_probe(p);
552                         exceptions_handler(regs, uprobe_handler_part2);
553                 } else {
554                         uprobe_handler_part2(p, regs);
555                 }
556         } else {
557                 unsigned long tramp_vaddr;
558
559                 tramp_vaddr = vaddr - UPROBES_TRAMP_RET_BREAK_IDX;
560                 p = get_uprobe_by_insn_slot((void *)tramp_vaddr, tgid, regs);
561                 if (p == NULL) {
562                         pr_info("no_uprobe\n");
563                         return 0;
564                 }
565
566                 set_current_probe(p);
567                 exceptions_handler(regs, trampoline_uprobe_handler);
568         }
569
570         return 1;
571 }
572
573 static int post_uprobe_handler(struct uprobe *p, struct pt_regs *regs)
574 {
575         unsigned long flags = current_ucb()->flags;
576
577         resume_execution(p, regs, flags);
578         restore_current_flags(regs, flags);
579
580         /* reset current probe */
581         set_current_probe(NULL);
582
583         return 1;
584 }
585
586 static int post_uprobe_handler_atomic(struct pt_regs *regs)
587 {
588         struct uprobe *p = get_current_probe();
589
590         if (p) {
591                 exceptions_handler(regs, post_uprobe_handler);
592         } else {
593                 pr_info("task[%u %u %s] current uprobe is not found\n",
594                         current->tgid, current->pid, current->comm);
595         }
596
597         return !!p;
598 }
599
600 static int uprobe_exceptions_notify(struct notifier_block *self,
601                                     unsigned long val, void *data)
602 {
603         struct die_args *args = (struct die_args *)data;
604         int ret = NOTIFY_DONE;
605
606         if (args->regs == NULL || !user_mode_vm(args->regs))
607                 return ret;
608
609         switch (val) {
610 #ifdef CONFIG_KPROBES
611         case DIE_INT3:
612 #else
613         case DIE_TRAP:
614 #endif
615                 if (uprobe_handler_atomic(args->regs))
616                         ret = NOTIFY_STOP;
617                 break;
618         case DIE_DEBUG:
619                 if (post_uprobe_handler_atomic(args->regs))
620                         ret = NOTIFY_STOP;
621                 break;
622         default:
623                 break;
624         }
625
626         return ret;
627 }
628
629 static struct notifier_block uprobe_exceptions_nb = {
630         .notifier_call = uprobe_exceptions_notify,
631         .priority = INT_MAX
632 };
633
634 /**
635  * @brief Registers notify.
636  *
637  * @return register_die_notifier result.
638  */
639 int swap_arch_init_uprobes(void)
640 {
641         int ret;
642
643         resume_userspace_addr = swap_ksyms("resume_userspace");
644         if (resume_userspace_addr == 0) {
645                 pr_err("symbol 'resume_userspace' not found\n");
646                 return -ESRCH;
647         }
648
649         ret = swap_td_raw_reg(&td_raw, sizeof(struct uprobe_ctlblk));
650         if (ret)
651                 return ret;
652
653         ret = register_die_notifier(&uprobe_exceptions_nb);
654         if (ret)
655                 swap_td_raw_unreg(&td_raw);
656
657         return ret;
658 }
659
660 /**
661  * @brief Unregisters notify.
662  *
663  * @return Void.
664  */
665 void swap_arch_exit_uprobes(void)
666 {
667         unregister_die_notifier(&uprobe_exceptions_nb);
668         swap_td_raw_unreg(&td_raw);
669 }
670