2 * User-space Probes (UProbes)
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 * Copyright (C) IBM Corporation, 2008-2012
22 * Copyright (C) 2011-2012 Red Hat, Inc., Peter Zijlstra
25 #include <linux/kernel.h>
26 #include <linux/highmem.h>
27 #include <linux/pagemap.h> /* read_mapping_page */
28 #include <linux/slab.h>
29 #include <linux/sched.h>
30 #include <linux/sched/mm.h>
31 #include <linux/sched/coredump.h>
32 #include <linux/export.h>
33 #include <linux/rmap.h> /* anon_vma_prepare */
34 #include <linux/mmu_notifier.h> /* set_pte_at_notify */
35 #include <linux/swap.h> /* try_to_free_swap */
36 #include <linux/ptrace.h> /* user_enable_single_step */
37 #include <linux/kdebug.h> /* notifier mechanism */
38 #include "../../mm/internal.h" /* munlock_vma_page */
39 #include <linux/percpu-rwsem.h>
40 #include <linux/task_work.h>
41 #include <linux/shmem_fs.h>
43 #include <linux/uprobes.h>
45 #define UINSNS_PER_PAGE (PAGE_SIZE/UPROBE_XOL_SLOT_BYTES)
46 #define MAX_UPROBE_XOL_SLOTS UINSNS_PER_PAGE
48 static struct rb_root uprobes_tree = RB_ROOT;
50 * allows us to skip the uprobe_mmap if there are no uprobe events active
51 * at this time. Probably a fine grained per inode count is better?
53 #define no_uprobe_events() RB_EMPTY_ROOT(&uprobes_tree)
55 static DEFINE_SPINLOCK(uprobes_treelock); /* serialize rbtree access */
57 #define UPROBES_HASH_SZ 13
58 /* serialize uprobe->pending_list */
59 static struct mutex uprobes_mmap_mutex[UPROBES_HASH_SZ];
60 #define uprobes_mmap_hash(v) (&uprobes_mmap_mutex[((unsigned long)(v)) % UPROBES_HASH_SZ])
62 static struct percpu_rw_semaphore dup_mmap_sem;
64 /* Have a copy of original instruction */
65 #define UPROBE_COPY_INSN 0
68 struct rb_node rb_node; /* node in the rb tree */
70 struct rw_semaphore register_rwsem;
71 struct rw_semaphore consumer_rwsem;
72 struct list_head pending_list;
73 struct uprobe_consumer *consumers;
74 struct inode *inode; /* Also hold a ref to inode */
76 loff_t ref_ctr_offset;
80 * The generic code assumes that it has two members of unknown type
81 * owned by the arch-specific code:
83 * insn - copy_insn() saves the original instruction here for
84 * arch_uprobe_analyze_insn().
86 * ixol - potentially modified instruction to execute out of
87 * line, copied to xol_area by xol_get_insn_slot().
89 struct arch_uprobe arch;
92 struct delayed_uprobe {
93 struct list_head list;
94 struct uprobe *uprobe;
98 static DEFINE_MUTEX(delayed_uprobe_lock);
99 static LIST_HEAD(delayed_uprobe_list);
102 * Execute out of line area: anonymous executable mapping installed
103 * by the probed task to execute the copy of the original instruction
104 * mangled by set_swbp().
106 * On a breakpoint hit, thread contests for a slot. It frees the
107 * slot after singlestep. Currently a fixed number of slots are
111 wait_queue_head_t wq; /* if all slots are busy */
112 atomic_t slot_count; /* number of in-use slots */
113 unsigned long *bitmap; /* 0 = free slot */
115 struct vm_special_mapping xol_mapping;
116 struct page *pages[2];
118 * We keep the vma's vm_start rather than a pointer to the vma
119 * itself. The probed process or a naughty kernel module could make
120 * the vma go away, and we must handle that reasonably gracefully.
122 unsigned long vaddr; /* Page(s) of instruction slots */
126 * valid_vma: Verify if the specified vma is an executable vma
127 * Relax restrictions while unregistering: vm_flags might have
128 * changed after breakpoint was inserted.
129 * - is_register: indicates if we are in register context.
130 * - Return 1 if the specified virtual address is in an
133 static bool valid_vma(struct vm_area_struct *vma, bool is_register)
135 vm_flags_t flags = VM_HUGETLB | VM_MAYEXEC | VM_MAYSHARE;
140 return vma->vm_file && (vma->vm_flags & flags) == VM_MAYEXEC;
143 static unsigned long offset_to_vaddr(struct vm_area_struct *vma, loff_t offset)
145 return vma->vm_start + offset - ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
148 static loff_t vaddr_to_offset(struct vm_area_struct *vma, unsigned long vaddr)
150 return ((loff_t)vma->vm_pgoff << PAGE_SHIFT) + (vaddr - vma->vm_start);
154 * __replace_page - replace page in vma by new page.
155 * based on replace_page in mm/ksm.c
157 * @vma: vma that holds the pte pointing to page
158 * @addr: address the old @page is mapped at
159 * @page: the cowed page we are replacing by kpage
160 * @kpage: the modified page we replace page by
162 * Returns 0 on success, -EFAULT on failure.
164 static int __replace_page(struct vm_area_struct *vma, unsigned long addr,
165 struct page *old_page, struct page *new_page)
167 struct mm_struct *mm = vma->vm_mm;
168 struct page_vma_mapped_walk pvmw = {
174 /* For mmu_notifiers */
175 const unsigned long mmun_start = addr;
176 const unsigned long mmun_end = addr + PAGE_SIZE;
177 struct mem_cgroup *memcg;
179 VM_BUG_ON_PAGE(PageTransHuge(old_page), old_page);
181 err = mem_cgroup_try_charge(new_page, vma->vm_mm, GFP_KERNEL, &memcg,
186 /* For try_to_free_swap() and munlock_vma_page() below */
189 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
191 if (!page_vma_mapped_walk(&pvmw)) {
192 mem_cgroup_cancel_charge(new_page, memcg, false);
195 VM_BUG_ON_PAGE(addr != pvmw.address, old_page);
198 page_add_new_anon_rmap(new_page, vma, addr, false);
199 mem_cgroup_commit_charge(new_page, memcg, false, false);
200 lru_cache_add_active_or_unevictable(new_page, vma);
202 if (!PageAnon(old_page)) {
203 dec_mm_counter(mm, mm_counter_file(old_page));
204 inc_mm_counter(mm, MM_ANONPAGES);
207 flush_cache_page(vma, addr, pte_pfn(*pvmw.pte));
208 ptep_clear_flush_notify(vma, addr, pvmw.pte);
209 set_pte_at_notify(mm, addr, pvmw.pte,
210 mk_pte(new_page, vma->vm_page_prot));
212 page_remove_rmap(old_page, false);
213 if (!page_mapped(old_page))
214 try_to_free_swap(old_page);
215 page_vma_mapped_walk_done(&pvmw);
217 if (vma->vm_flags & VM_LOCKED)
218 munlock_vma_page(old_page);
223 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
224 unlock_page(old_page);
229 * is_swbp_insn - check if instruction is breakpoint instruction.
230 * @insn: instruction to be checked.
231 * Default implementation of is_swbp_insn
232 * Returns true if @insn is a breakpoint instruction.
234 bool __weak is_swbp_insn(uprobe_opcode_t *insn)
236 return *insn == UPROBE_SWBP_INSN;
240 * is_trap_insn - check if instruction is breakpoint instruction.
241 * @insn: instruction to be checked.
242 * Default implementation of is_trap_insn
243 * Returns true if @insn is a breakpoint instruction.
245 * This function is needed for the case where an architecture has multiple
246 * trap instructions (like powerpc).
248 bool __weak is_trap_insn(uprobe_opcode_t *insn)
250 return is_swbp_insn(insn);
253 static void copy_from_page(struct page *page, unsigned long vaddr, void *dst, int len)
255 void *kaddr = kmap_atomic(page);
256 memcpy(dst, kaddr + (vaddr & ~PAGE_MASK), len);
257 kunmap_atomic(kaddr);
260 static void copy_to_page(struct page *page, unsigned long vaddr, const void *src, int len)
262 void *kaddr = kmap_atomic(page);
263 memcpy(kaddr + (vaddr & ~PAGE_MASK), src, len);
264 kunmap_atomic(kaddr);
267 static int verify_opcode(struct page *page, unsigned long vaddr, uprobe_opcode_t *new_opcode)
269 uprobe_opcode_t old_opcode;
273 * Note: We only check if the old_opcode is UPROBE_SWBP_INSN here.
274 * We do not check if it is any other 'trap variant' which could
275 * be conditional trap instruction such as the one powerpc supports.
277 * The logic is that we do not care if the underlying instruction
278 * is a trap variant; uprobes always wins over any other (gdb)
281 copy_from_page(page, vaddr, &old_opcode, UPROBE_SWBP_INSN_SIZE);
282 is_swbp = is_swbp_insn(&old_opcode);
284 if (is_swbp_insn(new_opcode)) {
285 if (is_swbp) /* register: already installed? */
288 if (!is_swbp) /* unregister: was it changed by us? */
295 static struct delayed_uprobe *
296 delayed_uprobe_check(struct uprobe *uprobe, struct mm_struct *mm)
298 struct delayed_uprobe *du;
300 list_for_each_entry(du, &delayed_uprobe_list, list)
301 if (du->uprobe == uprobe && du->mm == mm)
306 static int delayed_uprobe_add(struct uprobe *uprobe, struct mm_struct *mm)
308 struct delayed_uprobe *du;
310 if (delayed_uprobe_check(uprobe, mm))
313 du = kzalloc(sizeof(*du), GFP_KERNEL);
319 list_add(&du->list, &delayed_uprobe_list);
323 static void delayed_uprobe_delete(struct delayed_uprobe *du)
331 static void delayed_uprobe_remove(struct uprobe *uprobe, struct mm_struct *mm)
333 struct list_head *pos, *q;
334 struct delayed_uprobe *du;
339 list_for_each_safe(pos, q, &delayed_uprobe_list) {
340 du = list_entry(pos, struct delayed_uprobe, list);
342 if (uprobe && du->uprobe != uprobe)
344 if (mm && du->mm != mm)
347 delayed_uprobe_delete(du);
351 static bool valid_ref_ctr_vma(struct uprobe *uprobe,
352 struct vm_area_struct *vma)
354 unsigned long vaddr = offset_to_vaddr(vma, uprobe->ref_ctr_offset);
356 return uprobe->ref_ctr_offset &&
358 file_inode(vma->vm_file) == uprobe->inode &&
359 (vma->vm_flags & (VM_WRITE|VM_SHARED)) == VM_WRITE &&
360 vma->vm_start <= vaddr &&
364 static struct vm_area_struct *
365 find_ref_ctr_vma(struct uprobe *uprobe, struct mm_struct *mm)
367 struct vm_area_struct *tmp;
369 for (tmp = mm->mmap; tmp; tmp = tmp->vm_next)
370 if (valid_ref_ctr_vma(uprobe, tmp))
377 __update_ref_ctr(struct mm_struct *mm, unsigned long vaddr, short d)
381 struct vm_area_struct *vma;
388 ret = get_user_pages_remote(NULL, mm, vaddr, 1,
389 FOLL_WRITE, &page, &vma, NULL);
390 if (unlikely(ret <= 0)) {
392 * We are asking for 1 page. If get_user_pages_remote() fails,
393 * it may return 0, in that case we have to return error.
395 return ret == 0 ? -EBUSY : ret;
398 kaddr = kmap_atomic(page);
399 ptr = kaddr + (vaddr & ~PAGE_MASK);
401 if (unlikely(*ptr + d < 0)) {
402 pr_warn("ref_ctr going negative. vaddr: 0x%lx, "
403 "curr val: %d, delta: %d\n", vaddr, *ptr, d);
411 kunmap_atomic(kaddr);
416 static void update_ref_ctr_warn(struct uprobe *uprobe,
417 struct mm_struct *mm, short d)
419 pr_warn("ref_ctr %s failed for inode: 0x%lx offset: "
420 "0x%llx ref_ctr_offset: 0x%llx of mm: 0x%pK\n",
421 d > 0 ? "increment" : "decrement", uprobe->inode->i_ino,
422 (unsigned long long) uprobe->offset,
423 (unsigned long long) uprobe->ref_ctr_offset, mm);
426 static int update_ref_ctr(struct uprobe *uprobe, struct mm_struct *mm,
429 struct vm_area_struct *rc_vma;
430 unsigned long rc_vaddr;
433 rc_vma = find_ref_ctr_vma(uprobe, mm);
436 rc_vaddr = offset_to_vaddr(rc_vma, uprobe->ref_ctr_offset);
437 ret = __update_ref_ctr(mm, rc_vaddr, d);
439 update_ref_ctr_warn(uprobe, mm, d);
445 mutex_lock(&delayed_uprobe_lock);
447 ret = delayed_uprobe_add(uprobe, mm);
449 delayed_uprobe_remove(uprobe, mm);
450 mutex_unlock(&delayed_uprobe_lock);
457 * Expect the breakpoint instruction to be the smallest size instruction for
458 * the architecture. If an arch has variable length instruction and the
459 * breakpoint instruction is not of the smallest length instruction
460 * supported by that architecture then we need to modify is_trap_at_addr and
461 * uprobe_write_opcode accordingly. This would never be a problem for archs
462 * that have fixed length instructions.
464 * uprobe_write_opcode - write the opcode at a given virtual address.
465 * @mm: the probed process address space.
466 * @vaddr: the virtual address to store the opcode.
467 * @opcode: opcode to be written at @vaddr.
469 * Called with mm->mmap_sem held for write.
470 * Return 0 (success) or a negative errno.
472 int uprobe_write_opcode(struct arch_uprobe *auprobe, struct mm_struct *mm,
473 unsigned long vaddr, uprobe_opcode_t opcode)
475 struct uprobe *uprobe;
476 struct page *old_page, *new_page;
477 struct vm_area_struct *vma;
478 int ret, is_register, ref_ctr_updated = 0;
480 is_register = is_swbp_insn(&opcode);
481 uprobe = container_of(auprobe, struct uprobe, arch);
484 /* Read the page with vaddr into memory */
485 ret = get_user_pages_remote(NULL, mm, vaddr, 1,
486 FOLL_FORCE | FOLL_SPLIT, &old_page, &vma, NULL);
490 ret = verify_opcode(old_page, vaddr, &opcode);
494 /* We are going to replace instruction, update ref_ctr. */
495 if (!ref_ctr_updated && uprobe->ref_ctr_offset) {
496 ret = update_ref_ctr(uprobe, mm, is_register ? 1 : -1);
503 ret = anon_vma_prepare(vma);
508 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vaddr);
512 __SetPageUptodate(new_page);
513 copy_highpage(new_page, old_page);
514 copy_to_page(new_page, vaddr, &opcode, UPROBE_SWBP_INSN_SIZE);
516 ret = __replace_page(vma, vaddr, old_page, new_page);
521 if (unlikely(ret == -EAGAIN))
524 /* Revert back reference counter if instruction update failed. */
525 if (ret && is_register && ref_ctr_updated)
526 update_ref_ctr(uprobe, mm, -1);
532 * set_swbp - store breakpoint at a given address.
533 * @auprobe: arch specific probepoint information.
534 * @mm: the probed process address space.
535 * @vaddr: the virtual address to insert the opcode.
537 * For mm @mm, store the breakpoint instruction at @vaddr.
538 * Return 0 (success) or a negative errno.
540 int __weak set_swbp(struct arch_uprobe *auprobe, struct mm_struct *mm, unsigned long vaddr)
542 return uprobe_write_opcode(auprobe, mm, vaddr, UPROBE_SWBP_INSN);
546 * set_orig_insn - Restore the original instruction.
547 * @mm: the probed process address space.
548 * @auprobe: arch specific probepoint information.
549 * @vaddr: the virtual address to insert the opcode.
551 * For mm @mm, restore the original opcode (opcode) at @vaddr.
552 * Return 0 (success) or a negative errno.
555 set_orig_insn(struct arch_uprobe *auprobe, struct mm_struct *mm, unsigned long vaddr)
557 return uprobe_write_opcode(auprobe, mm, vaddr,
558 *(uprobe_opcode_t *)&auprobe->insn);
561 static struct uprobe *get_uprobe(struct uprobe *uprobe)
563 atomic_inc(&uprobe->ref);
567 static void put_uprobe(struct uprobe *uprobe)
569 if (atomic_dec_and_test(&uprobe->ref)) {
571 * If application munmap(exec_vma) before uprobe_unregister()
572 * gets called, we don't get a chance to remove uprobe from
573 * delayed_uprobe_list from remove_breakpoint(). Do it here.
575 mutex_lock(&delayed_uprobe_lock);
576 delayed_uprobe_remove(uprobe, NULL);
577 mutex_unlock(&delayed_uprobe_lock);
582 static int match_uprobe(struct uprobe *l, struct uprobe *r)
584 if (l->inode < r->inode)
587 if (l->inode > r->inode)
590 if (l->offset < r->offset)
593 if (l->offset > r->offset)
599 static struct uprobe *__find_uprobe(struct inode *inode, loff_t offset)
601 struct uprobe u = { .inode = inode, .offset = offset };
602 struct rb_node *n = uprobes_tree.rb_node;
603 struct uprobe *uprobe;
607 uprobe = rb_entry(n, struct uprobe, rb_node);
608 match = match_uprobe(&u, uprobe);
610 return get_uprobe(uprobe);
621 * Find a uprobe corresponding to a given inode:offset
622 * Acquires uprobes_treelock
624 static struct uprobe *find_uprobe(struct inode *inode, loff_t offset)
626 struct uprobe *uprobe;
628 spin_lock(&uprobes_treelock);
629 uprobe = __find_uprobe(inode, offset);
630 spin_unlock(&uprobes_treelock);
635 static struct uprobe *__insert_uprobe(struct uprobe *uprobe)
637 struct rb_node **p = &uprobes_tree.rb_node;
638 struct rb_node *parent = NULL;
644 u = rb_entry(parent, struct uprobe, rb_node);
645 match = match_uprobe(uprobe, u);
647 return get_uprobe(u);
650 p = &parent->rb_left;
652 p = &parent->rb_right;
657 rb_link_node(&uprobe->rb_node, parent, p);
658 rb_insert_color(&uprobe->rb_node, &uprobes_tree);
659 /* get access + creation ref */
660 atomic_set(&uprobe->ref, 2);
666 * Acquire uprobes_treelock.
667 * Matching uprobe already exists in rbtree;
668 * increment (access refcount) and return the matching uprobe.
670 * No matching uprobe; insert the uprobe in rb_tree;
671 * get a double refcount (access + creation) and return NULL.
673 static struct uprobe *insert_uprobe(struct uprobe *uprobe)
677 spin_lock(&uprobes_treelock);
678 u = __insert_uprobe(uprobe);
679 spin_unlock(&uprobes_treelock);
685 ref_ctr_mismatch_warn(struct uprobe *cur_uprobe, struct uprobe *uprobe)
687 pr_warn("ref_ctr_offset mismatch. inode: 0x%lx offset: 0x%llx "
688 "ref_ctr_offset(old): 0x%llx ref_ctr_offset(new): 0x%llx\n",
689 uprobe->inode->i_ino, (unsigned long long) uprobe->offset,
690 (unsigned long long) cur_uprobe->ref_ctr_offset,
691 (unsigned long long) uprobe->ref_ctr_offset);
694 static struct uprobe *alloc_uprobe(struct inode *inode, loff_t offset,
695 loff_t ref_ctr_offset)
697 struct uprobe *uprobe, *cur_uprobe;
699 uprobe = kzalloc(sizeof(struct uprobe), GFP_KERNEL);
703 uprobe->inode = inode;
704 uprobe->offset = offset;
705 uprobe->ref_ctr_offset = ref_ctr_offset;
706 init_rwsem(&uprobe->register_rwsem);
707 init_rwsem(&uprobe->consumer_rwsem);
709 /* add to uprobes_tree, sorted on inode:offset */
710 cur_uprobe = insert_uprobe(uprobe);
711 /* a uprobe exists for this inode:offset combination */
713 if (cur_uprobe->ref_ctr_offset != uprobe->ref_ctr_offset) {
714 ref_ctr_mismatch_warn(cur_uprobe, uprobe);
715 put_uprobe(cur_uprobe);
717 return ERR_PTR(-EINVAL);
726 static void consumer_add(struct uprobe *uprobe, struct uprobe_consumer *uc)
728 down_write(&uprobe->consumer_rwsem);
729 uc->next = uprobe->consumers;
730 uprobe->consumers = uc;
731 up_write(&uprobe->consumer_rwsem);
735 * For uprobe @uprobe, delete the consumer @uc.
736 * Return true if the @uc is deleted successfully
739 static bool consumer_del(struct uprobe *uprobe, struct uprobe_consumer *uc)
741 struct uprobe_consumer **con;
744 down_write(&uprobe->consumer_rwsem);
745 for (con = &uprobe->consumers; *con; con = &(*con)->next) {
752 up_write(&uprobe->consumer_rwsem);
757 static int __copy_insn(struct address_space *mapping, struct file *filp,
758 void *insn, int nbytes, loff_t offset)
762 * Ensure that the page that has the original instruction is populated
763 * and in page-cache. If ->readpage == NULL it must be shmem_mapping(),
764 * see uprobe_register().
766 if (mapping->a_ops->readpage)
767 page = read_mapping_page(mapping, offset >> PAGE_SHIFT, filp);
769 page = shmem_read_mapping_page(mapping, offset >> PAGE_SHIFT);
771 return PTR_ERR(page);
773 copy_from_page(page, offset, insn, nbytes);
779 static int copy_insn(struct uprobe *uprobe, struct file *filp)
781 struct address_space *mapping = uprobe->inode->i_mapping;
782 loff_t offs = uprobe->offset;
783 void *insn = &uprobe->arch.insn;
784 int size = sizeof(uprobe->arch.insn);
787 /* Copy only available bytes, -EIO if nothing was read */
789 if (offs >= i_size_read(uprobe->inode))
792 len = min_t(int, size, PAGE_SIZE - (offs & ~PAGE_MASK));
793 err = __copy_insn(mapping, filp, insn, len, offs);
805 static int prepare_uprobe(struct uprobe *uprobe, struct file *file,
806 struct mm_struct *mm, unsigned long vaddr)
810 if (test_bit(UPROBE_COPY_INSN, &uprobe->flags))
813 /* TODO: move this into _register, until then we abuse this sem. */
814 down_write(&uprobe->consumer_rwsem);
815 if (test_bit(UPROBE_COPY_INSN, &uprobe->flags))
818 ret = copy_insn(uprobe, file);
823 if (is_trap_insn((uprobe_opcode_t *)&uprobe->arch.insn))
826 ret = arch_uprobe_analyze_insn(&uprobe->arch, mm, vaddr);
830 /* uprobe_write_opcode() assumes we don't cross page boundary */
831 BUG_ON((uprobe->offset & ~PAGE_MASK) +
832 UPROBE_SWBP_INSN_SIZE > PAGE_SIZE);
834 smp_wmb(); /* pairs with the smp_rmb() in handle_swbp() */
835 set_bit(UPROBE_COPY_INSN, &uprobe->flags);
838 up_write(&uprobe->consumer_rwsem);
843 static inline bool consumer_filter(struct uprobe_consumer *uc,
844 enum uprobe_filter_ctx ctx, struct mm_struct *mm)
846 return !uc->filter || uc->filter(uc, ctx, mm);
849 static bool filter_chain(struct uprobe *uprobe,
850 enum uprobe_filter_ctx ctx, struct mm_struct *mm)
852 struct uprobe_consumer *uc;
855 down_read(&uprobe->consumer_rwsem);
856 for (uc = uprobe->consumers; uc; uc = uc->next) {
857 ret = consumer_filter(uc, ctx, mm);
861 up_read(&uprobe->consumer_rwsem);
867 install_breakpoint(struct uprobe *uprobe, struct mm_struct *mm,
868 struct vm_area_struct *vma, unsigned long vaddr)
873 ret = prepare_uprobe(uprobe, vma->vm_file, mm, vaddr);
878 * set MMF_HAS_UPROBES in advance for uprobe_pre_sstep_notifier(),
879 * the task can hit this breakpoint right after __replace_page().
881 first_uprobe = !test_bit(MMF_HAS_UPROBES, &mm->flags);
883 set_bit(MMF_HAS_UPROBES, &mm->flags);
885 ret = set_swbp(&uprobe->arch, mm, vaddr);
887 clear_bit(MMF_RECALC_UPROBES, &mm->flags);
888 else if (first_uprobe)
889 clear_bit(MMF_HAS_UPROBES, &mm->flags);
895 remove_breakpoint(struct uprobe *uprobe, struct mm_struct *mm, unsigned long vaddr)
897 set_bit(MMF_RECALC_UPROBES, &mm->flags);
898 return set_orig_insn(&uprobe->arch, mm, vaddr);
901 static inline bool uprobe_is_active(struct uprobe *uprobe)
903 return !RB_EMPTY_NODE(&uprobe->rb_node);
906 * There could be threads that have already hit the breakpoint. They
907 * will recheck the current insn and restart if find_uprobe() fails.
908 * See find_active_uprobe().
910 static void delete_uprobe(struct uprobe *uprobe)
912 if (WARN_ON(!uprobe_is_active(uprobe)))
915 spin_lock(&uprobes_treelock);
916 rb_erase(&uprobe->rb_node, &uprobes_tree);
917 spin_unlock(&uprobes_treelock);
918 RB_CLEAR_NODE(&uprobe->rb_node); /* for uprobe_is_active() */
923 struct map_info *next;
924 struct mm_struct *mm;
928 static inline struct map_info *free_map_info(struct map_info *info)
930 struct map_info *next = info->next;
935 static struct map_info *
936 build_map_info(struct address_space *mapping, loff_t offset, bool is_register)
938 unsigned long pgoff = offset >> PAGE_SHIFT;
939 struct vm_area_struct *vma;
940 struct map_info *curr = NULL;
941 struct map_info *prev = NULL;
942 struct map_info *info;
946 i_mmap_lock_read(mapping);
947 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
948 if (!valid_vma(vma, is_register))
951 if (!prev && !more) {
953 * Needs GFP_NOWAIT to avoid i_mmap_rwsem recursion through
954 * reclaim. This is optimistic, no harm done if it fails.
956 prev = kmalloc(sizeof(struct map_info),
957 GFP_NOWAIT | __GFP_NOMEMALLOC | __GFP_NOWARN);
966 if (!mmget_not_zero(vma->vm_mm))
974 info->mm = vma->vm_mm;
975 info->vaddr = offset_to_vaddr(vma, offset);
977 i_mmap_unlock_read(mapping);
989 info = kmalloc(sizeof(struct map_info), GFP_KERNEL);
991 curr = ERR_PTR(-ENOMEM);
1001 prev = free_map_info(prev);
1006 register_for_each_vma(struct uprobe *uprobe, struct uprobe_consumer *new)
1008 bool is_register = !!new;
1009 struct map_info *info;
1012 percpu_down_write(&dup_mmap_sem);
1013 info = build_map_info(uprobe->inode->i_mapping,
1014 uprobe->offset, is_register);
1016 err = PTR_ERR(info);
1021 struct mm_struct *mm = info->mm;
1022 struct vm_area_struct *vma;
1024 if (err && is_register)
1027 down_write(&mm->mmap_sem);
1028 vma = find_vma(mm, info->vaddr);
1029 if (!vma || !valid_vma(vma, is_register) ||
1030 file_inode(vma->vm_file) != uprobe->inode)
1033 if (vma->vm_start > info->vaddr ||
1034 vaddr_to_offset(vma, info->vaddr) != uprobe->offset)
1038 /* consult only the "caller", new consumer. */
1039 if (consumer_filter(new,
1040 UPROBE_FILTER_REGISTER, mm))
1041 err = install_breakpoint(uprobe, mm, vma, info->vaddr);
1042 } else if (test_bit(MMF_HAS_UPROBES, &mm->flags)) {
1043 if (!filter_chain(uprobe,
1044 UPROBE_FILTER_UNREGISTER, mm))
1045 err |= remove_breakpoint(uprobe, mm, info->vaddr);
1049 up_write(&mm->mmap_sem);
1052 info = free_map_info(info);
1055 percpu_up_write(&dup_mmap_sem);
1060 __uprobe_unregister(struct uprobe *uprobe, struct uprobe_consumer *uc)
1064 if (WARN_ON(!consumer_del(uprobe, uc)))
1067 err = register_for_each_vma(uprobe, NULL);
1068 /* TODO : cant unregister? schedule a worker thread */
1069 if (!uprobe->consumers && !err)
1070 delete_uprobe(uprobe);
1074 * uprobe_unregister - unregister an already registered probe.
1075 * @inode: the file in which the probe has to be removed.
1076 * @offset: offset from the start of the file.
1077 * @uc: identify which probe if multiple probes are colocated.
1079 void uprobe_unregister(struct inode *inode, loff_t offset, struct uprobe_consumer *uc)
1081 struct uprobe *uprobe;
1083 uprobe = find_uprobe(inode, offset);
1084 if (WARN_ON(!uprobe))
1087 down_write(&uprobe->register_rwsem);
1088 __uprobe_unregister(uprobe, uc);
1089 up_write(&uprobe->register_rwsem);
1092 EXPORT_SYMBOL_GPL(uprobe_unregister);
1095 * __uprobe_register - register a probe
1096 * @inode: the file in which the probe has to be placed.
1097 * @offset: offset from the start of the file.
1098 * @uc: information on howto handle the probe..
1100 * Apart from the access refcount, __uprobe_register() takes a creation
1101 * refcount (thro alloc_uprobe) if and only if this @uprobe is getting
1102 * inserted into the rbtree (i.e first consumer for a @inode:@offset
1103 * tuple). Creation refcount stops uprobe_unregister from freeing the
1104 * @uprobe even before the register operation is complete. Creation
1105 * refcount is released when the last @uc for the @uprobe
1106 * unregisters. Caller of __uprobe_register() is required to keep @inode
1107 * (and the containing mount) referenced.
1109 * Return errno if it cannot successully install probes
1110 * else return 0 (success)
1112 static int __uprobe_register(struct inode *inode, loff_t offset,
1113 loff_t ref_ctr_offset, struct uprobe_consumer *uc)
1115 struct uprobe *uprobe;
1118 /* Uprobe must have at least one set consumer */
1119 if (!uc->handler && !uc->ret_handler)
1122 /* copy_insn() uses read_mapping_page() or shmem_read_mapping_page() */
1123 if (!inode->i_mapping->a_ops->readpage && !shmem_mapping(inode->i_mapping))
1125 /* Racy, just to catch the obvious mistakes */
1126 if (offset > i_size_read(inode))
1130 uprobe = alloc_uprobe(inode, offset, ref_ctr_offset);
1134 return PTR_ERR(uprobe);
1137 * We can race with uprobe_unregister()->delete_uprobe().
1138 * Check uprobe_is_active() and retry if it is false.
1140 down_write(&uprobe->register_rwsem);
1142 if (likely(uprobe_is_active(uprobe))) {
1143 consumer_add(uprobe, uc);
1144 ret = register_for_each_vma(uprobe, uc);
1146 __uprobe_unregister(uprobe, uc);
1148 up_write(&uprobe->register_rwsem);
1151 if (unlikely(ret == -EAGAIN))
1156 int uprobe_register(struct inode *inode, loff_t offset,
1157 struct uprobe_consumer *uc)
1159 return __uprobe_register(inode, offset, 0, uc);
1161 EXPORT_SYMBOL_GPL(uprobe_register);
1163 int uprobe_register_refctr(struct inode *inode, loff_t offset,
1164 loff_t ref_ctr_offset, struct uprobe_consumer *uc)
1166 return __uprobe_register(inode, offset, ref_ctr_offset, uc);
1168 EXPORT_SYMBOL_GPL(uprobe_register_refctr);
1171 * uprobe_apply - unregister an already registered probe.
1172 * @inode: the file in which the probe has to be removed.
1173 * @offset: offset from the start of the file.
1174 * @uc: consumer which wants to add more or remove some breakpoints
1175 * @add: add or remove the breakpoints
1177 int uprobe_apply(struct inode *inode, loff_t offset,
1178 struct uprobe_consumer *uc, bool add)
1180 struct uprobe *uprobe;
1181 struct uprobe_consumer *con;
1184 uprobe = find_uprobe(inode, offset);
1185 if (WARN_ON(!uprobe))
1188 down_write(&uprobe->register_rwsem);
1189 for (con = uprobe->consumers; con && con != uc ; con = con->next)
1192 ret = register_for_each_vma(uprobe, add ? uc : NULL);
1193 up_write(&uprobe->register_rwsem);
1199 static int unapply_uprobe(struct uprobe *uprobe, struct mm_struct *mm)
1201 struct vm_area_struct *vma;
1204 down_read(&mm->mmap_sem);
1205 for (vma = mm->mmap; vma; vma = vma->vm_next) {
1206 unsigned long vaddr;
1209 if (!valid_vma(vma, false) ||
1210 file_inode(vma->vm_file) != uprobe->inode)
1213 offset = (loff_t)vma->vm_pgoff << PAGE_SHIFT;
1214 if (uprobe->offset < offset ||
1215 uprobe->offset >= offset + vma->vm_end - vma->vm_start)
1218 vaddr = offset_to_vaddr(vma, uprobe->offset);
1219 err |= remove_breakpoint(uprobe, mm, vaddr);
1221 up_read(&mm->mmap_sem);
1226 static struct rb_node *
1227 find_node_in_range(struct inode *inode, loff_t min, loff_t max)
1229 struct rb_node *n = uprobes_tree.rb_node;
1232 struct uprobe *u = rb_entry(n, struct uprobe, rb_node);
1234 if (inode < u->inode) {
1236 } else if (inode > u->inode) {
1239 if (max < u->offset)
1241 else if (min > u->offset)
1252 * For a given range in vma, build a list of probes that need to be inserted.
1254 static void build_probe_list(struct inode *inode,
1255 struct vm_area_struct *vma,
1256 unsigned long start, unsigned long end,
1257 struct list_head *head)
1260 struct rb_node *n, *t;
1263 INIT_LIST_HEAD(head);
1264 min = vaddr_to_offset(vma, start);
1265 max = min + (end - start) - 1;
1267 spin_lock(&uprobes_treelock);
1268 n = find_node_in_range(inode, min, max);
1270 for (t = n; t; t = rb_prev(t)) {
1271 u = rb_entry(t, struct uprobe, rb_node);
1272 if (u->inode != inode || u->offset < min)
1274 list_add(&u->pending_list, head);
1277 for (t = n; (t = rb_next(t)); ) {
1278 u = rb_entry(t, struct uprobe, rb_node);
1279 if (u->inode != inode || u->offset > max)
1281 list_add(&u->pending_list, head);
1285 spin_unlock(&uprobes_treelock);
1288 /* @vma contains reference counter, not the probed instruction. */
1289 static int delayed_ref_ctr_inc(struct vm_area_struct *vma)
1291 struct list_head *pos, *q;
1292 struct delayed_uprobe *du;
1293 unsigned long vaddr;
1294 int ret = 0, err = 0;
1296 mutex_lock(&delayed_uprobe_lock);
1297 list_for_each_safe(pos, q, &delayed_uprobe_list) {
1298 du = list_entry(pos, struct delayed_uprobe, list);
1300 if (du->mm != vma->vm_mm ||
1301 !valid_ref_ctr_vma(du->uprobe, vma))
1304 vaddr = offset_to_vaddr(vma, du->uprobe->ref_ctr_offset);
1305 ret = __update_ref_ctr(vma->vm_mm, vaddr, 1);
1307 update_ref_ctr_warn(du->uprobe, vma->vm_mm, 1);
1311 delayed_uprobe_delete(du);
1313 mutex_unlock(&delayed_uprobe_lock);
1318 * Called from mmap_region/vma_adjust with mm->mmap_sem acquired.
1320 * Currently we ignore all errors and always return 0, the callers
1321 * can't handle the failure anyway.
1323 int uprobe_mmap(struct vm_area_struct *vma)
1325 struct list_head tmp_list;
1326 struct uprobe *uprobe, *u;
1327 struct inode *inode;
1329 if (no_uprobe_events())
1333 (vma->vm_flags & (VM_WRITE|VM_SHARED)) == VM_WRITE &&
1334 test_bit(MMF_HAS_UPROBES, &vma->vm_mm->flags))
1335 delayed_ref_ctr_inc(vma);
1337 if (!valid_vma(vma, true))
1340 inode = file_inode(vma->vm_file);
1344 mutex_lock(uprobes_mmap_hash(inode));
1345 build_probe_list(inode, vma, vma->vm_start, vma->vm_end, &tmp_list);
1347 * We can race with uprobe_unregister(), this uprobe can be already
1348 * removed. But in this case filter_chain() must return false, all
1349 * consumers have gone away.
1351 list_for_each_entry_safe(uprobe, u, &tmp_list, pending_list) {
1352 if (!fatal_signal_pending(current) &&
1353 filter_chain(uprobe, UPROBE_FILTER_MMAP, vma->vm_mm)) {
1354 unsigned long vaddr = offset_to_vaddr(vma, uprobe->offset);
1355 install_breakpoint(uprobe, vma->vm_mm, vma, vaddr);
1359 mutex_unlock(uprobes_mmap_hash(inode));
1365 vma_has_uprobes(struct vm_area_struct *vma, unsigned long start, unsigned long end)
1368 struct inode *inode;
1371 inode = file_inode(vma->vm_file);
1373 min = vaddr_to_offset(vma, start);
1374 max = min + (end - start) - 1;
1376 spin_lock(&uprobes_treelock);
1377 n = find_node_in_range(inode, min, max);
1378 spin_unlock(&uprobes_treelock);
1384 * Called in context of a munmap of a vma.
1386 void uprobe_munmap(struct vm_area_struct *vma, unsigned long start, unsigned long end)
1388 if (no_uprobe_events() || !valid_vma(vma, false))
1391 if (!atomic_read(&vma->vm_mm->mm_users)) /* called by mmput() ? */
1394 if (!test_bit(MMF_HAS_UPROBES, &vma->vm_mm->flags) ||
1395 test_bit(MMF_RECALC_UPROBES, &vma->vm_mm->flags))
1398 if (vma_has_uprobes(vma, start, end))
1399 set_bit(MMF_RECALC_UPROBES, &vma->vm_mm->flags);
1402 /* Slot allocation for XOL */
1403 static int xol_add_vma(struct mm_struct *mm, struct xol_area *area)
1405 struct vm_area_struct *vma;
1408 if (down_write_killable(&mm->mmap_sem))
1411 if (mm->uprobes_state.xol_area) {
1417 /* Try to map as high as possible, this is only a hint. */
1418 area->vaddr = get_unmapped_area(NULL, TASK_SIZE - PAGE_SIZE,
1420 if (area->vaddr & ~PAGE_MASK) {
1426 vma = _install_special_mapping(mm, area->vaddr, PAGE_SIZE,
1427 VM_EXEC|VM_MAYEXEC|VM_DONTCOPY|VM_IO,
1428 &area->xol_mapping);
1435 /* pairs with get_xol_area() */
1436 smp_store_release(&mm->uprobes_state.xol_area, area); /* ^^^ */
1438 up_write(&mm->mmap_sem);
1443 static struct xol_area *__create_xol_area(unsigned long vaddr)
1445 struct mm_struct *mm = current->mm;
1446 uprobe_opcode_t insn = UPROBE_SWBP_INSN;
1447 struct xol_area *area;
1449 area = kmalloc(sizeof(*area), GFP_KERNEL);
1450 if (unlikely(!area))
1453 area->bitmap = kcalloc(BITS_TO_LONGS(UINSNS_PER_PAGE), sizeof(long),
1458 area->xol_mapping.name = "[uprobes]";
1459 area->xol_mapping.fault = NULL;
1460 area->xol_mapping.pages = area->pages;
1461 area->pages[0] = alloc_page(GFP_HIGHUSER);
1462 if (!area->pages[0])
1464 area->pages[1] = NULL;
1466 area->vaddr = vaddr;
1467 init_waitqueue_head(&area->wq);
1468 /* Reserve the 1st slot for get_trampoline_vaddr() */
1469 set_bit(0, area->bitmap);
1470 atomic_set(&area->slot_count, 1);
1471 arch_uprobe_copy_ixol(area->pages[0], 0, &insn, UPROBE_SWBP_INSN_SIZE);
1473 if (!xol_add_vma(mm, area))
1476 __free_page(area->pages[0]);
1478 kfree(area->bitmap);
1486 * get_xol_area - Allocate process's xol_area if necessary.
1487 * This area will be used for storing instructions for execution out of line.
1489 * Returns the allocated area or NULL.
1491 static struct xol_area *get_xol_area(void)
1493 struct mm_struct *mm = current->mm;
1494 struct xol_area *area;
1496 if (!mm->uprobes_state.xol_area)
1497 __create_xol_area(0);
1499 /* Pairs with xol_add_vma() smp_store_release() */
1500 area = READ_ONCE(mm->uprobes_state.xol_area); /* ^^^ */
1505 * uprobe_clear_state - Free the area allocated for slots.
1507 void uprobe_clear_state(struct mm_struct *mm)
1509 struct xol_area *area = mm->uprobes_state.xol_area;
1511 mutex_lock(&delayed_uprobe_lock);
1512 delayed_uprobe_remove(NULL, mm);
1513 mutex_unlock(&delayed_uprobe_lock);
1518 put_page(area->pages[0]);
1519 kfree(area->bitmap);
1523 void uprobe_start_dup_mmap(void)
1525 percpu_down_read(&dup_mmap_sem);
1528 void uprobe_end_dup_mmap(void)
1530 percpu_up_read(&dup_mmap_sem);
1533 void uprobe_dup_mmap(struct mm_struct *oldmm, struct mm_struct *newmm)
1535 if (test_bit(MMF_HAS_UPROBES, &oldmm->flags)) {
1536 set_bit(MMF_HAS_UPROBES, &newmm->flags);
1537 /* unconditionally, dup_mmap() skips VM_DONTCOPY vmas */
1538 set_bit(MMF_RECALC_UPROBES, &newmm->flags);
1543 * - search for a free slot.
1545 static unsigned long xol_take_insn_slot(struct xol_area *area)
1547 unsigned long slot_addr;
1551 slot_nr = find_first_zero_bit(area->bitmap, UINSNS_PER_PAGE);
1552 if (slot_nr < UINSNS_PER_PAGE) {
1553 if (!test_and_set_bit(slot_nr, area->bitmap))
1556 slot_nr = UINSNS_PER_PAGE;
1559 wait_event(area->wq, (atomic_read(&area->slot_count) < UINSNS_PER_PAGE));
1560 } while (slot_nr >= UINSNS_PER_PAGE);
1562 slot_addr = area->vaddr + (slot_nr * UPROBE_XOL_SLOT_BYTES);
1563 atomic_inc(&area->slot_count);
1569 * xol_get_insn_slot - allocate a slot for xol.
1570 * Returns the allocated slot address or 0.
1572 static unsigned long xol_get_insn_slot(struct uprobe *uprobe)
1574 struct xol_area *area;
1575 unsigned long xol_vaddr;
1577 area = get_xol_area();
1581 xol_vaddr = xol_take_insn_slot(area);
1582 if (unlikely(!xol_vaddr))
1585 arch_uprobe_copy_ixol(area->pages[0], xol_vaddr,
1586 &uprobe->arch.ixol, sizeof(uprobe->arch.ixol));
1592 * xol_free_insn_slot - If slot was earlier allocated by
1593 * @xol_get_insn_slot(), make the slot available for
1594 * subsequent requests.
1596 static void xol_free_insn_slot(struct task_struct *tsk)
1598 struct xol_area *area;
1599 unsigned long vma_end;
1600 unsigned long slot_addr;
1602 if (!tsk->mm || !tsk->mm->uprobes_state.xol_area || !tsk->utask)
1605 slot_addr = tsk->utask->xol_vaddr;
1606 if (unlikely(!slot_addr))
1609 area = tsk->mm->uprobes_state.xol_area;
1610 vma_end = area->vaddr + PAGE_SIZE;
1611 if (area->vaddr <= slot_addr && slot_addr < vma_end) {
1612 unsigned long offset;
1615 offset = slot_addr - area->vaddr;
1616 slot_nr = offset / UPROBE_XOL_SLOT_BYTES;
1617 if (slot_nr >= UINSNS_PER_PAGE)
1620 clear_bit(slot_nr, area->bitmap);
1621 atomic_dec(&area->slot_count);
1622 smp_mb__after_atomic(); /* pairs with prepare_to_wait() */
1623 if (waitqueue_active(&area->wq))
1626 tsk->utask->xol_vaddr = 0;
1630 void __weak arch_uprobe_copy_ixol(struct page *page, unsigned long vaddr,
1631 void *src, unsigned long len)
1633 /* Initialize the slot */
1634 copy_to_page(page, vaddr, src, len);
1637 * We probably need flush_icache_user_range() but it needs vma.
1638 * This should work on most of architectures by default. If
1639 * architecture needs to do something different it can define
1640 * its own version of the function.
1642 flush_dcache_page(page);
1646 * uprobe_get_swbp_addr - compute address of swbp given post-swbp regs
1647 * @regs: Reflects the saved state of the task after it has hit a breakpoint
1649 * Return the address of the breakpoint instruction.
1651 unsigned long __weak uprobe_get_swbp_addr(struct pt_regs *regs)
1653 return instruction_pointer(regs) - UPROBE_SWBP_INSN_SIZE;
1656 unsigned long uprobe_get_trap_addr(struct pt_regs *regs)
1658 struct uprobe_task *utask = current->utask;
1660 if (unlikely(utask && utask->active_uprobe))
1661 return utask->vaddr;
1663 return instruction_pointer(regs);
1666 static struct return_instance *free_ret_instance(struct return_instance *ri)
1668 struct return_instance *next = ri->next;
1669 put_uprobe(ri->uprobe);
1675 * Called with no locks held.
1676 * Called in context of an exiting or an exec-ing thread.
1678 void uprobe_free_utask(struct task_struct *t)
1680 struct uprobe_task *utask = t->utask;
1681 struct return_instance *ri;
1686 if (utask->active_uprobe)
1687 put_uprobe(utask->active_uprobe);
1689 ri = utask->return_instances;
1691 ri = free_ret_instance(ri);
1693 xol_free_insn_slot(t);
1699 * Allocate a uprobe_task object for the task if if necessary.
1700 * Called when the thread hits a breakpoint.
1703 * - pointer to new uprobe_task on success
1706 static struct uprobe_task *get_utask(void)
1708 if (!current->utask)
1709 current->utask = kzalloc(sizeof(struct uprobe_task), GFP_KERNEL);
1710 return current->utask;
1713 static int dup_utask(struct task_struct *t, struct uprobe_task *o_utask)
1715 struct uprobe_task *n_utask;
1716 struct return_instance **p, *o, *n;
1718 n_utask = kzalloc(sizeof(struct uprobe_task), GFP_KERNEL);
1723 p = &n_utask->return_instances;
1724 for (o = o_utask->return_instances; o; o = o->next) {
1725 n = kmalloc(sizeof(struct return_instance), GFP_KERNEL);
1730 get_uprobe(n->uprobe);
1741 static void uprobe_warn(struct task_struct *t, const char *msg)
1743 pr_warn("uprobe: %s:%d failed to %s\n",
1744 current->comm, current->pid, msg);
1747 static void dup_xol_work(struct callback_head *work)
1749 if (current->flags & PF_EXITING)
1752 if (!__create_xol_area(current->utask->dup_xol_addr) &&
1753 !fatal_signal_pending(current))
1754 uprobe_warn(current, "dup xol area");
1758 * Called in context of a new clone/fork from copy_process.
1760 void uprobe_copy_process(struct task_struct *t, unsigned long flags)
1762 struct uprobe_task *utask = current->utask;
1763 struct mm_struct *mm = current->mm;
1764 struct xol_area *area;
1768 if (!utask || !utask->return_instances)
1771 if (mm == t->mm && !(flags & CLONE_VFORK))
1774 if (dup_utask(t, utask))
1775 return uprobe_warn(t, "dup ret instances");
1777 /* The task can fork() after dup_xol_work() fails */
1778 area = mm->uprobes_state.xol_area;
1780 return uprobe_warn(t, "dup xol area");
1785 t->utask->dup_xol_addr = area->vaddr;
1786 init_task_work(&t->utask->dup_xol_work, dup_xol_work);
1787 task_work_add(t, &t->utask->dup_xol_work, true);
1791 * Current area->vaddr notion assume the trampoline address is always
1792 * equal area->vaddr.
1794 * Returns -1 in case the xol_area is not allocated.
1796 static unsigned long get_trampoline_vaddr(void)
1798 struct xol_area *area;
1799 unsigned long trampoline_vaddr = -1;
1801 /* Pairs with xol_add_vma() smp_store_release() */
1802 area = READ_ONCE(current->mm->uprobes_state.xol_area); /* ^^^ */
1804 trampoline_vaddr = area->vaddr;
1806 return trampoline_vaddr;
1809 static void cleanup_return_instances(struct uprobe_task *utask, bool chained,
1810 struct pt_regs *regs)
1812 struct return_instance *ri = utask->return_instances;
1813 enum rp_check ctx = chained ? RP_CHECK_CHAIN_CALL : RP_CHECK_CALL;
1815 while (ri && !arch_uretprobe_is_alive(ri, ctx, regs)) {
1816 ri = free_ret_instance(ri);
1819 utask->return_instances = ri;
1822 static void prepare_uretprobe(struct uprobe *uprobe, struct pt_regs *regs)
1824 struct return_instance *ri;
1825 struct uprobe_task *utask;
1826 unsigned long orig_ret_vaddr, trampoline_vaddr;
1829 if (!get_xol_area())
1832 utask = get_utask();
1836 if (utask->depth >= MAX_URETPROBE_DEPTH) {
1837 printk_ratelimited(KERN_INFO "uprobe: omit uretprobe due to"
1838 " nestedness limit pid/tgid=%d/%d\n",
1839 current->pid, current->tgid);
1843 ri = kmalloc(sizeof(struct return_instance), GFP_KERNEL);
1847 trampoline_vaddr = get_trampoline_vaddr();
1848 orig_ret_vaddr = arch_uretprobe_hijack_return_addr(trampoline_vaddr, regs);
1849 if (orig_ret_vaddr == -1)
1852 /* drop the entries invalidated by longjmp() */
1853 chained = (orig_ret_vaddr == trampoline_vaddr);
1854 cleanup_return_instances(utask, chained, regs);
1857 * We don't want to keep trampoline address in stack, rather keep the
1858 * original return address of first caller thru all the consequent
1859 * instances. This also makes breakpoint unwrapping easier.
1862 if (!utask->return_instances) {
1864 * This situation is not possible. Likely we have an
1865 * attack from user-space.
1867 uprobe_warn(current, "handle tail call");
1870 orig_ret_vaddr = utask->return_instances->orig_ret_vaddr;
1873 ri->uprobe = get_uprobe(uprobe);
1874 ri->func = instruction_pointer(regs);
1875 ri->stack = user_stack_pointer(regs);
1876 ri->orig_ret_vaddr = orig_ret_vaddr;
1877 ri->chained = chained;
1880 ri->next = utask->return_instances;
1881 utask->return_instances = ri;
1888 /* Prepare to single-step probed instruction out of line. */
1890 pre_ssout(struct uprobe *uprobe, struct pt_regs *regs, unsigned long bp_vaddr)
1892 struct uprobe_task *utask;
1893 unsigned long xol_vaddr;
1896 utask = get_utask();
1900 xol_vaddr = xol_get_insn_slot(uprobe);
1904 utask->xol_vaddr = xol_vaddr;
1905 utask->vaddr = bp_vaddr;
1907 err = arch_uprobe_pre_xol(&uprobe->arch, regs);
1908 if (unlikely(err)) {
1909 xol_free_insn_slot(current);
1913 utask->active_uprobe = uprobe;
1914 utask->state = UTASK_SSTEP;
1919 * If we are singlestepping, then ensure this thread is not connected to
1920 * non-fatal signals until completion of singlestep. When xol insn itself
1921 * triggers the signal, restart the original insn even if the task is
1922 * already SIGKILL'ed (since coredump should report the correct ip). This
1923 * is even more important if the task has a handler for SIGSEGV/etc, The
1924 * _same_ instruction should be repeated again after return from the signal
1925 * handler, and SSTEP can never finish in this case.
1927 bool uprobe_deny_signal(void)
1929 struct task_struct *t = current;
1930 struct uprobe_task *utask = t->utask;
1932 if (likely(!utask || !utask->active_uprobe))
1935 WARN_ON_ONCE(utask->state != UTASK_SSTEP);
1937 if (signal_pending(t)) {
1938 spin_lock_irq(&t->sighand->siglock);
1939 clear_tsk_thread_flag(t, TIF_SIGPENDING);
1940 spin_unlock_irq(&t->sighand->siglock);
1942 if (__fatal_signal_pending(t) || arch_uprobe_xol_was_trapped(t)) {
1943 utask->state = UTASK_SSTEP_TRAPPED;
1944 set_tsk_thread_flag(t, TIF_UPROBE);
1951 static void mmf_recalc_uprobes(struct mm_struct *mm)
1953 struct vm_area_struct *vma;
1955 for (vma = mm->mmap; vma; vma = vma->vm_next) {
1956 if (!valid_vma(vma, false))
1959 * This is not strictly accurate, we can race with
1960 * uprobe_unregister() and see the already removed
1961 * uprobe if delete_uprobe() was not yet called.
1962 * Or this uprobe can be filtered out.
1964 if (vma_has_uprobes(vma, vma->vm_start, vma->vm_end))
1968 clear_bit(MMF_HAS_UPROBES, &mm->flags);
1971 static int is_trap_at_addr(struct mm_struct *mm, unsigned long vaddr)
1974 uprobe_opcode_t opcode;
1977 pagefault_disable();
1978 result = __get_user(opcode, (uprobe_opcode_t __user *)vaddr);
1981 if (likely(result == 0))
1985 * The NULL 'tsk' here ensures that any faults that occur here
1986 * will not be accounted to the task. 'mm' *is* current->mm,
1987 * but we treat this as a 'remote' access since it is
1988 * essentially a kernel access to the memory.
1990 result = get_user_pages_remote(NULL, mm, vaddr, 1, FOLL_FORCE, &page,
1995 copy_from_page(page, vaddr, &opcode, UPROBE_SWBP_INSN_SIZE);
1998 /* This needs to return true for any variant of the trap insn */
1999 return is_trap_insn(&opcode);
2002 static struct uprobe *find_active_uprobe(unsigned long bp_vaddr, int *is_swbp)
2004 struct mm_struct *mm = current->mm;
2005 struct uprobe *uprobe = NULL;
2006 struct vm_area_struct *vma;
2008 down_read(&mm->mmap_sem);
2009 vma = find_vma(mm, bp_vaddr);
2010 if (vma && vma->vm_start <= bp_vaddr) {
2011 if (valid_vma(vma, false)) {
2012 struct inode *inode = file_inode(vma->vm_file);
2013 loff_t offset = vaddr_to_offset(vma, bp_vaddr);
2015 uprobe = find_uprobe(inode, offset);
2019 *is_swbp = is_trap_at_addr(mm, bp_vaddr);
2024 if (!uprobe && test_and_clear_bit(MMF_RECALC_UPROBES, &mm->flags))
2025 mmf_recalc_uprobes(mm);
2026 up_read(&mm->mmap_sem);
2031 static void handler_chain(struct uprobe *uprobe, struct pt_regs *regs)
2033 struct uprobe_consumer *uc;
2034 int remove = UPROBE_HANDLER_REMOVE;
2035 bool need_prep = false; /* prepare return uprobe, when needed */
2037 down_read(&uprobe->register_rwsem);
2038 for (uc = uprobe->consumers; uc; uc = uc->next) {
2042 rc = uc->handler(uc, regs);
2043 WARN(rc & ~UPROBE_HANDLER_MASK,
2044 "bad rc=0x%x from %pf()\n", rc, uc->handler);
2047 if (uc->ret_handler)
2053 if (need_prep && !remove)
2054 prepare_uretprobe(uprobe, regs); /* put bp at return */
2056 if (remove && uprobe->consumers) {
2057 WARN_ON(!uprobe_is_active(uprobe));
2058 unapply_uprobe(uprobe, current->mm);
2060 up_read(&uprobe->register_rwsem);
2064 handle_uretprobe_chain(struct return_instance *ri, struct pt_regs *regs)
2066 struct uprobe *uprobe = ri->uprobe;
2067 struct uprobe_consumer *uc;
2069 down_read(&uprobe->register_rwsem);
2070 for (uc = uprobe->consumers; uc; uc = uc->next) {
2071 if (uc->ret_handler)
2072 uc->ret_handler(uc, ri->func, regs);
2074 up_read(&uprobe->register_rwsem);
2077 static struct return_instance *find_next_ret_chain(struct return_instance *ri)
2082 chained = ri->chained;
2083 ri = ri->next; /* can't be NULL if chained */
2089 static void handle_trampoline(struct pt_regs *regs)
2091 struct uprobe_task *utask;
2092 struct return_instance *ri, *next;
2095 utask = current->utask;
2099 ri = utask->return_instances;
2105 * We should throw out the frames invalidated by longjmp().
2106 * If this chain is valid, then the next one should be alive
2107 * or NULL; the latter case means that nobody but ri->func
2108 * could hit this trampoline on return. TODO: sigaltstack().
2110 next = find_next_ret_chain(ri);
2111 valid = !next || arch_uretprobe_is_alive(next, RP_CHECK_RET, regs);
2113 instruction_pointer_set(regs, ri->orig_ret_vaddr);
2116 handle_uretprobe_chain(ri, regs);
2117 ri = free_ret_instance(ri);
2119 } while (ri != next);
2122 utask->return_instances = ri;
2126 uprobe_warn(current, "handle uretprobe, sending SIGILL.");
2127 force_sig(SIGILL, current);
2131 bool __weak arch_uprobe_ignore(struct arch_uprobe *aup, struct pt_regs *regs)
2136 bool __weak arch_uretprobe_is_alive(struct return_instance *ret, enum rp_check ctx,
2137 struct pt_regs *regs)
2143 * Run handler and ask thread to singlestep.
2144 * Ensure all non-fatal signals cannot interrupt thread while it singlesteps.
2146 static void handle_swbp(struct pt_regs *regs)
2148 struct uprobe *uprobe;
2149 unsigned long bp_vaddr;
2150 int uninitialized_var(is_swbp);
2152 bp_vaddr = uprobe_get_swbp_addr(regs);
2153 if (bp_vaddr == get_trampoline_vaddr())
2154 return handle_trampoline(regs);
2156 uprobe = find_active_uprobe(bp_vaddr, &is_swbp);
2159 /* No matching uprobe; signal SIGTRAP. */
2160 send_sig(SIGTRAP, current, 0);
2163 * Either we raced with uprobe_unregister() or we can't
2164 * access this memory. The latter is only possible if
2165 * another thread plays with our ->mm. In both cases
2166 * we can simply restart. If this vma was unmapped we
2167 * can pretend this insn was not executed yet and get
2168 * the (correct) SIGSEGV after restart.
2170 instruction_pointer_set(regs, bp_vaddr);
2175 /* change it in advance for ->handler() and restart */
2176 instruction_pointer_set(regs, bp_vaddr);
2179 * TODO: move copy_insn/etc into _register and remove this hack.
2180 * After we hit the bp, _unregister + _register can install the
2181 * new and not-yet-analyzed uprobe at the same address, restart.
2183 if (unlikely(!test_bit(UPROBE_COPY_INSN, &uprobe->flags)))
2187 * Pairs with the smp_wmb() in prepare_uprobe().
2189 * Guarantees that if we see the UPROBE_COPY_INSN bit set, then
2190 * we must also see the stores to &uprobe->arch performed by the
2191 * prepare_uprobe() call.
2195 /* Tracing handlers use ->utask to communicate with fetch methods */
2199 if (arch_uprobe_ignore(&uprobe->arch, regs))
2202 handler_chain(uprobe, regs);
2204 if (arch_uprobe_skip_sstep(&uprobe->arch, regs))
2207 if (!pre_ssout(uprobe, regs, bp_vaddr))
2210 /* arch_uprobe_skip_sstep() succeeded, or restart if can't singlestep */
2216 * Perform required fix-ups and disable singlestep.
2217 * Allow pending signals to take effect.
2219 static void handle_singlestep(struct uprobe_task *utask, struct pt_regs *regs)
2221 struct uprobe *uprobe;
2224 uprobe = utask->active_uprobe;
2225 if (utask->state == UTASK_SSTEP_ACK)
2226 err = arch_uprobe_post_xol(&uprobe->arch, regs);
2227 else if (utask->state == UTASK_SSTEP_TRAPPED)
2228 arch_uprobe_abort_xol(&uprobe->arch, regs);
2233 utask->active_uprobe = NULL;
2234 utask->state = UTASK_RUNNING;
2235 xol_free_insn_slot(current);
2237 spin_lock_irq(¤t->sighand->siglock);
2238 recalc_sigpending(); /* see uprobe_deny_signal() */
2239 spin_unlock_irq(¤t->sighand->siglock);
2241 if (unlikely(err)) {
2242 uprobe_warn(current, "execute the probed insn, sending SIGILL.");
2243 force_sig(SIGILL, current);
2248 * On breakpoint hit, breakpoint notifier sets the TIF_UPROBE flag and
2249 * allows the thread to return from interrupt. After that handle_swbp()
2250 * sets utask->active_uprobe.
2252 * On singlestep exception, singlestep notifier sets the TIF_UPROBE flag
2253 * and allows the thread to return from interrupt.
2255 * While returning to userspace, thread notices the TIF_UPROBE flag and calls
2256 * uprobe_notify_resume().
2258 void uprobe_notify_resume(struct pt_regs *regs)
2260 struct uprobe_task *utask;
2262 clear_thread_flag(TIF_UPROBE);
2264 utask = current->utask;
2265 if (utask && utask->active_uprobe)
2266 handle_singlestep(utask, regs);
2272 * uprobe_pre_sstep_notifier gets called from interrupt context as part of
2273 * notifier mechanism. Set TIF_UPROBE flag and indicate breakpoint hit.
2275 int uprobe_pre_sstep_notifier(struct pt_regs *regs)
2280 if (!test_bit(MMF_HAS_UPROBES, ¤t->mm->flags) &&
2281 (!current->utask || !current->utask->return_instances))
2284 set_thread_flag(TIF_UPROBE);
2289 * uprobe_post_sstep_notifier gets called in interrupt context as part of notifier
2290 * mechanism. Set TIF_UPROBE flag and indicate completion of singlestep.
2292 int uprobe_post_sstep_notifier(struct pt_regs *regs)
2294 struct uprobe_task *utask = current->utask;
2296 if (!current->mm || !utask || !utask->active_uprobe)
2297 /* task is currently not uprobed */
2300 utask->state = UTASK_SSTEP_ACK;
2301 set_thread_flag(TIF_UPROBE);
2305 static struct notifier_block uprobe_exception_nb = {
2306 .notifier_call = arch_uprobe_exception_notify,
2307 .priority = INT_MAX-1, /* notified after kprobes, kgdb */
2310 static int __init init_uprobes(void)
2314 for (i = 0; i < UPROBES_HASH_SZ; i++)
2315 mutex_init(&uprobes_mmap_mutex[i]);
2317 if (percpu_init_rwsem(&dup_mmap_sem))
2320 return register_die_notifier(&uprobe_exception_nb);
2322 __initcall(init_uprobes);