1 // SPDX-License-Identifier: GPL-2.0+
3 * User-space Probes (UProbes)
5 * Copyright (C) IBM Corporation, 2008-2012
9 * Copyright (C) 2011-2012 Red Hat, Inc., Peter Zijlstra
12 #include <linux/kernel.h>
13 #include <linux/highmem.h>
14 #include <linux/pagemap.h> /* read_mapping_page */
15 #include <linux/slab.h>
16 #include <linux/sched.h>
17 #include <linux/sched/mm.h>
18 #include <linux/sched/coredump.h>
19 #include <linux/export.h>
20 #include <linux/rmap.h> /* anon_vma_prepare */
21 #include <linux/mmu_notifier.h> /* set_pte_at_notify */
22 #include <linux/swap.h> /* try_to_free_swap */
23 #include <linux/ptrace.h> /* user_enable_single_step */
24 #include <linux/kdebug.h> /* notifier mechanism */
25 #include "../../mm/internal.h" /* munlock_vma_page */
26 #include <linux/percpu-rwsem.h>
27 #include <linux/task_work.h>
28 #include <linux/shmem_fs.h>
30 #include <linux/uprobes.h>
32 #define UINSNS_PER_PAGE (PAGE_SIZE/UPROBE_XOL_SLOT_BYTES)
33 #define MAX_UPROBE_XOL_SLOTS UINSNS_PER_PAGE
35 static struct rb_root uprobes_tree = RB_ROOT;
37 * allows us to skip the uprobe_mmap if there are no uprobe events active
38 * at this time. Probably a fine grained per inode count is better?
40 #define no_uprobe_events() RB_EMPTY_ROOT(&uprobes_tree)
42 static DEFINE_SPINLOCK(uprobes_treelock); /* serialize rbtree access */
44 #define UPROBES_HASH_SZ 13
45 /* serialize uprobe->pending_list */
46 static struct mutex uprobes_mmap_mutex[UPROBES_HASH_SZ];
47 #define uprobes_mmap_hash(v) (&uprobes_mmap_mutex[((unsigned long)(v)) % UPROBES_HASH_SZ])
49 DEFINE_STATIC_PERCPU_RWSEM(dup_mmap_sem);
51 /* Have a copy of original instruction */
52 #define UPROBE_COPY_INSN 0
55 struct rb_node rb_node; /* node in the rb tree */
57 struct rw_semaphore register_rwsem;
58 struct rw_semaphore consumer_rwsem;
59 struct list_head pending_list;
60 struct uprobe_consumer *consumers;
61 struct inode *inode; /* Also hold a ref to inode */
63 loff_t ref_ctr_offset;
67 * The generic code assumes that it has two members of unknown type
68 * owned by the arch-specific code:
70 * insn - copy_insn() saves the original instruction here for
71 * arch_uprobe_analyze_insn().
73 * ixol - potentially modified instruction to execute out of
74 * line, copied to xol_area by xol_get_insn_slot().
76 struct arch_uprobe arch;
79 struct delayed_uprobe {
80 struct list_head list;
81 struct uprobe *uprobe;
85 static DEFINE_MUTEX(delayed_uprobe_lock);
86 static LIST_HEAD(delayed_uprobe_list);
89 * Execute out of line area: anonymous executable mapping installed
90 * by the probed task to execute the copy of the original instruction
91 * mangled by set_swbp().
93 * On a breakpoint hit, thread contests for a slot. It frees the
94 * slot after singlestep. Currently a fixed number of slots are
98 wait_queue_head_t wq; /* if all slots are busy */
99 atomic_t slot_count; /* number of in-use slots */
100 unsigned long *bitmap; /* 0 = free slot */
102 struct vm_special_mapping xol_mapping;
103 struct page *pages[2];
105 * We keep the vma's vm_start rather than a pointer to the vma
106 * itself. The probed process or a naughty kernel module could make
107 * the vma go away, and we must handle that reasonably gracefully.
109 unsigned long vaddr; /* Page(s) of instruction slots */
113 * valid_vma: Verify if the specified vma is an executable vma
114 * Relax restrictions while unregistering: vm_flags might have
115 * changed after breakpoint was inserted.
116 * - is_register: indicates if we are in register context.
117 * - Return 1 if the specified virtual address is in an
120 static bool valid_vma(struct vm_area_struct *vma, bool is_register)
122 vm_flags_t flags = VM_HUGETLB | VM_MAYEXEC | VM_MAYSHARE;
127 return vma->vm_file && (vma->vm_flags & flags) == VM_MAYEXEC;
130 static unsigned long offset_to_vaddr(struct vm_area_struct *vma, loff_t offset)
132 return vma->vm_start + offset - ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
135 static loff_t vaddr_to_offset(struct vm_area_struct *vma, unsigned long vaddr)
137 return ((loff_t)vma->vm_pgoff << PAGE_SHIFT) + (vaddr - vma->vm_start);
141 * __replace_page - replace page in vma by new page.
142 * based on replace_page in mm/ksm.c
144 * @vma: vma that holds the pte pointing to page
145 * @addr: address the old @page is mapped at
146 * @old_page: the page we are replacing by new_page
147 * @new_page: the modified page we replace page by
149 * If @new_page is NULL, only unmap @old_page.
151 * Returns 0 on success, negative error code otherwise.
153 static int __replace_page(struct vm_area_struct *vma, unsigned long addr,
154 struct page *old_page, struct page *new_page)
156 struct mm_struct *mm = vma->vm_mm;
157 struct page_vma_mapped_walk pvmw = {
158 .page = compound_head(old_page),
163 struct mmu_notifier_range range;
164 struct mem_cgroup *memcg;
166 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm, addr,
170 err = mem_cgroup_try_charge(new_page, vma->vm_mm, GFP_KERNEL,
176 /* For try_to_free_swap() and munlock_vma_page() below */
179 mmu_notifier_invalidate_range_start(&range);
181 if (!page_vma_mapped_walk(&pvmw)) {
183 mem_cgroup_cancel_charge(new_page, memcg, false);
186 VM_BUG_ON_PAGE(addr != pvmw.address, old_page);
190 page_add_new_anon_rmap(new_page, vma, addr, false);
191 mem_cgroup_commit_charge(new_page, memcg, false, false);
192 lru_cache_add_active_or_unevictable(new_page, vma);
194 /* no new page, just dec_mm_counter for old_page */
195 dec_mm_counter(mm, MM_ANONPAGES);
197 if (!PageAnon(old_page)) {
198 dec_mm_counter(mm, mm_counter_file(old_page));
199 inc_mm_counter(mm, MM_ANONPAGES);
202 flush_cache_page(vma, addr, pte_pfn(*pvmw.pte));
203 ptep_clear_flush_notify(vma, addr, pvmw.pte);
205 set_pte_at_notify(mm, addr, pvmw.pte,
206 mk_pte(new_page, vma->vm_page_prot));
208 page_remove_rmap(old_page, false);
209 if (!page_mapped(old_page))
210 try_to_free_swap(old_page);
211 page_vma_mapped_walk_done(&pvmw);
213 if (vma->vm_flags & VM_LOCKED)
214 munlock_vma_page(old_page);
219 mmu_notifier_invalidate_range_end(&range);
220 unlock_page(old_page);
225 * is_swbp_insn - check if instruction is breakpoint instruction.
226 * @insn: instruction to be checked.
227 * Default implementation of is_swbp_insn
228 * Returns true if @insn is a breakpoint instruction.
230 bool __weak is_swbp_insn(uprobe_opcode_t *insn)
232 return *insn == UPROBE_SWBP_INSN;
236 * is_trap_insn - check if instruction is breakpoint instruction.
237 * @insn: instruction to be checked.
238 * Default implementation of is_trap_insn
239 * Returns true if @insn is a breakpoint instruction.
241 * This function is needed for the case where an architecture has multiple
242 * trap instructions (like powerpc).
244 bool __weak is_trap_insn(uprobe_opcode_t *insn)
246 return is_swbp_insn(insn);
249 static void copy_from_page(struct page *page, unsigned long vaddr, void *dst, int len)
251 void *kaddr = kmap_atomic(page);
252 memcpy(dst, kaddr + (vaddr & ~PAGE_MASK), len);
253 kunmap_atomic(kaddr);
256 static void copy_to_page(struct page *page, unsigned long vaddr, const void *src, int len)
258 void *kaddr = kmap_atomic(page);
259 memcpy(kaddr + (vaddr & ~PAGE_MASK), src, len);
260 kunmap_atomic(kaddr);
263 static int verify_opcode(struct page *page, unsigned long vaddr, uprobe_opcode_t *new_opcode)
265 uprobe_opcode_t old_opcode;
269 * Note: We only check if the old_opcode is UPROBE_SWBP_INSN here.
270 * We do not check if it is any other 'trap variant' which could
271 * be conditional trap instruction such as the one powerpc supports.
273 * The logic is that we do not care if the underlying instruction
274 * is a trap variant; uprobes always wins over any other (gdb)
277 copy_from_page(page, vaddr, &old_opcode, UPROBE_SWBP_INSN_SIZE);
278 is_swbp = is_swbp_insn(&old_opcode);
280 if (is_swbp_insn(new_opcode)) {
281 if (is_swbp) /* register: already installed? */
284 if (!is_swbp) /* unregister: was it changed by us? */
291 static struct delayed_uprobe *
292 delayed_uprobe_check(struct uprobe *uprobe, struct mm_struct *mm)
294 struct delayed_uprobe *du;
296 list_for_each_entry(du, &delayed_uprobe_list, list)
297 if (du->uprobe == uprobe && du->mm == mm)
302 static int delayed_uprobe_add(struct uprobe *uprobe, struct mm_struct *mm)
304 struct delayed_uprobe *du;
306 if (delayed_uprobe_check(uprobe, mm))
309 du = kzalloc(sizeof(*du), GFP_KERNEL);
315 list_add(&du->list, &delayed_uprobe_list);
319 static void delayed_uprobe_delete(struct delayed_uprobe *du)
327 static void delayed_uprobe_remove(struct uprobe *uprobe, struct mm_struct *mm)
329 struct list_head *pos, *q;
330 struct delayed_uprobe *du;
335 list_for_each_safe(pos, q, &delayed_uprobe_list) {
336 du = list_entry(pos, struct delayed_uprobe, list);
338 if (uprobe && du->uprobe != uprobe)
340 if (mm && du->mm != mm)
343 delayed_uprobe_delete(du);
347 static bool valid_ref_ctr_vma(struct uprobe *uprobe,
348 struct vm_area_struct *vma)
350 unsigned long vaddr = offset_to_vaddr(vma, uprobe->ref_ctr_offset);
352 return uprobe->ref_ctr_offset &&
354 file_inode(vma->vm_file) == uprobe->inode &&
355 (vma->vm_flags & (VM_WRITE|VM_SHARED)) == VM_WRITE &&
356 vma->vm_start <= vaddr &&
360 static struct vm_area_struct *
361 find_ref_ctr_vma(struct uprobe *uprobe, struct mm_struct *mm)
363 struct vm_area_struct *tmp;
365 for (tmp = mm->mmap; tmp; tmp = tmp->vm_next)
366 if (valid_ref_ctr_vma(uprobe, tmp))
373 __update_ref_ctr(struct mm_struct *mm, unsigned long vaddr, short d)
377 struct vm_area_struct *vma;
384 ret = get_user_pages_remote(NULL, mm, vaddr, 1,
385 FOLL_WRITE, &page, &vma, NULL);
386 if (unlikely(ret <= 0)) {
388 * We are asking for 1 page. If get_user_pages_remote() fails,
389 * it may return 0, in that case we have to return error.
391 return ret == 0 ? -EBUSY : ret;
394 kaddr = kmap_atomic(page);
395 ptr = kaddr + (vaddr & ~PAGE_MASK);
397 if (unlikely(*ptr + d < 0)) {
398 pr_warn("ref_ctr going negative. vaddr: 0x%lx, "
399 "curr val: %d, delta: %d\n", vaddr, *ptr, d);
407 kunmap_atomic(kaddr);
412 static void update_ref_ctr_warn(struct uprobe *uprobe,
413 struct mm_struct *mm, short d)
415 pr_warn("ref_ctr %s failed for inode: 0x%lx offset: "
416 "0x%llx ref_ctr_offset: 0x%llx of mm: 0x%pK\n",
417 d > 0 ? "increment" : "decrement", uprobe->inode->i_ino,
418 (unsigned long long) uprobe->offset,
419 (unsigned long long) uprobe->ref_ctr_offset, mm);
422 static int update_ref_ctr(struct uprobe *uprobe, struct mm_struct *mm,
425 struct vm_area_struct *rc_vma;
426 unsigned long rc_vaddr;
429 rc_vma = find_ref_ctr_vma(uprobe, mm);
432 rc_vaddr = offset_to_vaddr(rc_vma, uprobe->ref_ctr_offset);
433 ret = __update_ref_ctr(mm, rc_vaddr, d);
435 update_ref_ctr_warn(uprobe, mm, d);
441 mutex_lock(&delayed_uprobe_lock);
443 ret = delayed_uprobe_add(uprobe, mm);
445 delayed_uprobe_remove(uprobe, mm);
446 mutex_unlock(&delayed_uprobe_lock);
453 * Expect the breakpoint instruction to be the smallest size instruction for
454 * the architecture. If an arch has variable length instruction and the
455 * breakpoint instruction is not of the smallest length instruction
456 * supported by that architecture then we need to modify is_trap_at_addr and
457 * uprobe_write_opcode accordingly. This would never be a problem for archs
458 * that have fixed length instructions.
460 * uprobe_write_opcode - write the opcode at a given virtual address.
461 * @mm: the probed process address space.
462 * @vaddr: the virtual address to store the opcode.
463 * @opcode: opcode to be written at @vaddr.
465 * Called with mm->mmap_sem held for write.
466 * Return 0 (success) or a negative errno.
468 int uprobe_write_opcode(struct arch_uprobe *auprobe, struct mm_struct *mm,
469 unsigned long vaddr, uprobe_opcode_t opcode)
471 struct uprobe *uprobe;
472 struct page *old_page, *new_page;
473 struct vm_area_struct *vma;
474 int ret, is_register, ref_ctr_updated = 0;
476 is_register = is_swbp_insn(&opcode);
477 uprobe = container_of(auprobe, struct uprobe, arch);
480 /* Read the page with vaddr into memory */
481 ret = get_user_pages_remote(NULL, mm, vaddr, 1,
482 FOLL_FORCE | FOLL_SPLIT_PMD, &old_page, &vma, NULL);
486 ret = verify_opcode(old_page, vaddr, &opcode);
490 /* We are going to replace instruction, update ref_ctr. */
491 if (!ref_ctr_updated && uprobe->ref_ctr_offset) {
492 ret = update_ref_ctr(uprobe, mm, is_register ? 1 : -1);
500 if (!is_register && !PageAnon(old_page))
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);
517 struct page *orig_page;
520 VM_BUG_ON_PAGE(!PageAnon(old_page), old_page);
522 index = vaddr_to_offset(vma, vaddr & PAGE_MASK) >> PAGE_SHIFT;
523 orig_page = find_get_page(vma->vm_file->f_inode->i_mapping,
527 if (PageUptodate(orig_page) &&
528 pages_identical(new_page, orig_page)) {
529 /* let go new_page */
537 ret = __replace_page(vma, vaddr, old_page, new_page);
543 if (unlikely(ret == -EAGAIN))
546 /* Revert back reference counter if instruction update failed. */
547 if (ret && is_register && ref_ctr_updated)
548 update_ref_ctr(uprobe, mm, -1);
554 * set_swbp - store breakpoint at a given address.
555 * @auprobe: arch specific probepoint information.
556 * @mm: the probed process address space.
557 * @vaddr: the virtual address to insert the opcode.
559 * For mm @mm, store the breakpoint instruction at @vaddr.
560 * Return 0 (success) or a negative errno.
562 int __weak set_swbp(struct arch_uprobe *auprobe, struct mm_struct *mm, unsigned long vaddr)
564 return uprobe_write_opcode(auprobe, mm, vaddr, UPROBE_SWBP_INSN);
568 * set_orig_insn - Restore the original instruction.
569 * @mm: the probed process address space.
570 * @auprobe: arch specific probepoint information.
571 * @vaddr: the virtual address to insert the opcode.
573 * For mm @mm, restore the original opcode (opcode) at @vaddr.
574 * Return 0 (success) or a negative errno.
577 set_orig_insn(struct arch_uprobe *auprobe, struct mm_struct *mm, unsigned long vaddr)
579 return uprobe_write_opcode(auprobe, mm, vaddr,
580 *(uprobe_opcode_t *)&auprobe->insn);
583 static struct uprobe *get_uprobe(struct uprobe *uprobe)
585 refcount_inc(&uprobe->ref);
589 static void put_uprobe(struct uprobe *uprobe)
591 if (refcount_dec_and_test(&uprobe->ref)) {
593 * If application munmap(exec_vma) before uprobe_unregister()
594 * gets called, we don't get a chance to remove uprobe from
595 * delayed_uprobe_list from remove_breakpoint(). Do it here.
597 mutex_lock(&delayed_uprobe_lock);
598 delayed_uprobe_remove(uprobe, NULL);
599 mutex_unlock(&delayed_uprobe_lock);
604 static int match_uprobe(struct uprobe *l, struct uprobe *r)
606 if (l->inode < r->inode)
609 if (l->inode > r->inode)
612 if (l->offset < r->offset)
615 if (l->offset > r->offset)
621 static struct uprobe *__find_uprobe(struct inode *inode, loff_t offset)
623 struct uprobe u = { .inode = inode, .offset = offset };
624 struct rb_node *n = uprobes_tree.rb_node;
625 struct uprobe *uprobe;
629 uprobe = rb_entry(n, struct uprobe, rb_node);
630 match = match_uprobe(&u, uprobe);
632 return get_uprobe(uprobe);
643 * Find a uprobe corresponding to a given inode:offset
644 * Acquires uprobes_treelock
646 static struct uprobe *find_uprobe(struct inode *inode, loff_t offset)
648 struct uprobe *uprobe;
650 spin_lock(&uprobes_treelock);
651 uprobe = __find_uprobe(inode, offset);
652 spin_unlock(&uprobes_treelock);
657 static struct uprobe *__insert_uprobe(struct uprobe *uprobe)
659 struct rb_node **p = &uprobes_tree.rb_node;
660 struct rb_node *parent = NULL;
666 u = rb_entry(parent, struct uprobe, rb_node);
667 match = match_uprobe(uprobe, u);
669 return get_uprobe(u);
672 p = &parent->rb_left;
674 p = &parent->rb_right;
679 rb_link_node(&uprobe->rb_node, parent, p);
680 rb_insert_color(&uprobe->rb_node, &uprobes_tree);
681 /* get access + creation ref */
682 refcount_set(&uprobe->ref, 2);
688 * Acquire uprobes_treelock.
689 * Matching uprobe already exists in rbtree;
690 * increment (access refcount) and return the matching uprobe.
692 * No matching uprobe; insert the uprobe in rb_tree;
693 * get a double refcount (access + creation) and return NULL.
695 static struct uprobe *insert_uprobe(struct uprobe *uprobe)
699 spin_lock(&uprobes_treelock);
700 u = __insert_uprobe(uprobe);
701 spin_unlock(&uprobes_treelock);
707 ref_ctr_mismatch_warn(struct uprobe *cur_uprobe, struct uprobe *uprobe)
709 pr_warn("ref_ctr_offset mismatch. inode: 0x%lx offset: 0x%llx "
710 "ref_ctr_offset(old): 0x%llx ref_ctr_offset(new): 0x%llx\n",
711 uprobe->inode->i_ino, (unsigned long long) uprobe->offset,
712 (unsigned long long) cur_uprobe->ref_ctr_offset,
713 (unsigned long long) uprobe->ref_ctr_offset);
716 static struct uprobe *alloc_uprobe(struct inode *inode, loff_t offset,
717 loff_t ref_ctr_offset)
719 struct uprobe *uprobe, *cur_uprobe;
721 uprobe = kzalloc(sizeof(struct uprobe), GFP_KERNEL);
725 uprobe->inode = inode;
726 uprobe->offset = offset;
727 uprobe->ref_ctr_offset = ref_ctr_offset;
728 init_rwsem(&uprobe->register_rwsem);
729 init_rwsem(&uprobe->consumer_rwsem);
731 /* add to uprobes_tree, sorted on inode:offset */
732 cur_uprobe = insert_uprobe(uprobe);
733 /* a uprobe exists for this inode:offset combination */
735 if (cur_uprobe->ref_ctr_offset != uprobe->ref_ctr_offset) {
736 ref_ctr_mismatch_warn(cur_uprobe, uprobe);
737 put_uprobe(cur_uprobe);
739 return ERR_PTR(-EINVAL);
748 static void consumer_add(struct uprobe *uprobe, struct uprobe_consumer *uc)
750 down_write(&uprobe->consumer_rwsem);
751 uc->next = uprobe->consumers;
752 uprobe->consumers = uc;
753 up_write(&uprobe->consumer_rwsem);
757 * For uprobe @uprobe, delete the consumer @uc.
758 * Return true if the @uc is deleted successfully
761 static bool consumer_del(struct uprobe *uprobe, struct uprobe_consumer *uc)
763 struct uprobe_consumer **con;
766 down_write(&uprobe->consumer_rwsem);
767 for (con = &uprobe->consumers; *con; con = &(*con)->next) {
774 up_write(&uprobe->consumer_rwsem);
779 static int __copy_insn(struct address_space *mapping, struct file *filp,
780 void *insn, int nbytes, loff_t offset)
784 * Ensure that the page that has the original instruction is populated
785 * and in page-cache. If ->readpage == NULL it must be shmem_mapping(),
786 * see uprobe_register().
788 if (mapping->a_ops->readpage)
789 page = read_mapping_page(mapping, offset >> PAGE_SHIFT, filp);
791 page = shmem_read_mapping_page(mapping, offset >> PAGE_SHIFT);
793 return PTR_ERR(page);
795 copy_from_page(page, offset, insn, nbytes);
801 static int copy_insn(struct uprobe *uprobe, struct file *filp)
803 struct address_space *mapping = uprobe->inode->i_mapping;
804 loff_t offs = uprobe->offset;
805 void *insn = &uprobe->arch.insn;
806 int size = sizeof(uprobe->arch.insn);
809 /* Copy only available bytes, -EIO if nothing was read */
811 if (offs >= i_size_read(uprobe->inode))
814 len = min_t(int, size, PAGE_SIZE - (offs & ~PAGE_MASK));
815 err = __copy_insn(mapping, filp, insn, len, offs);
827 static int prepare_uprobe(struct uprobe *uprobe, struct file *file,
828 struct mm_struct *mm, unsigned long vaddr)
832 if (test_bit(UPROBE_COPY_INSN, &uprobe->flags))
835 /* TODO: move this into _register, until then we abuse this sem. */
836 down_write(&uprobe->consumer_rwsem);
837 if (test_bit(UPROBE_COPY_INSN, &uprobe->flags))
840 ret = copy_insn(uprobe, file);
845 if (is_trap_insn((uprobe_opcode_t *)&uprobe->arch.insn))
848 ret = arch_uprobe_analyze_insn(&uprobe->arch, mm, vaddr);
852 /* uprobe_write_opcode() assumes we don't cross page boundary */
853 BUG_ON((uprobe->offset & ~PAGE_MASK) +
854 UPROBE_SWBP_INSN_SIZE > PAGE_SIZE);
856 smp_wmb(); /* pairs with the smp_rmb() in handle_swbp() */
857 set_bit(UPROBE_COPY_INSN, &uprobe->flags);
860 up_write(&uprobe->consumer_rwsem);
865 static inline bool consumer_filter(struct uprobe_consumer *uc,
866 enum uprobe_filter_ctx ctx, struct mm_struct *mm)
868 return !uc->filter || uc->filter(uc, ctx, mm);
871 static bool filter_chain(struct uprobe *uprobe,
872 enum uprobe_filter_ctx ctx, struct mm_struct *mm)
874 struct uprobe_consumer *uc;
877 down_read(&uprobe->consumer_rwsem);
878 for (uc = uprobe->consumers; uc; uc = uc->next) {
879 ret = consumer_filter(uc, ctx, mm);
883 up_read(&uprobe->consumer_rwsem);
889 install_breakpoint(struct uprobe *uprobe, struct mm_struct *mm,
890 struct vm_area_struct *vma, unsigned long vaddr)
895 ret = prepare_uprobe(uprobe, vma->vm_file, mm, vaddr);
900 * set MMF_HAS_UPROBES in advance for uprobe_pre_sstep_notifier(),
901 * the task can hit this breakpoint right after __replace_page().
903 first_uprobe = !test_bit(MMF_HAS_UPROBES, &mm->flags);
905 set_bit(MMF_HAS_UPROBES, &mm->flags);
907 ret = set_swbp(&uprobe->arch, mm, vaddr);
909 clear_bit(MMF_RECALC_UPROBES, &mm->flags);
910 else if (first_uprobe)
911 clear_bit(MMF_HAS_UPROBES, &mm->flags);
917 remove_breakpoint(struct uprobe *uprobe, struct mm_struct *mm, unsigned long vaddr)
919 set_bit(MMF_RECALC_UPROBES, &mm->flags);
920 return set_orig_insn(&uprobe->arch, mm, vaddr);
923 static inline bool uprobe_is_active(struct uprobe *uprobe)
925 return !RB_EMPTY_NODE(&uprobe->rb_node);
928 * There could be threads that have already hit the breakpoint. They
929 * will recheck the current insn and restart if find_uprobe() fails.
930 * See find_active_uprobe().
932 static void delete_uprobe(struct uprobe *uprobe)
934 if (WARN_ON(!uprobe_is_active(uprobe)))
937 spin_lock(&uprobes_treelock);
938 rb_erase(&uprobe->rb_node, &uprobes_tree);
939 spin_unlock(&uprobes_treelock);
940 RB_CLEAR_NODE(&uprobe->rb_node); /* for uprobe_is_active() */
945 struct map_info *next;
946 struct mm_struct *mm;
950 static inline struct map_info *free_map_info(struct map_info *info)
952 struct map_info *next = info->next;
957 static struct map_info *
958 build_map_info(struct address_space *mapping, loff_t offset, bool is_register)
960 unsigned long pgoff = offset >> PAGE_SHIFT;
961 struct vm_area_struct *vma;
962 struct map_info *curr = NULL;
963 struct map_info *prev = NULL;
964 struct map_info *info;
968 i_mmap_lock_read(mapping);
969 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
970 if (!valid_vma(vma, is_register))
973 if (!prev && !more) {
975 * Needs GFP_NOWAIT to avoid i_mmap_rwsem recursion through
976 * reclaim. This is optimistic, no harm done if it fails.
978 prev = kmalloc(sizeof(struct map_info),
979 GFP_NOWAIT | __GFP_NOMEMALLOC | __GFP_NOWARN);
988 if (!mmget_not_zero(vma->vm_mm))
996 info->mm = vma->vm_mm;
997 info->vaddr = offset_to_vaddr(vma, offset);
999 i_mmap_unlock_read(mapping);
1011 info = kmalloc(sizeof(struct map_info), GFP_KERNEL);
1013 curr = ERR_PTR(-ENOMEM);
1023 prev = free_map_info(prev);
1028 register_for_each_vma(struct uprobe *uprobe, struct uprobe_consumer *new)
1030 bool is_register = !!new;
1031 struct map_info *info;
1034 percpu_down_write(&dup_mmap_sem);
1035 info = build_map_info(uprobe->inode->i_mapping,
1036 uprobe->offset, is_register);
1038 err = PTR_ERR(info);
1043 struct mm_struct *mm = info->mm;
1044 struct vm_area_struct *vma;
1046 if (err && is_register)
1049 down_write(&mm->mmap_sem);
1050 vma = find_vma(mm, info->vaddr);
1051 if (!vma || !valid_vma(vma, is_register) ||
1052 file_inode(vma->vm_file) != uprobe->inode)
1055 if (vma->vm_start > info->vaddr ||
1056 vaddr_to_offset(vma, info->vaddr) != uprobe->offset)
1060 /* consult only the "caller", new consumer. */
1061 if (consumer_filter(new,
1062 UPROBE_FILTER_REGISTER, mm))
1063 err = install_breakpoint(uprobe, mm, vma, info->vaddr);
1064 } else if (test_bit(MMF_HAS_UPROBES, &mm->flags)) {
1065 if (!filter_chain(uprobe,
1066 UPROBE_FILTER_UNREGISTER, mm))
1067 err |= remove_breakpoint(uprobe, mm, info->vaddr);
1071 up_write(&mm->mmap_sem);
1074 info = free_map_info(info);
1077 percpu_up_write(&dup_mmap_sem);
1082 __uprobe_unregister(struct uprobe *uprobe, struct uprobe_consumer *uc)
1086 if (WARN_ON(!consumer_del(uprobe, uc)))
1089 err = register_for_each_vma(uprobe, NULL);
1090 /* TODO : cant unregister? schedule a worker thread */
1091 if (!uprobe->consumers && !err)
1092 delete_uprobe(uprobe);
1096 * uprobe_unregister - unregister an already registered probe.
1097 * @inode: the file in which the probe has to be removed.
1098 * @offset: offset from the start of the file.
1099 * @uc: identify which probe if multiple probes are colocated.
1101 void uprobe_unregister(struct inode *inode, loff_t offset, struct uprobe_consumer *uc)
1103 struct uprobe *uprobe;
1105 uprobe = find_uprobe(inode, offset);
1106 if (WARN_ON(!uprobe))
1109 down_write(&uprobe->register_rwsem);
1110 __uprobe_unregister(uprobe, uc);
1111 up_write(&uprobe->register_rwsem);
1114 EXPORT_SYMBOL_GPL(uprobe_unregister);
1117 * __uprobe_register - register a probe
1118 * @inode: the file in which the probe has to be placed.
1119 * @offset: offset from the start of the file.
1120 * @uc: information on howto handle the probe..
1122 * Apart from the access refcount, __uprobe_register() takes a creation
1123 * refcount (thro alloc_uprobe) if and only if this @uprobe is getting
1124 * inserted into the rbtree (i.e first consumer for a @inode:@offset
1125 * tuple). Creation refcount stops uprobe_unregister from freeing the
1126 * @uprobe even before the register operation is complete. Creation
1127 * refcount is released when the last @uc for the @uprobe
1128 * unregisters. Caller of __uprobe_register() is required to keep @inode
1129 * (and the containing mount) referenced.
1131 * Return errno if it cannot successully install probes
1132 * else return 0 (success)
1134 static int __uprobe_register(struct inode *inode, loff_t offset,
1135 loff_t ref_ctr_offset, struct uprobe_consumer *uc)
1137 struct uprobe *uprobe;
1140 /* Uprobe must have at least one set consumer */
1141 if (!uc->handler && !uc->ret_handler)
1144 /* copy_insn() uses read_mapping_page() or shmem_read_mapping_page() */
1145 if (!inode->i_mapping->a_ops->readpage && !shmem_mapping(inode->i_mapping))
1147 /* Racy, just to catch the obvious mistakes */
1148 if (offset > i_size_read(inode))
1152 uprobe = alloc_uprobe(inode, offset, ref_ctr_offset);
1156 return PTR_ERR(uprobe);
1159 * We can race with uprobe_unregister()->delete_uprobe().
1160 * Check uprobe_is_active() and retry if it is false.
1162 down_write(&uprobe->register_rwsem);
1164 if (likely(uprobe_is_active(uprobe))) {
1165 consumer_add(uprobe, uc);
1166 ret = register_for_each_vma(uprobe, uc);
1168 __uprobe_unregister(uprobe, uc);
1170 up_write(&uprobe->register_rwsem);
1173 if (unlikely(ret == -EAGAIN))
1178 int uprobe_register(struct inode *inode, loff_t offset,
1179 struct uprobe_consumer *uc)
1181 return __uprobe_register(inode, offset, 0, uc);
1183 EXPORT_SYMBOL_GPL(uprobe_register);
1185 int uprobe_register_refctr(struct inode *inode, loff_t offset,
1186 loff_t ref_ctr_offset, struct uprobe_consumer *uc)
1188 return __uprobe_register(inode, offset, ref_ctr_offset, uc);
1190 EXPORT_SYMBOL_GPL(uprobe_register_refctr);
1193 * uprobe_apply - unregister an already registered probe.
1194 * @inode: the file in which the probe has to be removed.
1195 * @offset: offset from the start of the file.
1196 * @uc: consumer which wants to add more or remove some breakpoints
1197 * @add: add or remove the breakpoints
1199 int uprobe_apply(struct inode *inode, loff_t offset,
1200 struct uprobe_consumer *uc, bool add)
1202 struct uprobe *uprobe;
1203 struct uprobe_consumer *con;
1206 uprobe = find_uprobe(inode, offset);
1207 if (WARN_ON(!uprobe))
1210 down_write(&uprobe->register_rwsem);
1211 for (con = uprobe->consumers; con && con != uc ; con = con->next)
1214 ret = register_for_each_vma(uprobe, add ? uc : NULL);
1215 up_write(&uprobe->register_rwsem);
1221 static int unapply_uprobe(struct uprobe *uprobe, struct mm_struct *mm)
1223 struct vm_area_struct *vma;
1226 down_read(&mm->mmap_sem);
1227 for (vma = mm->mmap; vma; vma = vma->vm_next) {
1228 unsigned long vaddr;
1231 if (!valid_vma(vma, false) ||
1232 file_inode(vma->vm_file) != uprobe->inode)
1235 offset = (loff_t)vma->vm_pgoff << PAGE_SHIFT;
1236 if (uprobe->offset < offset ||
1237 uprobe->offset >= offset + vma->vm_end - vma->vm_start)
1240 vaddr = offset_to_vaddr(vma, uprobe->offset);
1241 err |= remove_breakpoint(uprobe, mm, vaddr);
1243 up_read(&mm->mmap_sem);
1248 static struct rb_node *
1249 find_node_in_range(struct inode *inode, loff_t min, loff_t max)
1251 struct rb_node *n = uprobes_tree.rb_node;
1254 struct uprobe *u = rb_entry(n, struct uprobe, rb_node);
1256 if (inode < u->inode) {
1258 } else if (inode > u->inode) {
1261 if (max < u->offset)
1263 else if (min > u->offset)
1274 * For a given range in vma, build a list of probes that need to be inserted.
1276 static void build_probe_list(struct inode *inode,
1277 struct vm_area_struct *vma,
1278 unsigned long start, unsigned long end,
1279 struct list_head *head)
1282 struct rb_node *n, *t;
1285 INIT_LIST_HEAD(head);
1286 min = vaddr_to_offset(vma, start);
1287 max = min + (end - start) - 1;
1289 spin_lock(&uprobes_treelock);
1290 n = find_node_in_range(inode, min, max);
1292 for (t = n; t; t = rb_prev(t)) {
1293 u = rb_entry(t, struct uprobe, rb_node);
1294 if (u->inode != inode || u->offset < min)
1296 list_add(&u->pending_list, head);
1299 for (t = n; (t = rb_next(t)); ) {
1300 u = rb_entry(t, struct uprobe, rb_node);
1301 if (u->inode != inode || u->offset > max)
1303 list_add(&u->pending_list, head);
1307 spin_unlock(&uprobes_treelock);
1310 /* @vma contains reference counter, not the probed instruction. */
1311 static int delayed_ref_ctr_inc(struct vm_area_struct *vma)
1313 struct list_head *pos, *q;
1314 struct delayed_uprobe *du;
1315 unsigned long vaddr;
1316 int ret = 0, err = 0;
1318 mutex_lock(&delayed_uprobe_lock);
1319 list_for_each_safe(pos, q, &delayed_uprobe_list) {
1320 du = list_entry(pos, struct delayed_uprobe, list);
1322 if (du->mm != vma->vm_mm ||
1323 !valid_ref_ctr_vma(du->uprobe, vma))
1326 vaddr = offset_to_vaddr(vma, du->uprobe->ref_ctr_offset);
1327 ret = __update_ref_ctr(vma->vm_mm, vaddr, 1);
1329 update_ref_ctr_warn(du->uprobe, vma->vm_mm, 1);
1333 delayed_uprobe_delete(du);
1335 mutex_unlock(&delayed_uprobe_lock);
1340 * Called from mmap_region/vma_adjust with mm->mmap_sem acquired.
1342 * Currently we ignore all errors and always return 0, the callers
1343 * can't handle the failure anyway.
1345 int uprobe_mmap(struct vm_area_struct *vma)
1347 struct list_head tmp_list;
1348 struct uprobe *uprobe, *u;
1349 struct inode *inode;
1351 if (no_uprobe_events())
1355 (vma->vm_flags & (VM_WRITE|VM_SHARED)) == VM_WRITE &&
1356 test_bit(MMF_HAS_UPROBES, &vma->vm_mm->flags))
1357 delayed_ref_ctr_inc(vma);
1359 if (!valid_vma(vma, true))
1362 inode = file_inode(vma->vm_file);
1366 mutex_lock(uprobes_mmap_hash(inode));
1367 build_probe_list(inode, vma, vma->vm_start, vma->vm_end, &tmp_list);
1369 * We can race with uprobe_unregister(), this uprobe can be already
1370 * removed. But in this case filter_chain() must return false, all
1371 * consumers have gone away.
1373 list_for_each_entry_safe(uprobe, u, &tmp_list, pending_list) {
1374 if (!fatal_signal_pending(current) &&
1375 filter_chain(uprobe, UPROBE_FILTER_MMAP, vma->vm_mm)) {
1376 unsigned long vaddr = offset_to_vaddr(vma, uprobe->offset);
1377 install_breakpoint(uprobe, vma->vm_mm, vma, vaddr);
1381 mutex_unlock(uprobes_mmap_hash(inode));
1387 vma_has_uprobes(struct vm_area_struct *vma, unsigned long start, unsigned long end)
1390 struct inode *inode;
1393 inode = file_inode(vma->vm_file);
1395 min = vaddr_to_offset(vma, start);
1396 max = min + (end - start) - 1;
1398 spin_lock(&uprobes_treelock);
1399 n = find_node_in_range(inode, min, max);
1400 spin_unlock(&uprobes_treelock);
1406 * Called in context of a munmap of a vma.
1408 void uprobe_munmap(struct vm_area_struct *vma, unsigned long start, unsigned long end)
1410 if (no_uprobe_events() || !valid_vma(vma, false))
1413 if (!atomic_read(&vma->vm_mm->mm_users)) /* called by mmput() ? */
1416 if (!test_bit(MMF_HAS_UPROBES, &vma->vm_mm->flags) ||
1417 test_bit(MMF_RECALC_UPROBES, &vma->vm_mm->flags))
1420 if (vma_has_uprobes(vma, start, end))
1421 set_bit(MMF_RECALC_UPROBES, &vma->vm_mm->flags);
1424 /* Slot allocation for XOL */
1425 static int xol_add_vma(struct mm_struct *mm, struct xol_area *area)
1427 struct vm_area_struct *vma;
1430 if (down_write_killable(&mm->mmap_sem))
1433 if (mm->uprobes_state.xol_area) {
1439 /* Try to map as high as possible, this is only a hint. */
1440 area->vaddr = get_unmapped_area(NULL, TASK_SIZE - PAGE_SIZE,
1442 if (area->vaddr & ~PAGE_MASK) {
1448 vma = _install_special_mapping(mm, area->vaddr, PAGE_SIZE,
1449 VM_EXEC|VM_MAYEXEC|VM_DONTCOPY|VM_IO,
1450 &area->xol_mapping);
1457 /* pairs with get_xol_area() */
1458 smp_store_release(&mm->uprobes_state.xol_area, area); /* ^^^ */
1460 up_write(&mm->mmap_sem);
1465 static struct xol_area *__create_xol_area(unsigned long vaddr)
1467 struct mm_struct *mm = current->mm;
1468 uprobe_opcode_t insn = UPROBE_SWBP_INSN;
1469 struct xol_area *area;
1471 area = kmalloc(sizeof(*area), GFP_KERNEL);
1472 if (unlikely(!area))
1475 area->bitmap = kcalloc(BITS_TO_LONGS(UINSNS_PER_PAGE), sizeof(long),
1480 area->xol_mapping.name = "[uprobes]";
1481 area->xol_mapping.fault = NULL;
1482 area->xol_mapping.pages = area->pages;
1483 area->pages[0] = alloc_page(GFP_HIGHUSER);
1484 if (!area->pages[0])
1486 area->pages[1] = NULL;
1488 area->vaddr = vaddr;
1489 init_waitqueue_head(&area->wq);
1490 /* Reserve the 1st slot for get_trampoline_vaddr() */
1491 set_bit(0, area->bitmap);
1492 atomic_set(&area->slot_count, 1);
1493 arch_uprobe_copy_ixol(area->pages[0], 0, &insn, UPROBE_SWBP_INSN_SIZE);
1495 if (!xol_add_vma(mm, area))
1498 __free_page(area->pages[0]);
1500 kfree(area->bitmap);
1508 * get_xol_area - Allocate process's xol_area if necessary.
1509 * This area will be used for storing instructions for execution out of line.
1511 * Returns the allocated area or NULL.
1513 static struct xol_area *get_xol_area(void)
1515 struct mm_struct *mm = current->mm;
1516 struct xol_area *area;
1518 if (!mm->uprobes_state.xol_area)
1519 __create_xol_area(0);
1521 /* Pairs with xol_add_vma() smp_store_release() */
1522 area = READ_ONCE(mm->uprobes_state.xol_area); /* ^^^ */
1527 * uprobe_clear_state - Free the area allocated for slots.
1529 void uprobe_clear_state(struct mm_struct *mm)
1531 struct xol_area *area = mm->uprobes_state.xol_area;
1533 mutex_lock(&delayed_uprobe_lock);
1534 delayed_uprobe_remove(NULL, mm);
1535 mutex_unlock(&delayed_uprobe_lock);
1540 put_page(area->pages[0]);
1541 kfree(area->bitmap);
1545 void uprobe_start_dup_mmap(void)
1547 percpu_down_read(&dup_mmap_sem);
1550 void uprobe_end_dup_mmap(void)
1552 percpu_up_read(&dup_mmap_sem);
1555 void uprobe_dup_mmap(struct mm_struct *oldmm, struct mm_struct *newmm)
1557 if (test_bit(MMF_HAS_UPROBES, &oldmm->flags)) {
1558 set_bit(MMF_HAS_UPROBES, &newmm->flags);
1559 /* unconditionally, dup_mmap() skips VM_DONTCOPY vmas */
1560 set_bit(MMF_RECALC_UPROBES, &newmm->flags);
1565 * - search for a free slot.
1567 static unsigned long xol_take_insn_slot(struct xol_area *area)
1569 unsigned long slot_addr;
1573 slot_nr = find_first_zero_bit(area->bitmap, UINSNS_PER_PAGE);
1574 if (slot_nr < UINSNS_PER_PAGE) {
1575 if (!test_and_set_bit(slot_nr, area->bitmap))
1578 slot_nr = UINSNS_PER_PAGE;
1581 wait_event(area->wq, (atomic_read(&area->slot_count) < UINSNS_PER_PAGE));
1582 } while (slot_nr >= UINSNS_PER_PAGE);
1584 slot_addr = area->vaddr + (slot_nr * UPROBE_XOL_SLOT_BYTES);
1585 atomic_inc(&area->slot_count);
1591 * xol_get_insn_slot - allocate a slot for xol.
1592 * Returns the allocated slot address or 0.
1594 static unsigned long xol_get_insn_slot(struct uprobe *uprobe)
1596 struct xol_area *area;
1597 unsigned long xol_vaddr;
1599 area = get_xol_area();
1603 xol_vaddr = xol_take_insn_slot(area);
1604 if (unlikely(!xol_vaddr))
1607 arch_uprobe_copy_ixol(area->pages[0], xol_vaddr,
1608 &uprobe->arch.ixol, sizeof(uprobe->arch.ixol));
1614 * xol_free_insn_slot - If slot was earlier allocated by
1615 * @xol_get_insn_slot(), make the slot available for
1616 * subsequent requests.
1618 static void xol_free_insn_slot(struct task_struct *tsk)
1620 struct xol_area *area;
1621 unsigned long vma_end;
1622 unsigned long slot_addr;
1624 if (!tsk->mm || !tsk->mm->uprobes_state.xol_area || !tsk->utask)
1627 slot_addr = tsk->utask->xol_vaddr;
1628 if (unlikely(!slot_addr))
1631 area = tsk->mm->uprobes_state.xol_area;
1632 vma_end = area->vaddr + PAGE_SIZE;
1633 if (area->vaddr <= slot_addr && slot_addr < vma_end) {
1634 unsigned long offset;
1637 offset = slot_addr - area->vaddr;
1638 slot_nr = offset / UPROBE_XOL_SLOT_BYTES;
1639 if (slot_nr >= UINSNS_PER_PAGE)
1642 clear_bit(slot_nr, area->bitmap);
1643 atomic_dec(&area->slot_count);
1644 smp_mb__after_atomic(); /* pairs with prepare_to_wait() */
1645 if (waitqueue_active(&area->wq))
1648 tsk->utask->xol_vaddr = 0;
1652 void __weak arch_uprobe_copy_ixol(struct page *page, unsigned long vaddr,
1653 void *src, unsigned long len)
1655 /* Initialize the slot */
1656 copy_to_page(page, vaddr, src, len);
1659 * We probably need flush_icache_user_range() but it needs vma.
1660 * This should work on most of architectures by default. If
1661 * architecture needs to do something different it can define
1662 * its own version of the function.
1664 flush_dcache_page(page);
1668 * uprobe_get_swbp_addr - compute address of swbp given post-swbp regs
1669 * @regs: Reflects the saved state of the task after it has hit a breakpoint
1671 * Return the address of the breakpoint instruction.
1673 unsigned long __weak uprobe_get_swbp_addr(struct pt_regs *regs)
1675 return instruction_pointer(regs) - UPROBE_SWBP_INSN_SIZE;
1678 unsigned long uprobe_get_trap_addr(struct pt_regs *regs)
1680 struct uprobe_task *utask = current->utask;
1682 if (unlikely(utask && utask->active_uprobe))
1683 return utask->vaddr;
1685 return instruction_pointer(regs);
1688 static struct return_instance *free_ret_instance(struct return_instance *ri)
1690 struct return_instance *next = ri->next;
1691 put_uprobe(ri->uprobe);
1697 * Called with no locks held.
1698 * Called in context of an exiting or an exec-ing thread.
1700 void uprobe_free_utask(struct task_struct *t)
1702 struct uprobe_task *utask = t->utask;
1703 struct return_instance *ri;
1708 if (utask->active_uprobe)
1709 put_uprobe(utask->active_uprobe);
1711 ri = utask->return_instances;
1713 ri = free_ret_instance(ri);
1715 xol_free_insn_slot(t);
1721 * Allocate a uprobe_task object for the task if if necessary.
1722 * Called when the thread hits a breakpoint.
1725 * - pointer to new uprobe_task on success
1728 static struct uprobe_task *get_utask(void)
1730 if (!current->utask)
1731 current->utask = kzalloc(sizeof(struct uprobe_task), GFP_KERNEL);
1732 return current->utask;
1735 static int dup_utask(struct task_struct *t, struct uprobe_task *o_utask)
1737 struct uprobe_task *n_utask;
1738 struct return_instance **p, *o, *n;
1740 n_utask = kzalloc(sizeof(struct uprobe_task), GFP_KERNEL);
1745 p = &n_utask->return_instances;
1746 for (o = o_utask->return_instances; o; o = o->next) {
1747 n = kmalloc(sizeof(struct return_instance), GFP_KERNEL);
1752 get_uprobe(n->uprobe);
1763 static void uprobe_warn(struct task_struct *t, const char *msg)
1765 pr_warn("uprobe: %s:%d failed to %s\n",
1766 current->comm, current->pid, msg);
1769 static void dup_xol_work(struct callback_head *work)
1771 if (current->flags & PF_EXITING)
1774 if (!__create_xol_area(current->utask->dup_xol_addr) &&
1775 !fatal_signal_pending(current))
1776 uprobe_warn(current, "dup xol area");
1780 * Called in context of a new clone/fork from copy_process.
1782 void uprobe_copy_process(struct task_struct *t, unsigned long flags)
1784 struct uprobe_task *utask = current->utask;
1785 struct mm_struct *mm = current->mm;
1786 struct xol_area *area;
1790 if (!utask || !utask->return_instances)
1793 if (mm == t->mm && !(flags & CLONE_VFORK))
1796 if (dup_utask(t, utask))
1797 return uprobe_warn(t, "dup ret instances");
1799 /* The task can fork() after dup_xol_work() fails */
1800 area = mm->uprobes_state.xol_area;
1802 return uprobe_warn(t, "dup xol area");
1807 t->utask->dup_xol_addr = area->vaddr;
1808 init_task_work(&t->utask->dup_xol_work, dup_xol_work);
1809 task_work_add(t, &t->utask->dup_xol_work, true);
1813 * Current area->vaddr notion assume the trampoline address is always
1814 * equal area->vaddr.
1816 * Returns -1 in case the xol_area is not allocated.
1818 static unsigned long get_trampoline_vaddr(void)
1820 struct xol_area *area;
1821 unsigned long trampoline_vaddr = -1;
1823 /* Pairs with xol_add_vma() smp_store_release() */
1824 area = READ_ONCE(current->mm->uprobes_state.xol_area); /* ^^^ */
1826 trampoline_vaddr = area->vaddr;
1828 return trampoline_vaddr;
1831 static void cleanup_return_instances(struct uprobe_task *utask, bool chained,
1832 struct pt_regs *regs)
1834 struct return_instance *ri = utask->return_instances;
1835 enum rp_check ctx = chained ? RP_CHECK_CHAIN_CALL : RP_CHECK_CALL;
1837 while (ri && !arch_uretprobe_is_alive(ri, ctx, regs)) {
1838 ri = free_ret_instance(ri);
1841 utask->return_instances = ri;
1844 static void prepare_uretprobe(struct uprobe *uprobe, struct pt_regs *regs)
1846 struct return_instance *ri;
1847 struct uprobe_task *utask;
1848 unsigned long orig_ret_vaddr, trampoline_vaddr;
1851 if (!get_xol_area())
1854 utask = get_utask();
1858 if (utask->depth >= MAX_URETPROBE_DEPTH) {
1859 printk_ratelimited(KERN_INFO "uprobe: omit uretprobe due to"
1860 " nestedness limit pid/tgid=%d/%d\n",
1861 current->pid, current->tgid);
1865 ri = kmalloc(sizeof(struct return_instance), GFP_KERNEL);
1869 trampoline_vaddr = get_trampoline_vaddr();
1870 orig_ret_vaddr = arch_uretprobe_hijack_return_addr(trampoline_vaddr, regs);
1871 if (orig_ret_vaddr == -1)
1874 /* drop the entries invalidated by longjmp() */
1875 chained = (orig_ret_vaddr == trampoline_vaddr);
1876 cleanup_return_instances(utask, chained, regs);
1879 * We don't want to keep trampoline address in stack, rather keep the
1880 * original return address of first caller thru all the consequent
1881 * instances. This also makes breakpoint unwrapping easier.
1884 if (!utask->return_instances) {
1886 * This situation is not possible. Likely we have an
1887 * attack from user-space.
1889 uprobe_warn(current, "handle tail call");
1892 orig_ret_vaddr = utask->return_instances->orig_ret_vaddr;
1895 ri->uprobe = get_uprobe(uprobe);
1896 ri->func = instruction_pointer(regs);
1897 ri->stack = user_stack_pointer(regs);
1898 ri->orig_ret_vaddr = orig_ret_vaddr;
1899 ri->chained = chained;
1902 ri->next = utask->return_instances;
1903 utask->return_instances = ri;
1910 /* Prepare to single-step probed instruction out of line. */
1912 pre_ssout(struct uprobe *uprobe, struct pt_regs *regs, unsigned long bp_vaddr)
1914 struct uprobe_task *utask;
1915 unsigned long xol_vaddr;
1918 utask = get_utask();
1922 xol_vaddr = xol_get_insn_slot(uprobe);
1926 utask->xol_vaddr = xol_vaddr;
1927 utask->vaddr = bp_vaddr;
1929 err = arch_uprobe_pre_xol(&uprobe->arch, regs);
1930 if (unlikely(err)) {
1931 xol_free_insn_slot(current);
1935 utask->active_uprobe = uprobe;
1936 utask->state = UTASK_SSTEP;
1941 * If we are singlestepping, then ensure this thread is not connected to
1942 * non-fatal signals until completion of singlestep. When xol insn itself
1943 * triggers the signal, restart the original insn even if the task is
1944 * already SIGKILL'ed (since coredump should report the correct ip). This
1945 * is even more important if the task has a handler for SIGSEGV/etc, The
1946 * _same_ instruction should be repeated again after return from the signal
1947 * handler, and SSTEP can never finish in this case.
1949 bool uprobe_deny_signal(void)
1951 struct task_struct *t = current;
1952 struct uprobe_task *utask = t->utask;
1954 if (likely(!utask || !utask->active_uprobe))
1957 WARN_ON_ONCE(utask->state != UTASK_SSTEP);
1959 if (signal_pending(t)) {
1960 spin_lock_irq(&t->sighand->siglock);
1961 clear_tsk_thread_flag(t, TIF_SIGPENDING);
1962 spin_unlock_irq(&t->sighand->siglock);
1964 if (__fatal_signal_pending(t) || arch_uprobe_xol_was_trapped(t)) {
1965 utask->state = UTASK_SSTEP_TRAPPED;
1966 set_tsk_thread_flag(t, TIF_UPROBE);
1973 static void mmf_recalc_uprobes(struct mm_struct *mm)
1975 struct vm_area_struct *vma;
1977 for (vma = mm->mmap; vma; vma = vma->vm_next) {
1978 if (!valid_vma(vma, false))
1981 * This is not strictly accurate, we can race with
1982 * uprobe_unregister() and see the already removed
1983 * uprobe if delete_uprobe() was not yet called.
1984 * Or this uprobe can be filtered out.
1986 if (vma_has_uprobes(vma, vma->vm_start, vma->vm_end))
1990 clear_bit(MMF_HAS_UPROBES, &mm->flags);
1993 static int is_trap_at_addr(struct mm_struct *mm, unsigned long vaddr)
1996 uprobe_opcode_t opcode;
1999 pagefault_disable();
2000 result = __get_user(opcode, (uprobe_opcode_t __user *)vaddr);
2003 if (likely(result == 0))
2007 * The NULL 'tsk' here ensures that any faults that occur here
2008 * will not be accounted to the task. 'mm' *is* current->mm,
2009 * but we treat this as a 'remote' access since it is
2010 * essentially a kernel access to the memory.
2012 result = get_user_pages_remote(NULL, mm, vaddr, 1, FOLL_FORCE, &page,
2017 copy_from_page(page, vaddr, &opcode, UPROBE_SWBP_INSN_SIZE);
2020 /* This needs to return true for any variant of the trap insn */
2021 return is_trap_insn(&opcode);
2024 static struct uprobe *find_active_uprobe(unsigned long bp_vaddr, int *is_swbp)
2026 struct mm_struct *mm = current->mm;
2027 struct uprobe *uprobe = NULL;
2028 struct vm_area_struct *vma;
2030 down_read(&mm->mmap_sem);
2031 vma = find_vma(mm, bp_vaddr);
2032 if (vma && vma->vm_start <= bp_vaddr) {
2033 if (valid_vma(vma, false)) {
2034 struct inode *inode = file_inode(vma->vm_file);
2035 loff_t offset = vaddr_to_offset(vma, bp_vaddr);
2037 uprobe = find_uprobe(inode, offset);
2041 *is_swbp = is_trap_at_addr(mm, bp_vaddr);
2046 if (!uprobe && test_and_clear_bit(MMF_RECALC_UPROBES, &mm->flags))
2047 mmf_recalc_uprobes(mm);
2048 up_read(&mm->mmap_sem);
2053 static void handler_chain(struct uprobe *uprobe, struct pt_regs *regs)
2055 struct uprobe_consumer *uc;
2056 int remove = UPROBE_HANDLER_REMOVE;
2057 bool need_prep = false; /* prepare return uprobe, when needed */
2059 down_read(&uprobe->register_rwsem);
2060 for (uc = uprobe->consumers; uc; uc = uc->next) {
2064 rc = uc->handler(uc, regs);
2065 WARN(rc & ~UPROBE_HANDLER_MASK,
2066 "bad rc=0x%x from %ps()\n", rc, uc->handler);
2069 if (uc->ret_handler)
2075 if (need_prep && !remove)
2076 prepare_uretprobe(uprobe, regs); /* put bp at return */
2078 if (remove && uprobe->consumers) {
2079 WARN_ON(!uprobe_is_active(uprobe));
2080 unapply_uprobe(uprobe, current->mm);
2082 up_read(&uprobe->register_rwsem);
2086 handle_uretprobe_chain(struct return_instance *ri, struct pt_regs *regs)
2088 struct uprobe *uprobe = ri->uprobe;
2089 struct uprobe_consumer *uc;
2091 down_read(&uprobe->register_rwsem);
2092 for (uc = uprobe->consumers; uc; uc = uc->next) {
2093 if (uc->ret_handler)
2094 uc->ret_handler(uc, ri->func, regs);
2096 up_read(&uprobe->register_rwsem);
2099 static struct return_instance *find_next_ret_chain(struct return_instance *ri)
2104 chained = ri->chained;
2105 ri = ri->next; /* can't be NULL if chained */
2111 static void handle_trampoline(struct pt_regs *regs)
2113 struct uprobe_task *utask;
2114 struct return_instance *ri, *next;
2117 utask = current->utask;
2121 ri = utask->return_instances;
2127 * We should throw out the frames invalidated by longjmp().
2128 * If this chain is valid, then the next one should be alive
2129 * or NULL; the latter case means that nobody but ri->func
2130 * could hit this trampoline on return. TODO: sigaltstack().
2132 next = find_next_ret_chain(ri);
2133 valid = !next || arch_uretprobe_is_alive(next, RP_CHECK_RET, regs);
2135 instruction_pointer_set(regs, ri->orig_ret_vaddr);
2138 handle_uretprobe_chain(ri, regs);
2139 ri = free_ret_instance(ri);
2141 } while (ri != next);
2144 utask->return_instances = ri;
2148 uprobe_warn(current, "handle uretprobe, sending SIGILL.");
2153 bool __weak arch_uprobe_ignore(struct arch_uprobe *aup, struct pt_regs *regs)
2158 bool __weak arch_uretprobe_is_alive(struct return_instance *ret, enum rp_check ctx,
2159 struct pt_regs *regs)
2165 * Run handler and ask thread to singlestep.
2166 * Ensure all non-fatal signals cannot interrupt thread while it singlesteps.
2168 static void handle_swbp(struct pt_regs *regs)
2170 struct uprobe *uprobe;
2171 unsigned long bp_vaddr;
2172 int uninitialized_var(is_swbp);
2174 bp_vaddr = uprobe_get_swbp_addr(regs);
2175 if (bp_vaddr == get_trampoline_vaddr())
2176 return handle_trampoline(regs);
2178 uprobe = find_active_uprobe(bp_vaddr, &is_swbp);
2181 /* No matching uprobe; signal SIGTRAP. */
2182 send_sig(SIGTRAP, current, 0);
2185 * Either we raced with uprobe_unregister() or we can't
2186 * access this memory. The latter is only possible if
2187 * another thread plays with our ->mm. In both cases
2188 * we can simply restart. If this vma was unmapped we
2189 * can pretend this insn was not executed yet and get
2190 * the (correct) SIGSEGV after restart.
2192 instruction_pointer_set(regs, bp_vaddr);
2197 /* change it in advance for ->handler() and restart */
2198 instruction_pointer_set(regs, bp_vaddr);
2201 * TODO: move copy_insn/etc into _register and remove this hack.
2202 * After we hit the bp, _unregister + _register can install the
2203 * new and not-yet-analyzed uprobe at the same address, restart.
2205 if (unlikely(!test_bit(UPROBE_COPY_INSN, &uprobe->flags)))
2209 * Pairs with the smp_wmb() in prepare_uprobe().
2211 * Guarantees that if we see the UPROBE_COPY_INSN bit set, then
2212 * we must also see the stores to &uprobe->arch performed by the
2213 * prepare_uprobe() call.
2217 /* Tracing handlers use ->utask to communicate with fetch methods */
2221 if (arch_uprobe_ignore(&uprobe->arch, regs))
2224 handler_chain(uprobe, regs);
2226 if (arch_uprobe_skip_sstep(&uprobe->arch, regs))
2229 if (!pre_ssout(uprobe, regs, bp_vaddr))
2232 /* arch_uprobe_skip_sstep() succeeded, or restart if can't singlestep */
2238 * Perform required fix-ups and disable singlestep.
2239 * Allow pending signals to take effect.
2241 static void handle_singlestep(struct uprobe_task *utask, struct pt_regs *regs)
2243 struct uprobe *uprobe;
2246 uprobe = utask->active_uprobe;
2247 if (utask->state == UTASK_SSTEP_ACK)
2248 err = arch_uprobe_post_xol(&uprobe->arch, regs);
2249 else if (utask->state == UTASK_SSTEP_TRAPPED)
2250 arch_uprobe_abort_xol(&uprobe->arch, regs);
2255 utask->active_uprobe = NULL;
2256 utask->state = UTASK_RUNNING;
2257 xol_free_insn_slot(current);
2259 spin_lock_irq(¤t->sighand->siglock);
2260 recalc_sigpending(); /* see uprobe_deny_signal() */
2261 spin_unlock_irq(¤t->sighand->siglock);
2263 if (unlikely(err)) {
2264 uprobe_warn(current, "execute the probed insn, sending SIGILL.");
2270 * On breakpoint hit, breakpoint notifier sets the TIF_UPROBE flag and
2271 * allows the thread to return from interrupt. After that handle_swbp()
2272 * sets utask->active_uprobe.
2274 * On singlestep exception, singlestep notifier sets the TIF_UPROBE flag
2275 * and allows the thread to return from interrupt.
2277 * While returning to userspace, thread notices the TIF_UPROBE flag and calls
2278 * uprobe_notify_resume().
2280 void uprobe_notify_resume(struct pt_regs *regs)
2282 struct uprobe_task *utask;
2284 clear_thread_flag(TIF_UPROBE);
2286 utask = current->utask;
2287 if (utask && utask->active_uprobe)
2288 handle_singlestep(utask, regs);
2294 * uprobe_pre_sstep_notifier gets called from interrupt context as part of
2295 * notifier mechanism. Set TIF_UPROBE flag and indicate breakpoint hit.
2297 int uprobe_pre_sstep_notifier(struct pt_regs *regs)
2302 if (!test_bit(MMF_HAS_UPROBES, ¤t->mm->flags) &&
2303 (!current->utask || !current->utask->return_instances))
2306 set_thread_flag(TIF_UPROBE);
2311 * uprobe_post_sstep_notifier gets called in interrupt context as part of notifier
2312 * mechanism. Set TIF_UPROBE flag and indicate completion of singlestep.
2314 int uprobe_post_sstep_notifier(struct pt_regs *regs)
2316 struct uprobe_task *utask = current->utask;
2318 if (!current->mm || !utask || !utask->active_uprobe)
2319 /* task is currently not uprobed */
2322 utask->state = UTASK_SSTEP_ACK;
2323 set_thread_flag(TIF_UPROBE);
2327 static struct notifier_block uprobe_exception_nb = {
2328 .notifier_call = arch_uprobe_exception_notify,
2329 .priority = INT_MAX-1, /* notified after kprobes, kgdb */
2332 void __init uprobes_init(void)
2336 for (i = 0; i < UPROBES_HASH_SZ; i++)
2337 mutex_init(&uprobes_mmap_mutex[i]);
2339 BUG_ON(register_die_notifier(&uprobe_exception_nb));