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 delayed_uprobe_remove(uprobe, NULL);
580 static int match_uprobe(struct uprobe *l, struct uprobe *r)
582 if (l->inode < r->inode)
585 if (l->inode > r->inode)
588 if (l->offset < r->offset)
591 if (l->offset > r->offset)
597 static struct uprobe *__find_uprobe(struct inode *inode, loff_t offset)
599 struct uprobe u = { .inode = inode, .offset = offset };
600 struct rb_node *n = uprobes_tree.rb_node;
601 struct uprobe *uprobe;
605 uprobe = rb_entry(n, struct uprobe, rb_node);
606 match = match_uprobe(&u, uprobe);
608 return get_uprobe(uprobe);
619 * Find a uprobe corresponding to a given inode:offset
620 * Acquires uprobes_treelock
622 static struct uprobe *find_uprobe(struct inode *inode, loff_t offset)
624 struct uprobe *uprobe;
626 spin_lock(&uprobes_treelock);
627 uprobe = __find_uprobe(inode, offset);
628 spin_unlock(&uprobes_treelock);
633 static struct uprobe *__insert_uprobe(struct uprobe *uprobe)
635 struct rb_node **p = &uprobes_tree.rb_node;
636 struct rb_node *parent = NULL;
642 u = rb_entry(parent, struct uprobe, rb_node);
643 match = match_uprobe(uprobe, u);
645 return get_uprobe(u);
648 p = &parent->rb_left;
650 p = &parent->rb_right;
655 rb_link_node(&uprobe->rb_node, parent, p);
656 rb_insert_color(&uprobe->rb_node, &uprobes_tree);
657 /* get access + creation ref */
658 atomic_set(&uprobe->ref, 2);
664 * Acquire uprobes_treelock.
665 * Matching uprobe already exists in rbtree;
666 * increment (access refcount) and return the matching uprobe.
668 * No matching uprobe; insert the uprobe in rb_tree;
669 * get a double refcount (access + creation) and return NULL.
671 static struct uprobe *insert_uprobe(struct uprobe *uprobe)
675 spin_lock(&uprobes_treelock);
676 u = __insert_uprobe(uprobe);
677 spin_unlock(&uprobes_treelock);
683 ref_ctr_mismatch_warn(struct uprobe *cur_uprobe, struct uprobe *uprobe)
685 pr_warn("ref_ctr_offset mismatch. inode: 0x%lx offset: 0x%llx "
686 "ref_ctr_offset(old): 0x%llx ref_ctr_offset(new): 0x%llx\n",
687 uprobe->inode->i_ino, (unsigned long long) uprobe->offset,
688 (unsigned long long) cur_uprobe->ref_ctr_offset,
689 (unsigned long long) uprobe->ref_ctr_offset);
692 static struct uprobe *alloc_uprobe(struct inode *inode, loff_t offset,
693 loff_t ref_ctr_offset)
695 struct uprobe *uprobe, *cur_uprobe;
697 uprobe = kzalloc(sizeof(struct uprobe), GFP_KERNEL);
701 uprobe->inode = inode;
702 uprobe->offset = offset;
703 uprobe->ref_ctr_offset = ref_ctr_offset;
704 init_rwsem(&uprobe->register_rwsem);
705 init_rwsem(&uprobe->consumer_rwsem);
707 /* add to uprobes_tree, sorted on inode:offset */
708 cur_uprobe = insert_uprobe(uprobe);
709 /* a uprobe exists for this inode:offset combination */
711 if (cur_uprobe->ref_ctr_offset != uprobe->ref_ctr_offset) {
712 ref_ctr_mismatch_warn(cur_uprobe, uprobe);
713 put_uprobe(cur_uprobe);
715 return ERR_PTR(-EINVAL);
724 static void consumer_add(struct uprobe *uprobe, struct uprobe_consumer *uc)
726 down_write(&uprobe->consumer_rwsem);
727 uc->next = uprobe->consumers;
728 uprobe->consumers = uc;
729 up_write(&uprobe->consumer_rwsem);
733 * For uprobe @uprobe, delete the consumer @uc.
734 * Return true if the @uc is deleted successfully
737 static bool consumer_del(struct uprobe *uprobe, struct uprobe_consumer *uc)
739 struct uprobe_consumer **con;
742 down_write(&uprobe->consumer_rwsem);
743 for (con = &uprobe->consumers; *con; con = &(*con)->next) {
750 up_write(&uprobe->consumer_rwsem);
755 static int __copy_insn(struct address_space *mapping, struct file *filp,
756 void *insn, int nbytes, loff_t offset)
760 * Ensure that the page that has the original instruction is populated
761 * and in page-cache. If ->readpage == NULL it must be shmem_mapping(),
762 * see uprobe_register().
764 if (mapping->a_ops->readpage)
765 page = read_mapping_page(mapping, offset >> PAGE_SHIFT, filp);
767 page = shmem_read_mapping_page(mapping, offset >> PAGE_SHIFT);
769 return PTR_ERR(page);
771 copy_from_page(page, offset, insn, nbytes);
777 static int copy_insn(struct uprobe *uprobe, struct file *filp)
779 struct address_space *mapping = uprobe->inode->i_mapping;
780 loff_t offs = uprobe->offset;
781 void *insn = &uprobe->arch.insn;
782 int size = sizeof(uprobe->arch.insn);
785 /* Copy only available bytes, -EIO if nothing was read */
787 if (offs >= i_size_read(uprobe->inode))
790 len = min_t(int, size, PAGE_SIZE - (offs & ~PAGE_MASK));
791 err = __copy_insn(mapping, filp, insn, len, offs);
803 static int prepare_uprobe(struct uprobe *uprobe, struct file *file,
804 struct mm_struct *mm, unsigned long vaddr)
808 if (test_bit(UPROBE_COPY_INSN, &uprobe->flags))
811 /* TODO: move this into _register, until then we abuse this sem. */
812 down_write(&uprobe->consumer_rwsem);
813 if (test_bit(UPROBE_COPY_INSN, &uprobe->flags))
816 ret = copy_insn(uprobe, file);
821 if (is_trap_insn((uprobe_opcode_t *)&uprobe->arch.insn))
824 ret = arch_uprobe_analyze_insn(&uprobe->arch, mm, vaddr);
828 /* uprobe_write_opcode() assumes we don't cross page boundary */
829 BUG_ON((uprobe->offset & ~PAGE_MASK) +
830 UPROBE_SWBP_INSN_SIZE > PAGE_SIZE);
832 smp_wmb(); /* pairs with the smp_rmb() in handle_swbp() */
833 set_bit(UPROBE_COPY_INSN, &uprobe->flags);
836 up_write(&uprobe->consumer_rwsem);
841 static inline bool consumer_filter(struct uprobe_consumer *uc,
842 enum uprobe_filter_ctx ctx, struct mm_struct *mm)
844 return !uc->filter || uc->filter(uc, ctx, mm);
847 static bool filter_chain(struct uprobe *uprobe,
848 enum uprobe_filter_ctx ctx, struct mm_struct *mm)
850 struct uprobe_consumer *uc;
853 down_read(&uprobe->consumer_rwsem);
854 for (uc = uprobe->consumers; uc; uc = uc->next) {
855 ret = consumer_filter(uc, ctx, mm);
859 up_read(&uprobe->consumer_rwsem);
865 install_breakpoint(struct uprobe *uprobe, struct mm_struct *mm,
866 struct vm_area_struct *vma, unsigned long vaddr)
871 ret = prepare_uprobe(uprobe, vma->vm_file, mm, vaddr);
876 * set MMF_HAS_UPROBES in advance for uprobe_pre_sstep_notifier(),
877 * the task can hit this breakpoint right after __replace_page().
879 first_uprobe = !test_bit(MMF_HAS_UPROBES, &mm->flags);
881 set_bit(MMF_HAS_UPROBES, &mm->flags);
883 ret = set_swbp(&uprobe->arch, mm, vaddr);
885 clear_bit(MMF_RECALC_UPROBES, &mm->flags);
886 else if (first_uprobe)
887 clear_bit(MMF_HAS_UPROBES, &mm->flags);
893 remove_breakpoint(struct uprobe *uprobe, struct mm_struct *mm, unsigned long vaddr)
895 set_bit(MMF_RECALC_UPROBES, &mm->flags);
896 return set_orig_insn(&uprobe->arch, mm, vaddr);
899 static inline bool uprobe_is_active(struct uprobe *uprobe)
901 return !RB_EMPTY_NODE(&uprobe->rb_node);
904 * There could be threads that have already hit the breakpoint. They
905 * will recheck the current insn and restart if find_uprobe() fails.
906 * See find_active_uprobe().
908 static void delete_uprobe(struct uprobe *uprobe)
910 if (WARN_ON(!uprobe_is_active(uprobe)))
913 spin_lock(&uprobes_treelock);
914 rb_erase(&uprobe->rb_node, &uprobes_tree);
915 spin_unlock(&uprobes_treelock);
916 RB_CLEAR_NODE(&uprobe->rb_node); /* for uprobe_is_active() */
921 struct map_info *next;
922 struct mm_struct *mm;
926 static inline struct map_info *free_map_info(struct map_info *info)
928 struct map_info *next = info->next;
933 static struct map_info *
934 build_map_info(struct address_space *mapping, loff_t offset, bool is_register)
936 unsigned long pgoff = offset >> PAGE_SHIFT;
937 struct vm_area_struct *vma;
938 struct map_info *curr = NULL;
939 struct map_info *prev = NULL;
940 struct map_info *info;
944 i_mmap_lock_read(mapping);
945 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
946 if (!valid_vma(vma, is_register))
949 if (!prev && !more) {
951 * Needs GFP_NOWAIT to avoid i_mmap_rwsem recursion through
952 * reclaim. This is optimistic, no harm done if it fails.
954 prev = kmalloc(sizeof(struct map_info),
955 GFP_NOWAIT | __GFP_NOMEMALLOC | __GFP_NOWARN);
964 if (!mmget_not_zero(vma->vm_mm))
972 info->mm = vma->vm_mm;
973 info->vaddr = offset_to_vaddr(vma, offset);
975 i_mmap_unlock_read(mapping);
987 info = kmalloc(sizeof(struct map_info), GFP_KERNEL);
989 curr = ERR_PTR(-ENOMEM);
999 prev = free_map_info(prev);
1004 register_for_each_vma(struct uprobe *uprobe, struct uprobe_consumer *new)
1006 bool is_register = !!new;
1007 struct map_info *info;
1010 percpu_down_write(&dup_mmap_sem);
1011 info = build_map_info(uprobe->inode->i_mapping,
1012 uprobe->offset, is_register);
1014 err = PTR_ERR(info);
1019 struct mm_struct *mm = info->mm;
1020 struct vm_area_struct *vma;
1022 if (err && is_register)
1025 down_write(&mm->mmap_sem);
1026 vma = find_vma(mm, info->vaddr);
1027 if (!vma || !valid_vma(vma, is_register) ||
1028 file_inode(vma->vm_file) != uprobe->inode)
1031 if (vma->vm_start > info->vaddr ||
1032 vaddr_to_offset(vma, info->vaddr) != uprobe->offset)
1036 /* consult only the "caller", new consumer. */
1037 if (consumer_filter(new,
1038 UPROBE_FILTER_REGISTER, mm))
1039 err = install_breakpoint(uprobe, mm, vma, info->vaddr);
1040 } else if (test_bit(MMF_HAS_UPROBES, &mm->flags)) {
1041 if (!filter_chain(uprobe,
1042 UPROBE_FILTER_UNREGISTER, mm))
1043 err |= remove_breakpoint(uprobe, mm, info->vaddr);
1047 up_write(&mm->mmap_sem);
1050 info = free_map_info(info);
1053 percpu_up_write(&dup_mmap_sem);
1058 __uprobe_unregister(struct uprobe *uprobe, struct uprobe_consumer *uc)
1062 if (WARN_ON(!consumer_del(uprobe, uc)))
1065 err = register_for_each_vma(uprobe, NULL);
1066 /* TODO : cant unregister? schedule a worker thread */
1067 if (!uprobe->consumers && !err)
1068 delete_uprobe(uprobe);
1072 * uprobe_unregister - unregister an already registered probe.
1073 * @inode: the file in which the probe has to be removed.
1074 * @offset: offset from the start of the file.
1075 * @uc: identify which probe if multiple probes are colocated.
1077 void uprobe_unregister(struct inode *inode, loff_t offset, struct uprobe_consumer *uc)
1079 struct uprobe *uprobe;
1081 uprobe = find_uprobe(inode, offset);
1082 if (WARN_ON(!uprobe))
1085 down_write(&uprobe->register_rwsem);
1086 __uprobe_unregister(uprobe, uc);
1087 up_write(&uprobe->register_rwsem);
1090 EXPORT_SYMBOL_GPL(uprobe_unregister);
1093 * __uprobe_register - register a probe
1094 * @inode: the file in which the probe has to be placed.
1095 * @offset: offset from the start of the file.
1096 * @uc: information on howto handle the probe..
1098 * Apart from the access refcount, __uprobe_register() takes a creation
1099 * refcount (thro alloc_uprobe) if and only if this @uprobe is getting
1100 * inserted into the rbtree (i.e first consumer for a @inode:@offset
1101 * tuple). Creation refcount stops uprobe_unregister from freeing the
1102 * @uprobe even before the register operation is complete. Creation
1103 * refcount is released when the last @uc for the @uprobe
1104 * unregisters. Caller of __uprobe_register() is required to keep @inode
1105 * (and the containing mount) referenced.
1107 * Return errno if it cannot successully install probes
1108 * else return 0 (success)
1110 static int __uprobe_register(struct inode *inode, loff_t offset,
1111 loff_t ref_ctr_offset, struct uprobe_consumer *uc)
1113 struct uprobe *uprobe;
1116 /* Uprobe must have at least one set consumer */
1117 if (!uc->handler && !uc->ret_handler)
1120 /* copy_insn() uses read_mapping_page() or shmem_read_mapping_page() */
1121 if (!inode->i_mapping->a_ops->readpage && !shmem_mapping(inode->i_mapping))
1123 /* Racy, just to catch the obvious mistakes */
1124 if (offset > i_size_read(inode))
1128 uprobe = alloc_uprobe(inode, offset, ref_ctr_offset);
1132 return PTR_ERR(uprobe);
1135 * We can race with uprobe_unregister()->delete_uprobe().
1136 * Check uprobe_is_active() and retry if it is false.
1138 down_write(&uprobe->register_rwsem);
1140 if (likely(uprobe_is_active(uprobe))) {
1141 consumer_add(uprobe, uc);
1142 ret = register_for_each_vma(uprobe, uc);
1144 __uprobe_unregister(uprobe, uc);
1146 up_write(&uprobe->register_rwsem);
1149 if (unlikely(ret == -EAGAIN))
1154 int uprobe_register(struct inode *inode, loff_t offset,
1155 struct uprobe_consumer *uc)
1157 return __uprobe_register(inode, offset, 0, uc);
1159 EXPORT_SYMBOL_GPL(uprobe_register);
1161 int uprobe_register_refctr(struct inode *inode, loff_t offset,
1162 loff_t ref_ctr_offset, struct uprobe_consumer *uc)
1164 return __uprobe_register(inode, offset, ref_ctr_offset, uc);
1166 EXPORT_SYMBOL_GPL(uprobe_register_refctr);
1169 * uprobe_apply - unregister an already registered probe.
1170 * @inode: the file in which the probe has to be removed.
1171 * @offset: offset from the start of the file.
1172 * @uc: consumer which wants to add more or remove some breakpoints
1173 * @add: add or remove the breakpoints
1175 int uprobe_apply(struct inode *inode, loff_t offset,
1176 struct uprobe_consumer *uc, bool add)
1178 struct uprobe *uprobe;
1179 struct uprobe_consumer *con;
1182 uprobe = find_uprobe(inode, offset);
1183 if (WARN_ON(!uprobe))
1186 down_write(&uprobe->register_rwsem);
1187 for (con = uprobe->consumers; con && con != uc ; con = con->next)
1190 ret = register_for_each_vma(uprobe, add ? uc : NULL);
1191 up_write(&uprobe->register_rwsem);
1197 static int unapply_uprobe(struct uprobe *uprobe, struct mm_struct *mm)
1199 struct vm_area_struct *vma;
1202 down_read(&mm->mmap_sem);
1203 for (vma = mm->mmap; vma; vma = vma->vm_next) {
1204 unsigned long vaddr;
1207 if (!valid_vma(vma, false) ||
1208 file_inode(vma->vm_file) != uprobe->inode)
1211 offset = (loff_t)vma->vm_pgoff << PAGE_SHIFT;
1212 if (uprobe->offset < offset ||
1213 uprobe->offset >= offset + vma->vm_end - vma->vm_start)
1216 vaddr = offset_to_vaddr(vma, uprobe->offset);
1217 err |= remove_breakpoint(uprobe, mm, vaddr);
1219 up_read(&mm->mmap_sem);
1224 static struct rb_node *
1225 find_node_in_range(struct inode *inode, loff_t min, loff_t max)
1227 struct rb_node *n = uprobes_tree.rb_node;
1230 struct uprobe *u = rb_entry(n, struct uprobe, rb_node);
1232 if (inode < u->inode) {
1234 } else if (inode > u->inode) {
1237 if (max < u->offset)
1239 else if (min > u->offset)
1250 * For a given range in vma, build a list of probes that need to be inserted.
1252 static void build_probe_list(struct inode *inode,
1253 struct vm_area_struct *vma,
1254 unsigned long start, unsigned long end,
1255 struct list_head *head)
1258 struct rb_node *n, *t;
1261 INIT_LIST_HEAD(head);
1262 min = vaddr_to_offset(vma, start);
1263 max = min + (end - start) - 1;
1265 spin_lock(&uprobes_treelock);
1266 n = find_node_in_range(inode, min, max);
1268 for (t = n; t; t = rb_prev(t)) {
1269 u = rb_entry(t, struct uprobe, rb_node);
1270 if (u->inode != inode || u->offset < min)
1272 list_add(&u->pending_list, head);
1275 for (t = n; (t = rb_next(t)); ) {
1276 u = rb_entry(t, struct uprobe, rb_node);
1277 if (u->inode != inode || u->offset > max)
1279 list_add(&u->pending_list, head);
1283 spin_unlock(&uprobes_treelock);
1286 /* @vma contains reference counter, not the probed instruction. */
1287 static int delayed_ref_ctr_inc(struct vm_area_struct *vma)
1289 struct list_head *pos, *q;
1290 struct delayed_uprobe *du;
1291 unsigned long vaddr;
1292 int ret = 0, err = 0;
1294 mutex_lock(&delayed_uprobe_lock);
1295 list_for_each_safe(pos, q, &delayed_uprobe_list) {
1296 du = list_entry(pos, struct delayed_uprobe, list);
1298 if (du->mm != vma->vm_mm ||
1299 !valid_ref_ctr_vma(du->uprobe, vma))
1302 vaddr = offset_to_vaddr(vma, du->uprobe->ref_ctr_offset);
1303 ret = __update_ref_ctr(vma->vm_mm, vaddr, 1);
1305 update_ref_ctr_warn(du->uprobe, vma->vm_mm, 1);
1309 delayed_uprobe_delete(du);
1311 mutex_unlock(&delayed_uprobe_lock);
1316 * Called from mmap_region/vma_adjust with mm->mmap_sem acquired.
1318 * Currently we ignore all errors and always return 0, the callers
1319 * can't handle the failure anyway.
1321 int uprobe_mmap(struct vm_area_struct *vma)
1323 struct list_head tmp_list;
1324 struct uprobe *uprobe, *u;
1325 struct inode *inode;
1327 if (no_uprobe_events())
1331 (vma->vm_flags & (VM_WRITE|VM_SHARED)) == VM_WRITE &&
1332 test_bit(MMF_HAS_UPROBES, &vma->vm_mm->flags))
1333 delayed_ref_ctr_inc(vma);
1335 if (!valid_vma(vma, true))
1338 inode = file_inode(vma->vm_file);
1342 mutex_lock(uprobes_mmap_hash(inode));
1343 build_probe_list(inode, vma, vma->vm_start, vma->vm_end, &tmp_list);
1345 * We can race with uprobe_unregister(), this uprobe can be already
1346 * removed. But in this case filter_chain() must return false, all
1347 * consumers have gone away.
1349 list_for_each_entry_safe(uprobe, u, &tmp_list, pending_list) {
1350 if (!fatal_signal_pending(current) &&
1351 filter_chain(uprobe, UPROBE_FILTER_MMAP, vma->vm_mm)) {
1352 unsigned long vaddr = offset_to_vaddr(vma, uprobe->offset);
1353 install_breakpoint(uprobe, vma->vm_mm, vma, vaddr);
1357 mutex_unlock(uprobes_mmap_hash(inode));
1363 vma_has_uprobes(struct vm_area_struct *vma, unsigned long start, unsigned long end)
1366 struct inode *inode;
1369 inode = file_inode(vma->vm_file);
1371 min = vaddr_to_offset(vma, start);
1372 max = min + (end - start) - 1;
1374 spin_lock(&uprobes_treelock);
1375 n = find_node_in_range(inode, min, max);
1376 spin_unlock(&uprobes_treelock);
1382 * Called in context of a munmap of a vma.
1384 void uprobe_munmap(struct vm_area_struct *vma, unsigned long start, unsigned long end)
1386 if (no_uprobe_events() || !valid_vma(vma, false))
1389 if (!atomic_read(&vma->vm_mm->mm_users)) /* called by mmput() ? */
1392 if (!test_bit(MMF_HAS_UPROBES, &vma->vm_mm->flags) ||
1393 test_bit(MMF_RECALC_UPROBES, &vma->vm_mm->flags))
1396 if (vma_has_uprobes(vma, start, end))
1397 set_bit(MMF_RECALC_UPROBES, &vma->vm_mm->flags);
1400 /* Slot allocation for XOL */
1401 static int xol_add_vma(struct mm_struct *mm, struct xol_area *area)
1403 struct vm_area_struct *vma;
1406 if (down_write_killable(&mm->mmap_sem))
1409 if (mm->uprobes_state.xol_area) {
1415 /* Try to map as high as possible, this is only a hint. */
1416 area->vaddr = get_unmapped_area(NULL, TASK_SIZE - PAGE_SIZE,
1418 if (area->vaddr & ~PAGE_MASK) {
1424 vma = _install_special_mapping(mm, area->vaddr, PAGE_SIZE,
1425 VM_EXEC|VM_MAYEXEC|VM_DONTCOPY|VM_IO,
1426 &area->xol_mapping);
1433 /* pairs with get_xol_area() */
1434 smp_store_release(&mm->uprobes_state.xol_area, area); /* ^^^ */
1436 up_write(&mm->mmap_sem);
1441 static struct xol_area *__create_xol_area(unsigned long vaddr)
1443 struct mm_struct *mm = current->mm;
1444 uprobe_opcode_t insn = UPROBE_SWBP_INSN;
1445 struct xol_area *area;
1447 area = kmalloc(sizeof(*area), GFP_KERNEL);
1448 if (unlikely(!area))
1451 area->bitmap = kcalloc(BITS_TO_LONGS(UINSNS_PER_PAGE), sizeof(long),
1456 area->xol_mapping.name = "[uprobes]";
1457 area->xol_mapping.fault = NULL;
1458 area->xol_mapping.pages = area->pages;
1459 area->pages[0] = alloc_page(GFP_HIGHUSER);
1460 if (!area->pages[0])
1462 area->pages[1] = NULL;
1464 area->vaddr = vaddr;
1465 init_waitqueue_head(&area->wq);
1466 /* Reserve the 1st slot for get_trampoline_vaddr() */
1467 set_bit(0, area->bitmap);
1468 atomic_set(&area->slot_count, 1);
1469 arch_uprobe_copy_ixol(area->pages[0], 0, &insn, UPROBE_SWBP_INSN_SIZE);
1471 if (!xol_add_vma(mm, area))
1474 __free_page(area->pages[0]);
1476 kfree(area->bitmap);
1484 * get_xol_area - Allocate process's xol_area if necessary.
1485 * This area will be used for storing instructions for execution out of line.
1487 * Returns the allocated area or NULL.
1489 static struct xol_area *get_xol_area(void)
1491 struct mm_struct *mm = current->mm;
1492 struct xol_area *area;
1494 if (!mm->uprobes_state.xol_area)
1495 __create_xol_area(0);
1497 /* Pairs with xol_add_vma() smp_store_release() */
1498 area = READ_ONCE(mm->uprobes_state.xol_area); /* ^^^ */
1503 * uprobe_clear_state - Free the area allocated for slots.
1505 void uprobe_clear_state(struct mm_struct *mm)
1507 struct xol_area *area = mm->uprobes_state.xol_area;
1509 mutex_lock(&delayed_uprobe_lock);
1510 delayed_uprobe_remove(NULL, mm);
1511 mutex_unlock(&delayed_uprobe_lock);
1516 put_page(area->pages[0]);
1517 kfree(area->bitmap);
1521 void uprobe_start_dup_mmap(void)
1523 percpu_down_read(&dup_mmap_sem);
1526 void uprobe_end_dup_mmap(void)
1528 percpu_up_read(&dup_mmap_sem);
1531 void uprobe_dup_mmap(struct mm_struct *oldmm, struct mm_struct *newmm)
1533 if (test_bit(MMF_HAS_UPROBES, &oldmm->flags)) {
1534 set_bit(MMF_HAS_UPROBES, &newmm->flags);
1535 /* unconditionally, dup_mmap() skips VM_DONTCOPY vmas */
1536 set_bit(MMF_RECALC_UPROBES, &newmm->flags);
1541 * - search for a free slot.
1543 static unsigned long xol_take_insn_slot(struct xol_area *area)
1545 unsigned long slot_addr;
1549 slot_nr = find_first_zero_bit(area->bitmap, UINSNS_PER_PAGE);
1550 if (slot_nr < UINSNS_PER_PAGE) {
1551 if (!test_and_set_bit(slot_nr, area->bitmap))
1554 slot_nr = UINSNS_PER_PAGE;
1557 wait_event(area->wq, (atomic_read(&area->slot_count) < UINSNS_PER_PAGE));
1558 } while (slot_nr >= UINSNS_PER_PAGE);
1560 slot_addr = area->vaddr + (slot_nr * UPROBE_XOL_SLOT_BYTES);
1561 atomic_inc(&area->slot_count);
1567 * xol_get_insn_slot - allocate a slot for xol.
1568 * Returns the allocated slot address or 0.
1570 static unsigned long xol_get_insn_slot(struct uprobe *uprobe)
1572 struct xol_area *area;
1573 unsigned long xol_vaddr;
1575 area = get_xol_area();
1579 xol_vaddr = xol_take_insn_slot(area);
1580 if (unlikely(!xol_vaddr))
1583 arch_uprobe_copy_ixol(area->pages[0], xol_vaddr,
1584 &uprobe->arch.ixol, sizeof(uprobe->arch.ixol));
1590 * xol_free_insn_slot - If slot was earlier allocated by
1591 * @xol_get_insn_slot(), make the slot available for
1592 * subsequent requests.
1594 static void xol_free_insn_slot(struct task_struct *tsk)
1596 struct xol_area *area;
1597 unsigned long vma_end;
1598 unsigned long slot_addr;
1600 if (!tsk->mm || !tsk->mm->uprobes_state.xol_area || !tsk->utask)
1603 slot_addr = tsk->utask->xol_vaddr;
1604 if (unlikely(!slot_addr))
1607 area = tsk->mm->uprobes_state.xol_area;
1608 vma_end = area->vaddr + PAGE_SIZE;
1609 if (area->vaddr <= slot_addr && slot_addr < vma_end) {
1610 unsigned long offset;
1613 offset = slot_addr - area->vaddr;
1614 slot_nr = offset / UPROBE_XOL_SLOT_BYTES;
1615 if (slot_nr >= UINSNS_PER_PAGE)
1618 clear_bit(slot_nr, area->bitmap);
1619 atomic_dec(&area->slot_count);
1620 smp_mb__after_atomic(); /* pairs with prepare_to_wait() */
1621 if (waitqueue_active(&area->wq))
1624 tsk->utask->xol_vaddr = 0;
1628 void __weak arch_uprobe_copy_ixol(struct page *page, unsigned long vaddr,
1629 void *src, unsigned long len)
1631 /* Initialize the slot */
1632 copy_to_page(page, vaddr, src, len);
1635 * We probably need flush_icache_user_range() but it needs vma.
1636 * This should work on most of architectures by default. If
1637 * architecture needs to do something different it can define
1638 * its own version of the function.
1640 flush_dcache_page(page);
1644 * uprobe_get_swbp_addr - compute address of swbp given post-swbp regs
1645 * @regs: Reflects the saved state of the task after it has hit a breakpoint
1647 * Return the address of the breakpoint instruction.
1649 unsigned long __weak uprobe_get_swbp_addr(struct pt_regs *regs)
1651 return instruction_pointer(regs) - UPROBE_SWBP_INSN_SIZE;
1654 unsigned long uprobe_get_trap_addr(struct pt_regs *regs)
1656 struct uprobe_task *utask = current->utask;
1658 if (unlikely(utask && utask->active_uprobe))
1659 return utask->vaddr;
1661 return instruction_pointer(regs);
1664 static struct return_instance *free_ret_instance(struct return_instance *ri)
1666 struct return_instance *next = ri->next;
1667 put_uprobe(ri->uprobe);
1673 * Called with no locks held.
1674 * Called in context of an exiting or an exec-ing thread.
1676 void uprobe_free_utask(struct task_struct *t)
1678 struct uprobe_task *utask = t->utask;
1679 struct return_instance *ri;
1684 if (utask->active_uprobe)
1685 put_uprobe(utask->active_uprobe);
1687 ri = utask->return_instances;
1689 ri = free_ret_instance(ri);
1691 xol_free_insn_slot(t);
1697 * Allocate a uprobe_task object for the task if if necessary.
1698 * Called when the thread hits a breakpoint.
1701 * - pointer to new uprobe_task on success
1704 static struct uprobe_task *get_utask(void)
1706 if (!current->utask)
1707 current->utask = kzalloc(sizeof(struct uprobe_task), GFP_KERNEL);
1708 return current->utask;
1711 static int dup_utask(struct task_struct *t, struct uprobe_task *o_utask)
1713 struct uprobe_task *n_utask;
1714 struct return_instance **p, *o, *n;
1716 n_utask = kzalloc(sizeof(struct uprobe_task), GFP_KERNEL);
1721 p = &n_utask->return_instances;
1722 for (o = o_utask->return_instances; o; o = o->next) {
1723 n = kmalloc(sizeof(struct return_instance), GFP_KERNEL);
1728 get_uprobe(n->uprobe);
1739 static void uprobe_warn(struct task_struct *t, const char *msg)
1741 pr_warn("uprobe: %s:%d failed to %s\n",
1742 current->comm, current->pid, msg);
1745 static void dup_xol_work(struct callback_head *work)
1747 if (current->flags & PF_EXITING)
1750 if (!__create_xol_area(current->utask->dup_xol_addr) &&
1751 !fatal_signal_pending(current))
1752 uprobe_warn(current, "dup xol area");
1756 * Called in context of a new clone/fork from copy_process.
1758 void uprobe_copy_process(struct task_struct *t, unsigned long flags)
1760 struct uprobe_task *utask = current->utask;
1761 struct mm_struct *mm = current->mm;
1762 struct xol_area *area;
1766 if (!utask || !utask->return_instances)
1769 if (mm == t->mm && !(flags & CLONE_VFORK))
1772 if (dup_utask(t, utask))
1773 return uprobe_warn(t, "dup ret instances");
1775 /* The task can fork() after dup_xol_work() fails */
1776 area = mm->uprobes_state.xol_area;
1778 return uprobe_warn(t, "dup xol area");
1783 t->utask->dup_xol_addr = area->vaddr;
1784 init_task_work(&t->utask->dup_xol_work, dup_xol_work);
1785 task_work_add(t, &t->utask->dup_xol_work, true);
1789 * Current area->vaddr notion assume the trampoline address is always
1790 * equal area->vaddr.
1792 * Returns -1 in case the xol_area is not allocated.
1794 static unsigned long get_trampoline_vaddr(void)
1796 struct xol_area *area;
1797 unsigned long trampoline_vaddr = -1;
1799 /* Pairs with xol_add_vma() smp_store_release() */
1800 area = READ_ONCE(current->mm->uprobes_state.xol_area); /* ^^^ */
1802 trampoline_vaddr = area->vaddr;
1804 return trampoline_vaddr;
1807 static void cleanup_return_instances(struct uprobe_task *utask, bool chained,
1808 struct pt_regs *regs)
1810 struct return_instance *ri = utask->return_instances;
1811 enum rp_check ctx = chained ? RP_CHECK_CHAIN_CALL : RP_CHECK_CALL;
1813 while (ri && !arch_uretprobe_is_alive(ri, ctx, regs)) {
1814 ri = free_ret_instance(ri);
1817 utask->return_instances = ri;
1820 static void prepare_uretprobe(struct uprobe *uprobe, struct pt_regs *regs)
1822 struct return_instance *ri;
1823 struct uprobe_task *utask;
1824 unsigned long orig_ret_vaddr, trampoline_vaddr;
1827 if (!get_xol_area())
1830 utask = get_utask();
1834 if (utask->depth >= MAX_URETPROBE_DEPTH) {
1835 printk_ratelimited(KERN_INFO "uprobe: omit uretprobe due to"
1836 " nestedness limit pid/tgid=%d/%d\n",
1837 current->pid, current->tgid);
1841 ri = kmalloc(sizeof(struct return_instance), GFP_KERNEL);
1845 trampoline_vaddr = get_trampoline_vaddr();
1846 orig_ret_vaddr = arch_uretprobe_hijack_return_addr(trampoline_vaddr, regs);
1847 if (orig_ret_vaddr == -1)
1850 /* drop the entries invalidated by longjmp() */
1851 chained = (orig_ret_vaddr == trampoline_vaddr);
1852 cleanup_return_instances(utask, chained, regs);
1855 * We don't want to keep trampoline address in stack, rather keep the
1856 * original return address of first caller thru all the consequent
1857 * instances. This also makes breakpoint unwrapping easier.
1860 if (!utask->return_instances) {
1862 * This situation is not possible. Likely we have an
1863 * attack from user-space.
1865 uprobe_warn(current, "handle tail call");
1868 orig_ret_vaddr = utask->return_instances->orig_ret_vaddr;
1871 ri->uprobe = get_uprobe(uprobe);
1872 ri->func = instruction_pointer(regs);
1873 ri->stack = user_stack_pointer(regs);
1874 ri->orig_ret_vaddr = orig_ret_vaddr;
1875 ri->chained = chained;
1878 ri->next = utask->return_instances;
1879 utask->return_instances = ri;
1886 /* Prepare to single-step probed instruction out of line. */
1888 pre_ssout(struct uprobe *uprobe, struct pt_regs *regs, unsigned long bp_vaddr)
1890 struct uprobe_task *utask;
1891 unsigned long xol_vaddr;
1894 utask = get_utask();
1898 xol_vaddr = xol_get_insn_slot(uprobe);
1902 utask->xol_vaddr = xol_vaddr;
1903 utask->vaddr = bp_vaddr;
1905 err = arch_uprobe_pre_xol(&uprobe->arch, regs);
1906 if (unlikely(err)) {
1907 xol_free_insn_slot(current);
1911 utask->active_uprobe = uprobe;
1912 utask->state = UTASK_SSTEP;
1917 * If we are singlestepping, then ensure this thread is not connected to
1918 * non-fatal signals until completion of singlestep. When xol insn itself
1919 * triggers the signal, restart the original insn even if the task is
1920 * already SIGKILL'ed (since coredump should report the correct ip). This
1921 * is even more important if the task has a handler for SIGSEGV/etc, The
1922 * _same_ instruction should be repeated again after return from the signal
1923 * handler, and SSTEP can never finish in this case.
1925 bool uprobe_deny_signal(void)
1927 struct task_struct *t = current;
1928 struct uprobe_task *utask = t->utask;
1930 if (likely(!utask || !utask->active_uprobe))
1933 WARN_ON_ONCE(utask->state != UTASK_SSTEP);
1935 if (signal_pending(t)) {
1936 spin_lock_irq(&t->sighand->siglock);
1937 clear_tsk_thread_flag(t, TIF_SIGPENDING);
1938 spin_unlock_irq(&t->sighand->siglock);
1940 if (__fatal_signal_pending(t) || arch_uprobe_xol_was_trapped(t)) {
1941 utask->state = UTASK_SSTEP_TRAPPED;
1942 set_tsk_thread_flag(t, TIF_UPROBE);
1949 static void mmf_recalc_uprobes(struct mm_struct *mm)
1951 struct vm_area_struct *vma;
1953 for (vma = mm->mmap; vma; vma = vma->vm_next) {
1954 if (!valid_vma(vma, false))
1957 * This is not strictly accurate, we can race with
1958 * uprobe_unregister() and see the already removed
1959 * uprobe if delete_uprobe() was not yet called.
1960 * Or this uprobe can be filtered out.
1962 if (vma_has_uprobes(vma, vma->vm_start, vma->vm_end))
1966 clear_bit(MMF_HAS_UPROBES, &mm->flags);
1969 static int is_trap_at_addr(struct mm_struct *mm, unsigned long vaddr)
1972 uprobe_opcode_t opcode;
1975 pagefault_disable();
1976 result = __get_user(opcode, (uprobe_opcode_t __user *)vaddr);
1979 if (likely(result == 0))
1983 * The NULL 'tsk' here ensures that any faults that occur here
1984 * will not be accounted to the task. 'mm' *is* current->mm,
1985 * but we treat this as a 'remote' access since it is
1986 * essentially a kernel access to the memory.
1988 result = get_user_pages_remote(NULL, mm, vaddr, 1, FOLL_FORCE, &page,
1993 copy_from_page(page, vaddr, &opcode, UPROBE_SWBP_INSN_SIZE);
1996 /* This needs to return true for any variant of the trap insn */
1997 return is_trap_insn(&opcode);
2000 static struct uprobe *find_active_uprobe(unsigned long bp_vaddr, int *is_swbp)
2002 struct mm_struct *mm = current->mm;
2003 struct uprobe *uprobe = NULL;
2004 struct vm_area_struct *vma;
2006 down_read(&mm->mmap_sem);
2007 vma = find_vma(mm, bp_vaddr);
2008 if (vma && vma->vm_start <= bp_vaddr) {
2009 if (valid_vma(vma, false)) {
2010 struct inode *inode = file_inode(vma->vm_file);
2011 loff_t offset = vaddr_to_offset(vma, bp_vaddr);
2013 uprobe = find_uprobe(inode, offset);
2017 *is_swbp = is_trap_at_addr(mm, bp_vaddr);
2022 if (!uprobe && test_and_clear_bit(MMF_RECALC_UPROBES, &mm->flags))
2023 mmf_recalc_uprobes(mm);
2024 up_read(&mm->mmap_sem);
2029 static void handler_chain(struct uprobe *uprobe, struct pt_regs *regs)
2031 struct uprobe_consumer *uc;
2032 int remove = UPROBE_HANDLER_REMOVE;
2033 bool need_prep = false; /* prepare return uprobe, when needed */
2035 down_read(&uprobe->register_rwsem);
2036 for (uc = uprobe->consumers; uc; uc = uc->next) {
2040 rc = uc->handler(uc, regs);
2041 WARN(rc & ~UPROBE_HANDLER_MASK,
2042 "bad rc=0x%x from %pf()\n", rc, uc->handler);
2045 if (uc->ret_handler)
2051 if (need_prep && !remove)
2052 prepare_uretprobe(uprobe, regs); /* put bp at return */
2054 if (remove && uprobe->consumers) {
2055 WARN_ON(!uprobe_is_active(uprobe));
2056 unapply_uprobe(uprobe, current->mm);
2058 up_read(&uprobe->register_rwsem);
2062 handle_uretprobe_chain(struct return_instance *ri, struct pt_regs *regs)
2064 struct uprobe *uprobe = ri->uprobe;
2065 struct uprobe_consumer *uc;
2067 down_read(&uprobe->register_rwsem);
2068 for (uc = uprobe->consumers; uc; uc = uc->next) {
2069 if (uc->ret_handler)
2070 uc->ret_handler(uc, ri->func, regs);
2072 up_read(&uprobe->register_rwsem);
2075 static struct return_instance *find_next_ret_chain(struct return_instance *ri)
2080 chained = ri->chained;
2081 ri = ri->next; /* can't be NULL if chained */
2087 static void handle_trampoline(struct pt_regs *regs)
2089 struct uprobe_task *utask;
2090 struct return_instance *ri, *next;
2093 utask = current->utask;
2097 ri = utask->return_instances;
2103 * We should throw out the frames invalidated by longjmp().
2104 * If this chain is valid, then the next one should be alive
2105 * or NULL; the latter case means that nobody but ri->func
2106 * could hit this trampoline on return. TODO: sigaltstack().
2108 next = find_next_ret_chain(ri);
2109 valid = !next || arch_uretprobe_is_alive(next, RP_CHECK_RET, regs);
2111 instruction_pointer_set(regs, ri->orig_ret_vaddr);
2114 handle_uretprobe_chain(ri, regs);
2115 ri = free_ret_instance(ri);
2117 } while (ri != next);
2120 utask->return_instances = ri;
2124 uprobe_warn(current, "handle uretprobe, sending SIGILL.");
2125 force_sig(SIGILL, current);
2129 bool __weak arch_uprobe_ignore(struct arch_uprobe *aup, struct pt_regs *regs)
2134 bool __weak arch_uretprobe_is_alive(struct return_instance *ret, enum rp_check ctx,
2135 struct pt_regs *regs)
2141 * Run handler and ask thread to singlestep.
2142 * Ensure all non-fatal signals cannot interrupt thread while it singlesteps.
2144 static void handle_swbp(struct pt_regs *regs)
2146 struct uprobe *uprobe;
2147 unsigned long bp_vaddr;
2148 int uninitialized_var(is_swbp);
2150 bp_vaddr = uprobe_get_swbp_addr(regs);
2151 if (bp_vaddr == get_trampoline_vaddr())
2152 return handle_trampoline(regs);
2154 uprobe = find_active_uprobe(bp_vaddr, &is_swbp);
2157 /* No matching uprobe; signal SIGTRAP. */
2158 send_sig(SIGTRAP, current, 0);
2161 * Either we raced with uprobe_unregister() or we can't
2162 * access this memory. The latter is only possible if
2163 * another thread plays with our ->mm. In both cases
2164 * we can simply restart. If this vma was unmapped we
2165 * can pretend this insn was not executed yet and get
2166 * the (correct) SIGSEGV after restart.
2168 instruction_pointer_set(regs, bp_vaddr);
2173 /* change it in advance for ->handler() and restart */
2174 instruction_pointer_set(regs, bp_vaddr);
2177 * TODO: move copy_insn/etc into _register and remove this hack.
2178 * After we hit the bp, _unregister + _register can install the
2179 * new and not-yet-analyzed uprobe at the same address, restart.
2181 if (unlikely(!test_bit(UPROBE_COPY_INSN, &uprobe->flags)))
2185 * Pairs with the smp_wmb() in prepare_uprobe().
2187 * Guarantees that if we see the UPROBE_COPY_INSN bit set, then
2188 * we must also see the stores to &uprobe->arch performed by the
2189 * prepare_uprobe() call.
2193 /* Tracing handlers use ->utask to communicate with fetch methods */
2197 if (arch_uprobe_ignore(&uprobe->arch, regs))
2200 handler_chain(uprobe, regs);
2202 if (arch_uprobe_skip_sstep(&uprobe->arch, regs))
2205 if (!pre_ssout(uprobe, regs, bp_vaddr))
2208 /* arch_uprobe_skip_sstep() succeeded, or restart if can't singlestep */
2214 * Perform required fix-ups and disable singlestep.
2215 * Allow pending signals to take effect.
2217 static void handle_singlestep(struct uprobe_task *utask, struct pt_regs *regs)
2219 struct uprobe *uprobe;
2222 uprobe = utask->active_uprobe;
2223 if (utask->state == UTASK_SSTEP_ACK)
2224 err = arch_uprobe_post_xol(&uprobe->arch, regs);
2225 else if (utask->state == UTASK_SSTEP_TRAPPED)
2226 arch_uprobe_abort_xol(&uprobe->arch, regs);
2231 utask->active_uprobe = NULL;
2232 utask->state = UTASK_RUNNING;
2233 xol_free_insn_slot(current);
2235 spin_lock_irq(¤t->sighand->siglock);
2236 recalc_sigpending(); /* see uprobe_deny_signal() */
2237 spin_unlock_irq(¤t->sighand->siglock);
2239 if (unlikely(err)) {
2240 uprobe_warn(current, "execute the probed insn, sending SIGILL.");
2241 force_sig(SIGILL, current);
2246 * On breakpoint hit, breakpoint notifier sets the TIF_UPROBE flag and
2247 * allows the thread to return from interrupt. After that handle_swbp()
2248 * sets utask->active_uprobe.
2250 * On singlestep exception, singlestep notifier sets the TIF_UPROBE flag
2251 * and allows the thread to return from interrupt.
2253 * While returning to userspace, thread notices the TIF_UPROBE flag and calls
2254 * uprobe_notify_resume().
2256 void uprobe_notify_resume(struct pt_regs *regs)
2258 struct uprobe_task *utask;
2260 clear_thread_flag(TIF_UPROBE);
2262 utask = current->utask;
2263 if (utask && utask->active_uprobe)
2264 handle_singlestep(utask, regs);
2270 * uprobe_pre_sstep_notifier gets called from interrupt context as part of
2271 * notifier mechanism. Set TIF_UPROBE flag and indicate breakpoint hit.
2273 int uprobe_pre_sstep_notifier(struct pt_regs *regs)
2278 if (!test_bit(MMF_HAS_UPROBES, ¤t->mm->flags) &&
2279 (!current->utask || !current->utask->return_instances))
2282 set_thread_flag(TIF_UPROBE);
2287 * uprobe_post_sstep_notifier gets called in interrupt context as part of notifier
2288 * mechanism. Set TIF_UPROBE flag and indicate completion of singlestep.
2290 int uprobe_post_sstep_notifier(struct pt_regs *regs)
2292 struct uprobe_task *utask = current->utask;
2294 if (!current->mm || !utask || !utask->active_uprobe)
2295 /* task is currently not uprobed */
2298 utask->state = UTASK_SSTEP_ACK;
2299 set_thread_flag(TIF_UPROBE);
2303 static struct notifier_block uprobe_exception_nb = {
2304 .notifier_call = arch_uprobe_exception_notify,
2305 .priority = INT_MAX-1, /* notified after kprobes, kgdb */
2308 static int __init init_uprobes(void)
2312 for (i = 0; i < UPROBES_HASH_SZ; i++)
2313 mutex_init(&uprobes_mmap_mutex[i]);
2315 if (percpu_init_rwsem(&dup_mmap_sem))
2318 return register_die_notifier(&uprobe_exception_nb);
2320 __initcall(init_uprobes);