1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3 * User-space Probes (UProbes)
4 *
5 * Copyright (C) IBM Corporation, 2008-2012
6 * Authors:
7 * Srikar Dronamraju
8 * Jim Keniston
9 * Copyright (C) 2011-2012 Red Hat, Inc., Peter Zijlstra
10 */
11
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> /* folio_free_swap */
23 #include <linux/ptrace.h> /* user_enable_single_step */
24 #include <linux/kdebug.h> /* notifier mechanism */
25 #include <linux/percpu-rwsem.h>
26 #include <linux/task_work.h>
27 #include <linux/shmem_fs.h>
28 #include <linux/khugepaged.h>
29
30 #include <linux/uprobes.h>
31
32 #define UINSNS_PER_PAGE (PAGE_SIZE/UPROBE_XOL_SLOT_BYTES)
33 #define MAX_UPROBE_XOL_SLOTS UINSNS_PER_PAGE
34
35 static struct rb_root uprobes_tree = RB_ROOT;
36 /*
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?
39 */
40 #define no_uprobe_events() RB_EMPTY_ROOT(&uprobes_tree)
41
42 static DEFINE_SPINLOCK(uprobes_treelock); /* serialize rbtree access */
43
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])
48
49 DEFINE_STATIC_PERCPU_RWSEM(dup_mmap_sem);
50
51 /* Have a copy of original instruction */
52 #define UPROBE_COPY_INSN 0
53
54 struct uprobe {
55 struct rb_node rb_node; /* node in the rb tree */
56 refcount_t ref;
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 */
62 loff_t offset;
63 loff_t ref_ctr_offset;
64 unsigned long flags;
65
66 /*
67 * The generic code assumes that it has two members of unknown type
68 * owned by the arch-specific code:
69 *
70 * insn - copy_insn() saves the original instruction here for
71 * arch_uprobe_analyze_insn().
72 *
73 * ixol - potentially modified instruction to execute out of
74 * line, copied to xol_area by xol_get_insn_slot().
75 */
76 struct arch_uprobe arch;
77 };
78
79 struct delayed_uprobe {
80 struct list_head list;
81 struct uprobe *uprobe;
82 struct mm_struct *mm;
83 };
84
85 static DEFINE_MUTEX(delayed_uprobe_lock);
86 static LIST_HEAD(delayed_uprobe_list);
87
88 /*
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().
92 *
93 * On a breakpoint hit, thread contests for a slot. It frees the
94 * slot after singlestep. Currently a fixed number of slots are
95 * allocated.
96 */
97 struct xol_area {
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 */
101
102 struct vm_special_mapping xol_mapping;
103 struct page *pages[2];
104 /*
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.
108 */
109 unsigned long vaddr; /* Page(s) of instruction slots */
110 };
111
112 /*
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
118 * executable vma.
119 */
valid_vma(struct vm_area_struct * vma,bool is_register)120 static bool valid_vma(struct vm_area_struct *vma, bool is_register)
121 {
122 vm_flags_t flags = VM_HUGETLB | VM_MAYEXEC | VM_MAYSHARE;
123
124 if (is_register)
125 flags |= VM_WRITE;
126
127 return vma->vm_file && (vma->vm_flags & flags) == VM_MAYEXEC;
128 }
129
offset_to_vaddr(struct vm_area_struct * vma,loff_t offset)130 static unsigned long offset_to_vaddr(struct vm_area_struct *vma, loff_t offset)
131 {
132 return vma->vm_start + offset - ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
133 }
134
vaddr_to_offset(struct vm_area_struct * vma,unsigned long vaddr)135 static loff_t vaddr_to_offset(struct vm_area_struct *vma, unsigned long vaddr)
136 {
137 return ((loff_t)vma->vm_pgoff << PAGE_SHIFT) + (vaddr - vma->vm_start);
138 }
139
140 /**
141 * __replace_page - replace page in vma by new page.
142 * based on replace_page in mm/ksm.c
143 *
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
148 *
149 * If @new_page is NULL, only unmap @old_page.
150 *
151 * Returns 0 on success, negative error code otherwise.
152 */
__replace_page(struct vm_area_struct * vma,unsigned long addr,struct page * old_page,struct page * new_page)153 static int __replace_page(struct vm_area_struct *vma, unsigned long addr,
154 struct page *old_page, struct page *new_page)
155 {
156 struct folio *old_folio = page_folio(old_page);
157 struct folio *new_folio;
158 struct mm_struct *mm = vma->vm_mm;
159 DEFINE_FOLIO_VMA_WALK(pvmw, old_folio, vma, addr, 0);
160 int err;
161 struct mmu_notifier_range range;
162 pte_t pte;
163
164 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, addr,
165 addr + PAGE_SIZE);
166
167 if (new_page) {
168 new_folio = page_folio(new_page);
169 err = mem_cgroup_charge(new_folio, vma->vm_mm, GFP_KERNEL);
170 if (err)
171 return err;
172 }
173
174 /* For folio_free_swap() below */
175 folio_lock(old_folio);
176
177 mmu_notifier_invalidate_range_start(&range);
178 err = -EAGAIN;
179 if (!page_vma_mapped_walk(&pvmw))
180 goto unlock;
181 VM_BUG_ON_PAGE(addr != pvmw.address, old_page);
182 pte = ptep_get(pvmw.pte);
183
184 /*
185 * Handle PFN swap PTES, such as device-exclusive ones, that actually
186 * map pages: simply trigger GUP again to fix it up.
187 */
188 if (unlikely(!pte_present(pte))) {
189 page_vma_mapped_walk_done(&pvmw);
190 goto unlock;
191 }
192
193 if (new_page) {
194 folio_get(new_folio);
195 page_add_new_anon_rmap(new_page, vma, addr);
196 folio_add_lru_vma(new_folio, vma);
197 } else
198 /* no new page, just dec_mm_counter for old_page */
199 dec_mm_counter(mm, MM_ANONPAGES);
200
201 if (!folio_test_anon(old_folio)) {
202 dec_mm_counter(mm, mm_counter_file(old_page));
203 inc_mm_counter(mm, MM_ANONPAGES);
204 }
205
206 flush_cache_page(vma, addr, pte_pfn(pte));
207 ptep_clear_flush(vma, addr, pvmw.pte);
208 if (new_page)
209 set_pte_at_notify(mm, addr, pvmw.pte,
210 mk_pte(new_page, vma->vm_page_prot));
211
212 page_remove_rmap(old_page, vma, false);
213 if (!folio_mapped(old_folio))
214 folio_free_swap(old_folio);
215 page_vma_mapped_walk_done(&pvmw);
216 folio_put(old_folio);
217
218 err = 0;
219 unlock:
220 mmu_notifier_invalidate_range_end(&range);
221 folio_unlock(old_folio);
222 return err;
223 }
224
225 /**
226 * is_swbp_insn - check if instruction is breakpoint instruction.
227 * @insn: instruction to be checked.
228 * Default implementation of is_swbp_insn
229 * Returns true if @insn is a breakpoint instruction.
230 */
is_swbp_insn(uprobe_opcode_t * insn)231 bool __weak is_swbp_insn(uprobe_opcode_t *insn)
232 {
233 return *insn == UPROBE_SWBP_INSN;
234 }
235
236 /**
237 * is_trap_insn - check if instruction is breakpoint instruction.
238 * @insn: instruction to be checked.
239 * Default implementation of is_trap_insn
240 * Returns true if @insn is a breakpoint instruction.
241 *
242 * This function is needed for the case where an architecture has multiple
243 * trap instructions (like powerpc).
244 */
is_trap_insn(uprobe_opcode_t * insn)245 bool __weak is_trap_insn(uprobe_opcode_t *insn)
246 {
247 return is_swbp_insn(insn);
248 }
249
copy_from_page(struct page * page,unsigned long vaddr,void * dst,int len)250 static void copy_from_page(struct page *page, unsigned long vaddr, void *dst, int len)
251 {
252 void *kaddr = kmap_atomic(page);
253 memcpy(dst, kaddr + (vaddr & ~PAGE_MASK), len);
254 kunmap_atomic(kaddr);
255 }
256
copy_to_page(struct page * page,unsigned long vaddr,const void * src,int len)257 static void copy_to_page(struct page *page, unsigned long vaddr, const void *src, int len)
258 {
259 void *kaddr = kmap_atomic(page);
260 memcpy(kaddr + (vaddr & ~PAGE_MASK), src, len);
261 kunmap_atomic(kaddr);
262 }
263
verify_opcode(struct page * page,unsigned long vaddr,uprobe_opcode_t * new_opcode)264 static int verify_opcode(struct page *page, unsigned long vaddr, uprobe_opcode_t *new_opcode)
265 {
266 uprobe_opcode_t old_opcode;
267 bool is_swbp;
268
269 /*
270 * Note: We only check if the old_opcode is UPROBE_SWBP_INSN here.
271 * We do not check if it is any other 'trap variant' which could
272 * be conditional trap instruction such as the one powerpc supports.
273 *
274 * The logic is that we do not care if the underlying instruction
275 * is a trap variant; uprobes always wins over any other (gdb)
276 * breakpoint.
277 */
278 copy_from_page(page, vaddr, &old_opcode, UPROBE_SWBP_INSN_SIZE);
279 is_swbp = is_swbp_insn(&old_opcode);
280
281 if (is_swbp_insn(new_opcode)) {
282 if (is_swbp) /* register: already installed? */
283 return 0;
284 } else {
285 if (!is_swbp) /* unregister: was it changed by us? */
286 return 0;
287 }
288
289 return 1;
290 }
291
292 static struct delayed_uprobe *
delayed_uprobe_check(struct uprobe * uprobe,struct mm_struct * mm)293 delayed_uprobe_check(struct uprobe *uprobe, struct mm_struct *mm)
294 {
295 struct delayed_uprobe *du;
296
297 list_for_each_entry(du, &delayed_uprobe_list, list)
298 if (du->uprobe == uprobe && du->mm == mm)
299 return du;
300 return NULL;
301 }
302
delayed_uprobe_add(struct uprobe * uprobe,struct mm_struct * mm)303 static int delayed_uprobe_add(struct uprobe *uprobe, struct mm_struct *mm)
304 {
305 struct delayed_uprobe *du;
306
307 if (delayed_uprobe_check(uprobe, mm))
308 return 0;
309
310 du = kzalloc(sizeof(*du), GFP_KERNEL);
311 if (!du)
312 return -ENOMEM;
313
314 du->uprobe = uprobe;
315 du->mm = mm;
316 list_add(&du->list, &delayed_uprobe_list);
317 return 0;
318 }
319
delayed_uprobe_delete(struct delayed_uprobe * du)320 static void delayed_uprobe_delete(struct delayed_uprobe *du)
321 {
322 if (WARN_ON(!du))
323 return;
324 list_del(&du->list);
325 kfree(du);
326 }
327
delayed_uprobe_remove(struct uprobe * uprobe,struct mm_struct * mm)328 static void delayed_uprobe_remove(struct uprobe *uprobe, struct mm_struct *mm)
329 {
330 struct list_head *pos, *q;
331 struct delayed_uprobe *du;
332
333 if (!uprobe && !mm)
334 return;
335
336 list_for_each_safe(pos, q, &delayed_uprobe_list) {
337 du = list_entry(pos, struct delayed_uprobe, list);
338
339 if (uprobe && du->uprobe != uprobe)
340 continue;
341 if (mm && du->mm != mm)
342 continue;
343
344 delayed_uprobe_delete(du);
345 }
346 }
347
valid_ref_ctr_vma(struct uprobe * uprobe,struct vm_area_struct * vma)348 static bool valid_ref_ctr_vma(struct uprobe *uprobe,
349 struct vm_area_struct *vma)
350 {
351 unsigned long vaddr = offset_to_vaddr(vma, uprobe->ref_ctr_offset);
352
353 return uprobe->ref_ctr_offset &&
354 vma->vm_file &&
355 file_inode(vma->vm_file) == uprobe->inode &&
356 (vma->vm_flags & (VM_WRITE|VM_SHARED)) == VM_WRITE &&
357 vma->vm_start <= vaddr &&
358 vma->vm_end > vaddr;
359 }
360
361 static struct vm_area_struct *
find_ref_ctr_vma(struct uprobe * uprobe,struct mm_struct * mm)362 find_ref_ctr_vma(struct uprobe *uprobe, struct mm_struct *mm)
363 {
364 VMA_ITERATOR(vmi, mm, 0);
365 struct vm_area_struct *tmp;
366
367 for_each_vma(vmi, tmp)
368 if (valid_ref_ctr_vma(uprobe, tmp))
369 return tmp;
370
371 return NULL;
372 }
373
374 static int
__update_ref_ctr(struct mm_struct * mm,unsigned long vaddr,short d)375 __update_ref_ctr(struct mm_struct *mm, unsigned long vaddr, short d)
376 {
377 void *kaddr;
378 struct page *page;
379 int ret;
380 short *ptr;
381
382 if (!vaddr || !d)
383 return -EINVAL;
384
385 ret = get_user_pages_remote(mm, vaddr, 1,
386 FOLL_WRITE, &page, NULL);
387 if (unlikely(ret <= 0)) {
388 /*
389 * We are asking for 1 page. If get_user_pages_remote() fails,
390 * it may return 0, in that case we have to return error.
391 */
392 return ret == 0 ? -EBUSY : ret;
393 }
394
395 kaddr = kmap_atomic(page);
396 ptr = kaddr + (vaddr & ~PAGE_MASK);
397
398 if (unlikely(*ptr + d < 0)) {
399 pr_warn("ref_ctr going negative. vaddr: 0x%lx, "
400 "curr val: %d, delta: %d\n", vaddr, *ptr, d);
401 ret = -EINVAL;
402 goto out;
403 }
404
405 *ptr += d;
406 ret = 0;
407 out:
408 kunmap_atomic(kaddr);
409 put_page(page);
410 return ret;
411 }
412
update_ref_ctr_warn(struct uprobe * uprobe,struct mm_struct * mm,short d)413 static void update_ref_ctr_warn(struct uprobe *uprobe,
414 struct mm_struct *mm, short d)
415 {
416 pr_warn("ref_ctr %s failed for inode: 0x%lx offset: "
417 "0x%llx ref_ctr_offset: 0x%llx of mm: 0x%pK\n",
418 d > 0 ? "increment" : "decrement", uprobe->inode->i_ino,
419 (unsigned long long) uprobe->offset,
420 (unsigned long long) uprobe->ref_ctr_offset, mm);
421 }
422
update_ref_ctr(struct uprobe * uprobe,struct mm_struct * mm,short d)423 static int update_ref_ctr(struct uprobe *uprobe, struct mm_struct *mm,
424 short d)
425 {
426 struct vm_area_struct *rc_vma;
427 unsigned long rc_vaddr;
428 int ret = 0;
429
430 rc_vma = find_ref_ctr_vma(uprobe, mm);
431
432 if (rc_vma) {
433 rc_vaddr = offset_to_vaddr(rc_vma, uprobe->ref_ctr_offset);
434 ret = __update_ref_ctr(mm, rc_vaddr, d);
435 if (ret)
436 update_ref_ctr_warn(uprobe, mm, d);
437
438 if (d > 0)
439 return ret;
440 }
441
442 mutex_lock(&delayed_uprobe_lock);
443 if (d > 0)
444 ret = delayed_uprobe_add(uprobe, mm);
445 else
446 delayed_uprobe_remove(uprobe, mm);
447 mutex_unlock(&delayed_uprobe_lock);
448
449 return ret;
450 }
451
452 /*
453 * NOTE:
454 * Expect the breakpoint instruction to be the smallest size instruction for
455 * the architecture. If an arch has variable length instruction and the
456 * breakpoint instruction is not of the smallest length instruction
457 * supported by that architecture then we need to modify is_trap_at_addr and
458 * uprobe_write_opcode accordingly. This would never be a problem for archs
459 * that have fixed length instructions.
460 *
461 * uprobe_write_opcode - write the opcode at a given virtual address.
462 * @auprobe: arch specific probepoint information.
463 * @mm: the probed process address space.
464 * @vaddr: the virtual address to store the opcode.
465 * @opcode: opcode to be written at @vaddr.
466 *
467 * Called with mm->mmap_lock held for write.
468 * Return 0 (success) or a negative errno.
469 */
uprobe_write_opcode(struct arch_uprobe * auprobe,struct mm_struct * mm,unsigned long vaddr,uprobe_opcode_t opcode)470 int uprobe_write_opcode(struct arch_uprobe *auprobe, struct mm_struct *mm,
471 unsigned long vaddr, uprobe_opcode_t opcode)
472 {
473 struct uprobe *uprobe;
474 struct page *old_page, *new_page;
475 struct vm_area_struct *vma;
476 int ret, is_register, ref_ctr_updated = 0;
477 bool orig_page_huge = false;
478 unsigned int gup_flags = FOLL_FORCE;
479
480 is_register = is_swbp_insn(&opcode);
481 uprobe = container_of(auprobe, struct uprobe, arch);
482
483 retry:
484 if (is_register)
485 gup_flags |= FOLL_SPLIT_PMD;
486 /* Read the page with vaddr into memory */
487 old_page = get_user_page_vma_remote(mm, vaddr, gup_flags, &vma);
488 if (IS_ERR_OR_NULL(old_page))
489 return old_page ? PTR_ERR(old_page) : 0;
490
491 ret = verify_opcode(old_page, vaddr, &opcode);
492 if (ret <= 0)
493 goto put_old;
494
495 if (is_zero_page(old_page)) {
496 ret = -EINVAL;
497 goto put_old;
498 }
499
500 if (WARN(!is_register && PageCompound(old_page),
501 "uprobe unregister should never work on compound page\n")) {
502 ret = -EINVAL;
503 goto put_old;
504 }
505
506 /* We are going to replace instruction, update ref_ctr. */
507 if (!ref_ctr_updated && uprobe->ref_ctr_offset) {
508 ret = update_ref_ctr(uprobe, mm, is_register ? 1 : -1);
509 if (ret)
510 goto put_old;
511
512 ref_ctr_updated = 1;
513 }
514
515 ret = 0;
516 if (!is_register && !PageAnon(old_page))
517 goto put_old;
518
519 ret = anon_vma_prepare(vma);
520 if (ret)
521 goto put_old;
522
523 ret = -ENOMEM;
524 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vaddr);
525 if (!new_page)
526 goto put_old;
527
528 __SetPageUptodate(new_page);
529 copy_highpage(new_page, old_page);
530 copy_to_page(new_page, vaddr, &opcode, UPROBE_SWBP_INSN_SIZE);
531
532 if (!is_register) {
533 struct page *orig_page;
534 pgoff_t index;
535
536 VM_BUG_ON_PAGE(!PageAnon(old_page), old_page);
537
538 index = vaddr_to_offset(vma, vaddr & PAGE_MASK) >> PAGE_SHIFT;
539 orig_page = find_get_page(vma->vm_file->f_inode->i_mapping,
540 index);
541
542 if (orig_page) {
543 if (PageUptodate(orig_page) &&
544 pages_identical(new_page, orig_page)) {
545 /* let go new_page */
546 put_page(new_page);
547 new_page = NULL;
548
549 if (PageCompound(orig_page))
550 orig_page_huge = true;
551 }
552 put_page(orig_page);
553 }
554 }
555
556 ret = __replace_page(vma, vaddr, old_page, new_page);
557 if (new_page)
558 put_page(new_page);
559 put_old:
560 put_page(old_page);
561
562 if (unlikely(ret == -EAGAIN))
563 goto retry;
564
565 /* Revert back reference counter if instruction update failed. */
566 if (ret && is_register && ref_ctr_updated)
567 update_ref_ctr(uprobe, mm, -1);
568
569 /* try collapse pmd for compound page */
570 if (!ret && orig_page_huge)
571 collapse_pte_mapped_thp(mm, vaddr, false);
572
573 return ret;
574 }
575
576 /**
577 * set_swbp - store breakpoint at a given address.
578 * @auprobe: arch specific probepoint information.
579 * @mm: the probed process address space.
580 * @vaddr: the virtual address to insert the opcode.
581 *
582 * For mm @mm, store the breakpoint instruction at @vaddr.
583 * Return 0 (success) or a negative errno.
584 */
set_swbp(struct arch_uprobe * auprobe,struct mm_struct * mm,unsigned long vaddr)585 int __weak set_swbp(struct arch_uprobe *auprobe, struct mm_struct *mm, unsigned long vaddr)
586 {
587 return uprobe_write_opcode(auprobe, mm, vaddr, UPROBE_SWBP_INSN);
588 }
589
590 /**
591 * set_orig_insn - Restore the original instruction.
592 * @mm: the probed process address space.
593 * @auprobe: arch specific probepoint information.
594 * @vaddr: the virtual address to insert the opcode.
595 *
596 * For mm @mm, restore the original opcode (opcode) at @vaddr.
597 * Return 0 (success) or a negative errno.
598 */
599 int __weak
set_orig_insn(struct arch_uprobe * auprobe,struct mm_struct * mm,unsigned long vaddr)600 set_orig_insn(struct arch_uprobe *auprobe, struct mm_struct *mm, unsigned long vaddr)
601 {
602 return uprobe_write_opcode(auprobe, mm, vaddr,
603 *(uprobe_opcode_t *)&auprobe->insn);
604 }
605
get_uprobe(struct uprobe * uprobe)606 static struct uprobe *get_uprobe(struct uprobe *uprobe)
607 {
608 refcount_inc(&uprobe->ref);
609 return uprobe;
610 }
611
put_uprobe(struct uprobe * uprobe)612 static void put_uprobe(struct uprobe *uprobe)
613 {
614 if (refcount_dec_and_test(&uprobe->ref)) {
615 /*
616 * If application munmap(exec_vma) before uprobe_unregister()
617 * gets called, we don't get a chance to remove uprobe from
618 * delayed_uprobe_list from remove_breakpoint(). Do it here.
619 */
620 mutex_lock(&delayed_uprobe_lock);
621 delayed_uprobe_remove(uprobe, NULL);
622 mutex_unlock(&delayed_uprobe_lock);
623 kfree(uprobe);
624 }
625 }
626
627 static __always_inline
uprobe_cmp(const struct inode * l_inode,const loff_t l_offset,const struct uprobe * r)628 int uprobe_cmp(const struct inode *l_inode, const loff_t l_offset,
629 const struct uprobe *r)
630 {
631 if (l_inode < r->inode)
632 return -1;
633
634 if (l_inode > r->inode)
635 return 1;
636
637 if (l_offset < r->offset)
638 return -1;
639
640 if (l_offset > r->offset)
641 return 1;
642
643 return 0;
644 }
645
646 #define __node_2_uprobe(node) \
647 rb_entry((node), struct uprobe, rb_node)
648
649 struct __uprobe_key {
650 struct inode *inode;
651 loff_t offset;
652 };
653
__uprobe_cmp_key(const void * key,const struct rb_node * b)654 static inline int __uprobe_cmp_key(const void *key, const struct rb_node *b)
655 {
656 const struct __uprobe_key *a = key;
657 return uprobe_cmp(a->inode, a->offset, __node_2_uprobe(b));
658 }
659
__uprobe_cmp(struct rb_node * a,const struct rb_node * b)660 static inline int __uprobe_cmp(struct rb_node *a, const struct rb_node *b)
661 {
662 struct uprobe *u = __node_2_uprobe(a);
663 return uprobe_cmp(u->inode, u->offset, __node_2_uprobe(b));
664 }
665
__find_uprobe(struct inode * inode,loff_t offset)666 static struct uprobe *__find_uprobe(struct inode *inode, loff_t offset)
667 {
668 struct __uprobe_key key = {
669 .inode = inode,
670 .offset = offset,
671 };
672 struct rb_node *node = rb_find(&key, &uprobes_tree, __uprobe_cmp_key);
673
674 if (node)
675 return get_uprobe(__node_2_uprobe(node));
676
677 return NULL;
678 }
679
680 /*
681 * Find a uprobe corresponding to a given inode:offset
682 * Acquires uprobes_treelock
683 */
find_uprobe(struct inode * inode,loff_t offset)684 static struct uprobe *find_uprobe(struct inode *inode, loff_t offset)
685 {
686 struct uprobe *uprobe;
687
688 spin_lock(&uprobes_treelock);
689 uprobe = __find_uprobe(inode, offset);
690 spin_unlock(&uprobes_treelock);
691
692 return uprobe;
693 }
694
__insert_uprobe(struct uprobe * uprobe)695 static struct uprobe *__insert_uprobe(struct uprobe *uprobe)
696 {
697 struct rb_node *node;
698
699 node = rb_find_add(&uprobe->rb_node, &uprobes_tree, __uprobe_cmp);
700 if (node)
701 return get_uprobe(__node_2_uprobe(node));
702
703 /* get access + creation ref */
704 refcount_set(&uprobe->ref, 2);
705 return NULL;
706 }
707
708 /*
709 * Acquire uprobes_treelock.
710 * Matching uprobe already exists in rbtree;
711 * increment (access refcount) and return the matching uprobe.
712 *
713 * No matching uprobe; insert the uprobe in rb_tree;
714 * get a double refcount (access + creation) and return NULL.
715 */
insert_uprobe(struct uprobe * uprobe)716 static struct uprobe *insert_uprobe(struct uprobe *uprobe)
717 {
718 struct uprobe *u;
719
720 spin_lock(&uprobes_treelock);
721 u = __insert_uprobe(uprobe);
722 spin_unlock(&uprobes_treelock);
723
724 return u;
725 }
726
727 static void
ref_ctr_mismatch_warn(struct uprobe * cur_uprobe,struct uprobe * uprobe)728 ref_ctr_mismatch_warn(struct uprobe *cur_uprobe, struct uprobe *uprobe)
729 {
730 pr_warn("ref_ctr_offset mismatch. inode: 0x%lx offset: 0x%llx "
731 "ref_ctr_offset(old): 0x%llx ref_ctr_offset(new): 0x%llx\n",
732 uprobe->inode->i_ino, (unsigned long long) uprobe->offset,
733 (unsigned long long) cur_uprobe->ref_ctr_offset,
734 (unsigned long long) uprobe->ref_ctr_offset);
735 }
736
alloc_uprobe(struct inode * inode,loff_t offset,loff_t ref_ctr_offset)737 static struct uprobe *alloc_uprobe(struct inode *inode, loff_t offset,
738 loff_t ref_ctr_offset)
739 {
740 struct uprobe *uprobe, *cur_uprobe;
741
742 uprobe = kzalloc(sizeof(struct uprobe), GFP_KERNEL);
743 if (!uprobe)
744 return NULL;
745
746 uprobe->inode = inode;
747 uprobe->offset = offset;
748 uprobe->ref_ctr_offset = ref_ctr_offset;
749 init_rwsem(&uprobe->register_rwsem);
750 init_rwsem(&uprobe->consumer_rwsem);
751
752 /* add to uprobes_tree, sorted on inode:offset */
753 cur_uprobe = insert_uprobe(uprobe);
754 /* a uprobe exists for this inode:offset combination */
755 if (cur_uprobe) {
756 if (cur_uprobe->ref_ctr_offset != uprobe->ref_ctr_offset) {
757 ref_ctr_mismatch_warn(cur_uprobe, uprobe);
758 put_uprobe(cur_uprobe);
759 kfree(uprobe);
760 return ERR_PTR(-EINVAL);
761 }
762 kfree(uprobe);
763 uprobe = cur_uprobe;
764 }
765
766 return uprobe;
767 }
768
consumer_add(struct uprobe * uprobe,struct uprobe_consumer * uc)769 static void consumer_add(struct uprobe *uprobe, struct uprobe_consumer *uc)
770 {
771 down_write(&uprobe->consumer_rwsem);
772 uc->next = uprobe->consumers;
773 uprobe->consumers = uc;
774 up_write(&uprobe->consumer_rwsem);
775 }
776
777 /*
778 * For uprobe @uprobe, delete the consumer @uc.
779 * Return true if the @uc is deleted successfully
780 * or return false.
781 */
consumer_del(struct uprobe * uprobe,struct uprobe_consumer * uc)782 static bool consumer_del(struct uprobe *uprobe, struct uprobe_consumer *uc)
783 {
784 struct uprobe_consumer **con;
785 bool ret = false;
786
787 down_write(&uprobe->consumer_rwsem);
788 for (con = &uprobe->consumers; *con; con = &(*con)->next) {
789 if (*con == uc) {
790 *con = uc->next;
791 ret = true;
792 break;
793 }
794 }
795 up_write(&uprobe->consumer_rwsem);
796
797 return ret;
798 }
799
__copy_insn(struct address_space * mapping,struct file * filp,void * insn,int nbytes,loff_t offset)800 static int __copy_insn(struct address_space *mapping, struct file *filp,
801 void *insn, int nbytes, loff_t offset)
802 {
803 struct page *page;
804 /*
805 * Ensure that the page that has the original instruction is populated
806 * and in page-cache. If ->read_folio == NULL it must be shmem_mapping(),
807 * see uprobe_register().
808 */
809 if (mapping->a_ops->read_folio)
810 page = read_mapping_page(mapping, offset >> PAGE_SHIFT, filp);
811 else
812 page = shmem_read_mapping_page(mapping, offset >> PAGE_SHIFT);
813 if (IS_ERR(page))
814 return PTR_ERR(page);
815
816 copy_from_page(page, offset, insn, nbytes);
817 put_page(page);
818
819 return 0;
820 }
821
copy_insn(struct uprobe * uprobe,struct file * filp)822 static int copy_insn(struct uprobe *uprobe, struct file *filp)
823 {
824 struct address_space *mapping = uprobe->inode->i_mapping;
825 loff_t offs = uprobe->offset;
826 void *insn = &uprobe->arch.insn;
827 int size = sizeof(uprobe->arch.insn);
828 int len, err = -EIO;
829
830 /* Copy only available bytes, -EIO if nothing was read */
831 do {
832 if (offs >= i_size_read(uprobe->inode))
833 break;
834
835 len = min_t(int, size, PAGE_SIZE - (offs & ~PAGE_MASK));
836 err = __copy_insn(mapping, filp, insn, len, offs);
837 if (err)
838 break;
839
840 insn += len;
841 offs += len;
842 size -= len;
843 } while (size);
844
845 return err;
846 }
847
prepare_uprobe(struct uprobe * uprobe,struct file * file,struct mm_struct * mm,unsigned long vaddr)848 static int prepare_uprobe(struct uprobe *uprobe, struct file *file,
849 struct mm_struct *mm, unsigned long vaddr)
850 {
851 int ret = 0;
852
853 if (test_bit(UPROBE_COPY_INSN, &uprobe->flags))
854 return ret;
855
856 /* TODO: move this into _register, until then we abuse this sem. */
857 down_write(&uprobe->consumer_rwsem);
858 if (test_bit(UPROBE_COPY_INSN, &uprobe->flags))
859 goto out;
860
861 ret = copy_insn(uprobe, file);
862 if (ret)
863 goto out;
864
865 ret = -ENOTSUPP;
866 if (is_trap_insn((uprobe_opcode_t *)&uprobe->arch.insn))
867 goto out;
868
869 ret = arch_uprobe_analyze_insn(&uprobe->arch, mm, vaddr);
870 if (ret)
871 goto out;
872
873 smp_wmb(); /* pairs with the smp_rmb() in handle_swbp() */
874 set_bit(UPROBE_COPY_INSN, &uprobe->flags);
875
876 out:
877 up_write(&uprobe->consumer_rwsem);
878
879 return ret;
880 }
881
consumer_filter(struct uprobe_consumer * uc,enum uprobe_filter_ctx ctx,struct mm_struct * mm)882 static inline bool consumer_filter(struct uprobe_consumer *uc,
883 enum uprobe_filter_ctx ctx, struct mm_struct *mm)
884 {
885 return !uc->filter || uc->filter(uc, ctx, mm);
886 }
887
filter_chain(struct uprobe * uprobe,enum uprobe_filter_ctx ctx,struct mm_struct * mm)888 static bool filter_chain(struct uprobe *uprobe,
889 enum uprobe_filter_ctx ctx, struct mm_struct *mm)
890 {
891 struct uprobe_consumer *uc;
892 bool ret = false;
893
894 down_read(&uprobe->consumer_rwsem);
895 for (uc = uprobe->consumers; uc; uc = uc->next) {
896 ret = consumer_filter(uc, ctx, mm);
897 if (ret)
898 break;
899 }
900 up_read(&uprobe->consumer_rwsem);
901
902 return ret;
903 }
904
905 static int
install_breakpoint(struct uprobe * uprobe,struct mm_struct * mm,struct vm_area_struct * vma,unsigned long vaddr)906 install_breakpoint(struct uprobe *uprobe, struct mm_struct *mm,
907 struct vm_area_struct *vma, unsigned long vaddr)
908 {
909 bool first_uprobe;
910 int ret;
911
912 ret = prepare_uprobe(uprobe, vma->vm_file, mm, vaddr);
913 if (ret)
914 return ret;
915
916 /*
917 * set MMF_HAS_UPROBES in advance for uprobe_pre_sstep_notifier(),
918 * the task can hit this breakpoint right after __replace_page().
919 */
920 first_uprobe = !test_bit(MMF_HAS_UPROBES, &mm->flags);
921 if (first_uprobe)
922 set_bit(MMF_HAS_UPROBES, &mm->flags);
923
924 ret = set_swbp(&uprobe->arch, mm, vaddr);
925 if (!ret)
926 clear_bit(MMF_RECALC_UPROBES, &mm->flags);
927 else if (first_uprobe)
928 clear_bit(MMF_HAS_UPROBES, &mm->flags);
929
930 return ret;
931 }
932
933 static int
remove_breakpoint(struct uprobe * uprobe,struct mm_struct * mm,unsigned long vaddr)934 remove_breakpoint(struct uprobe *uprobe, struct mm_struct *mm, unsigned long vaddr)
935 {
936 set_bit(MMF_RECALC_UPROBES, &mm->flags);
937 return set_orig_insn(&uprobe->arch, mm, vaddr);
938 }
939
uprobe_is_active(struct uprobe * uprobe)940 static inline bool uprobe_is_active(struct uprobe *uprobe)
941 {
942 return !RB_EMPTY_NODE(&uprobe->rb_node);
943 }
944 /*
945 * There could be threads that have already hit the breakpoint. They
946 * will recheck the current insn and restart if find_uprobe() fails.
947 * See find_active_uprobe().
948 */
delete_uprobe(struct uprobe * uprobe)949 static void delete_uprobe(struct uprobe *uprobe)
950 {
951 if (WARN_ON(!uprobe_is_active(uprobe)))
952 return;
953
954 spin_lock(&uprobes_treelock);
955 rb_erase(&uprobe->rb_node, &uprobes_tree);
956 spin_unlock(&uprobes_treelock);
957 RB_CLEAR_NODE(&uprobe->rb_node); /* for uprobe_is_active() */
958 put_uprobe(uprobe);
959 }
960
961 struct map_info {
962 struct map_info *next;
963 struct mm_struct *mm;
964 unsigned long vaddr;
965 };
966
free_map_info(struct map_info * info)967 static inline struct map_info *free_map_info(struct map_info *info)
968 {
969 struct map_info *next = info->next;
970 kfree(info);
971 return next;
972 }
973
974 static struct map_info *
build_map_info(struct address_space * mapping,loff_t offset,bool is_register)975 build_map_info(struct address_space *mapping, loff_t offset, bool is_register)
976 {
977 unsigned long pgoff = offset >> PAGE_SHIFT;
978 struct vm_area_struct *vma;
979 struct map_info *curr = NULL;
980 struct map_info *prev = NULL;
981 struct map_info *info;
982 int more = 0;
983
984 again:
985 i_mmap_lock_read(mapping);
986 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
987 if (!valid_vma(vma, is_register))
988 continue;
989
990 if (!prev && !more) {
991 /*
992 * Needs GFP_NOWAIT to avoid i_mmap_rwsem recursion through
993 * reclaim. This is optimistic, no harm done if it fails.
994 */
995 prev = kmalloc(sizeof(struct map_info),
996 GFP_NOWAIT | __GFP_NOMEMALLOC | __GFP_NOWARN);
997 if (prev)
998 prev->next = NULL;
999 }
1000 if (!prev) {
1001 more++;
1002 continue;
1003 }
1004
1005 if (!mmget_not_zero(vma->vm_mm))
1006 continue;
1007
1008 info = prev;
1009 prev = prev->next;
1010 info->next = curr;
1011 curr = info;
1012
1013 info->mm = vma->vm_mm;
1014 info->vaddr = offset_to_vaddr(vma, offset);
1015 }
1016 i_mmap_unlock_read(mapping);
1017
1018 if (!more)
1019 goto out;
1020
1021 prev = curr;
1022 while (curr) {
1023 mmput(curr->mm);
1024 curr = curr->next;
1025 }
1026
1027 do {
1028 info = kmalloc(sizeof(struct map_info), GFP_KERNEL);
1029 if (!info) {
1030 curr = ERR_PTR(-ENOMEM);
1031 goto out;
1032 }
1033 info->next = prev;
1034 prev = info;
1035 } while (--more);
1036
1037 goto again;
1038 out:
1039 while (prev)
1040 prev = free_map_info(prev);
1041 return curr;
1042 }
1043
1044 static int
register_for_each_vma(struct uprobe * uprobe,struct uprobe_consumer * new)1045 register_for_each_vma(struct uprobe *uprobe, struct uprobe_consumer *new)
1046 {
1047 bool is_register = !!new;
1048 struct map_info *info;
1049 int err = 0;
1050
1051 percpu_down_write(&dup_mmap_sem);
1052 info = build_map_info(uprobe->inode->i_mapping,
1053 uprobe->offset, is_register);
1054 if (IS_ERR(info)) {
1055 err = PTR_ERR(info);
1056 goto out;
1057 }
1058
1059 while (info) {
1060 struct mm_struct *mm = info->mm;
1061 struct vm_area_struct *vma;
1062
1063 if (err && is_register)
1064 goto free;
1065
1066 mmap_write_lock(mm);
1067 vma = find_vma(mm, info->vaddr);
1068 if (!vma || !valid_vma(vma, is_register) ||
1069 file_inode(vma->vm_file) != uprobe->inode)
1070 goto unlock;
1071
1072 if (vma->vm_start > info->vaddr ||
1073 vaddr_to_offset(vma, info->vaddr) != uprobe->offset)
1074 goto unlock;
1075
1076 if (is_register) {
1077 /* consult only the "caller", new consumer. */
1078 if (consumer_filter(new,
1079 UPROBE_FILTER_REGISTER, mm))
1080 err = install_breakpoint(uprobe, mm, vma, info->vaddr);
1081 } else if (test_bit(MMF_HAS_UPROBES, &mm->flags)) {
1082 if (!filter_chain(uprobe,
1083 UPROBE_FILTER_UNREGISTER, mm))
1084 err |= remove_breakpoint(uprobe, mm, info->vaddr);
1085 }
1086
1087 unlock:
1088 mmap_write_unlock(mm);
1089 free:
1090 mmput(mm);
1091 info = free_map_info(info);
1092 }
1093 out:
1094 percpu_up_write(&dup_mmap_sem);
1095 return err;
1096 }
1097
1098 static void
__uprobe_unregister(struct uprobe * uprobe,struct uprobe_consumer * uc)1099 __uprobe_unregister(struct uprobe *uprobe, struct uprobe_consumer *uc)
1100 {
1101 int err;
1102
1103 if (WARN_ON(!consumer_del(uprobe, uc)))
1104 return;
1105
1106 err = register_for_each_vma(uprobe, NULL);
1107 /* TODO : cant unregister? schedule a worker thread */
1108 if (!uprobe->consumers && !err)
1109 delete_uprobe(uprobe);
1110 }
1111
1112 /*
1113 * uprobe_unregister - unregister an already registered probe.
1114 * @inode: the file in which the probe has to be removed.
1115 * @offset: offset from the start of the file.
1116 * @uc: identify which probe if multiple probes are colocated.
1117 */
uprobe_unregister(struct inode * inode,loff_t offset,struct uprobe_consumer * uc)1118 void uprobe_unregister(struct inode *inode, loff_t offset, struct uprobe_consumer *uc)
1119 {
1120 struct uprobe *uprobe;
1121
1122 uprobe = find_uprobe(inode, offset);
1123 if (WARN_ON(!uprobe))
1124 return;
1125
1126 down_write(&uprobe->register_rwsem);
1127 __uprobe_unregister(uprobe, uc);
1128 up_write(&uprobe->register_rwsem);
1129 put_uprobe(uprobe);
1130 }
1131 EXPORT_SYMBOL_GPL(uprobe_unregister);
1132
1133 /*
1134 * __uprobe_register - register a probe
1135 * @inode: the file in which the probe has to be placed.
1136 * @offset: offset from the start of the file.
1137 * @uc: information on howto handle the probe..
1138 *
1139 * Apart from the access refcount, __uprobe_register() takes a creation
1140 * refcount (thro alloc_uprobe) if and only if this @uprobe is getting
1141 * inserted into the rbtree (i.e first consumer for a @inode:@offset
1142 * tuple). Creation refcount stops uprobe_unregister from freeing the
1143 * @uprobe even before the register operation is complete. Creation
1144 * refcount is released when the last @uc for the @uprobe
1145 * unregisters. Caller of __uprobe_register() is required to keep @inode
1146 * (and the containing mount) referenced.
1147 *
1148 * Return errno if it cannot successully install probes
1149 * else return 0 (success)
1150 */
__uprobe_register(struct inode * inode,loff_t offset,loff_t ref_ctr_offset,struct uprobe_consumer * uc)1151 static int __uprobe_register(struct inode *inode, loff_t offset,
1152 loff_t ref_ctr_offset, struct uprobe_consumer *uc)
1153 {
1154 struct uprobe *uprobe;
1155 int ret;
1156
1157 /* Uprobe must have at least one set consumer */
1158 if (!uc->handler && !uc->ret_handler)
1159 return -EINVAL;
1160
1161 /* copy_insn() uses read_mapping_page() or shmem_read_mapping_page() */
1162 if (!inode->i_mapping->a_ops->read_folio &&
1163 !shmem_mapping(inode->i_mapping))
1164 return -EIO;
1165 /* Racy, just to catch the obvious mistakes */
1166 if (offset > i_size_read(inode))
1167 return -EINVAL;
1168
1169 /*
1170 * This ensures that copy_from_page(), copy_to_page() and
1171 * __update_ref_ctr() can't cross page boundary.
1172 */
1173 if (!IS_ALIGNED(offset, UPROBE_SWBP_INSN_SIZE))
1174 return -EINVAL;
1175 if (!IS_ALIGNED(ref_ctr_offset, sizeof(short)))
1176 return -EINVAL;
1177
1178 retry:
1179 uprobe = alloc_uprobe(inode, offset, ref_ctr_offset);
1180 if (!uprobe)
1181 return -ENOMEM;
1182 if (IS_ERR(uprobe))
1183 return PTR_ERR(uprobe);
1184
1185 /*
1186 * We can race with uprobe_unregister()->delete_uprobe().
1187 * Check uprobe_is_active() and retry if it is false.
1188 */
1189 down_write(&uprobe->register_rwsem);
1190 ret = -EAGAIN;
1191 if (likely(uprobe_is_active(uprobe))) {
1192 consumer_add(uprobe, uc);
1193 ret = register_for_each_vma(uprobe, uc);
1194 if (ret)
1195 __uprobe_unregister(uprobe, uc);
1196 }
1197 up_write(&uprobe->register_rwsem);
1198 put_uprobe(uprobe);
1199
1200 if (unlikely(ret == -EAGAIN))
1201 goto retry;
1202 return ret;
1203 }
1204
uprobe_register(struct inode * inode,loff_t offset,struct uprobe_consumer * uc)1205 int uprobe_register(struct inode *inode, loff_t offset,
1206 struct uprobe_consumer *uc)
1207 {
1208 return __uprobe_register(inode, offset, 0, uc);
1209 }
1210 EXPORT_SYMBOL_GPL(uprobe_register);
1211
uprobe_register_refctr(struct inode * inode,loff_t offset,loff_t ref_ctr_offset,struct uprobe_consumer * uc)1212 int uprobe_register_refctr(struct inode *inode, loff_t offset,
1213 loff_t ref_ctr_offset, struct uprobe_consumer *uc)
1214 {
1215 return __uprobe_register(inode, offset, ref_ctr_offset, uc);
1216 }
1217 EXPORT_SYMBOL_GPL(uprobe_register_refctr);
1218
1219 /*
1220 * uprobe_apply - unregister an already registered probe.
1221 * @inode: the file in which the probe has to be removed.
1222 * @offset: offset from the start of the file.
1223 * @uc: consumer which wants to add more or remove some breakpoints
1224 * @add: add or remove the breakpoints
1225 */
uprobe_apply(struct inode * inode,loff_t offset,struct uprobe_consumer * uc,bool add)1226 int uprobe_apply(struct inode *inode, loff_t offset,
1227 struct uprobe_consumer *uc, bool add)
1228 {
1229 struct uprobe *uprobe;
1230 struct uprobe_consumer *con;
1231 int ret = -ENOENT;
1232
1233 uprobe = find_uprobe(inode, offset);
1234 if (WARN_ON(!uprobe))
1235 return ret;
1236
1237 down_write(&uprobe->register_rwsem);
1238 for (con = uprobe->consumers; con && con != uc ; con = con->next)
1239 ;
1240 if (con)
1241 ret = register_for_each_vma(uprobe, add ? uc : NULL);
1242 up_write(&uprobe->register_rwsem);
1243 put_uprobe(uprobe);
1244
1245 return ret;
1246 }
1247
unapply_uprobe(struct uprobe * uprobe,struct mm_struct * mm)1248 static int unapply_uprobe(struct uprobe *uprobe, struct mm_struct *mm)
1249 {
1250 VMA_ITERATOR(vmi, mm, 0);
1251 struct vm_area_struct *vma;
1252 int err = 0;
1253
1254 mmap_read_lock(mm);
1255 for_each_vma(vmi, vma) {
1256 unsigned long vaddr;
1257 loff_t offset;
1258
1259 if (!valid_vma(vma, false) ||
1260 file_inode(vma->vm_file) != uprobe->inode)
1261 continue;
1262
1263 offset = (loff_t)vma->vm_pgoff << PAGE_SHIFT;
1264 if (uprobe->offset < offset ||
1265 uprobe->offset >= offset + vma->vm_end - vma->vm_start)
1266 continue;
1267
1268 vaddr = offset_to_vaddr(vma, uprobe->offset);
1269 err |= remove_breakpoint(uprobe, mm, vaddr);
1270 }
1271 mmap_read_unlock(mm);
1272
1273 return err;
1274 }
1275
1276 static struct rb_node *
find_node_in_range(struct inode * inode,loff_t min,loff_t max)1277 find_node_in_range(struct inode *inode, loff_t min, loff_t max)
1278 {
1279 struct rb_node *n = uprobes_tree.rb_node;
1280
1281 while (n) {
1282 struct uprobe *u = rb_entry(n, struct uprobe, rb_node);
1283
1284 if (inode < u->inode) {
1285 n = n->rb_left;
1286 } else if (inode > u->inode) {
1287 n = n->rb_right;
1288 } else {
1289 if (max < u->offset)
1290 n = n->rb_left;
1291 else if (min > u->offset)
1292 n = n->rb_right;
1293 else
1294 break;
1295 }
1296 }
1297
1298 return n;
1299 }
1300
1301 /*
1302 * For a given range in vma, build a list of probes that need to be inserted.
1303 */
build_probe_list(struct inode * inode,struct vm_area_struct * vma,unsigned long start,unsigned long end,struct list_head * head)1304 static void build_probe_list(struct inode *inode,
1305 struct vm_area_struct *vma,
1306 unsigned long start, unsigned long end,
1307 struct list_head *head)
1308 {
1309 loff_t min, max;
1310 struct rb_node *n, *t;
1311 struct uprobe *u;
1312
1313 INIT_LIST_HEAD(head);
1314 min = vaddr_to_offset(vma, start);
1315 max = min + (end - start) - 1;
1316
1317 spin_lock(&uprobes_treelock);
1318 n = find_node_in_range(inode, min, max);
1319 if (n) {
1320 for (t = n; t; t = rb_prev(t)) {
1321 u = rb_entry(t, struct uprobe, rb_node);
1322 if (u->inode != inode || u->offset < min)
1323 break;
1324 list_add(&u->pending_list, head);
1325 get_uprobe(u);
1326 }
1327 for (t = n; (t = rb_next(t)); ) {
1328 u = rb_entry(t, struct uprobe, rb_node);
1329 if (u->inode != inode || u->offset > max)
1330 break;
1331 list_add(&u->pending_list, head);
1332 get_uprobe(u);
1333 }
1334 }
1335 spin_unlock(&uprobes_treelock);
1336 }
1337
1338 /* @vma contains reference counter, not the probed instruction. */
delayed_ref_ctr_inc(struct vm_area_struct * vma)1339 static int delayed_ref_ctr_inc(struct vm_area_struct *vma)
1340 {
1341 struct list_head *pos, *q;
1342 struct delayed_uprobe *du;
1343 unsigned long vaddr;
1344 int ret = 0, err = 0;
1345
1346 mutex_lock(&delayed_uprobe_lock);
1347 list_for_each_safe(pos, q, &delayed_uprobe_list) {
1348 du = list_entry(pos, struct delayed_uprobe, list);
1349
1350 if (du->mm != vma->vm_mm ||
1351 !valid_ref_ctr_vma(du->uprobe, vma))
1352 continue;
1353
1354 vaddr = offset_to_vaddr(vma, du->uprobe->ref_ctr_offset);
1355 ret = __update_ref_ctr(vma->vm_mm, vaddr, 1);
1356 if (ret) {
1357 update_ref_ctr_warn(du->uprobe, vma->vm_mm, 1);
1358 if (!err)
1359 err = ret;
1360 }
1361 delayed_uprobe_delete(du);
1362 }
1363 mutex_unlock(&delayed_uprobe_lock);
1364 return err;
1365 }
1366
1367 /*
1368 * Called from mmap_region/vma_merge with mm->mmap_lock acquired.
1369 *
1370 * Currently we ignore all errors and always return 0, the callers
1371 * can't handle the failure anyway.
1372 */
uprobe_mmap(struct vm_area_struct * vma)1373 int uprobe_mmap(struct vm_area_struct *vma)
1374 {
1375 struct list_head tmp_list;
1376 struct uprobe *uprobe, *u;
1377 struct inode *inode;
1378
1379 if (no_uprobe_events())
1380 return 0;
1381
1382 if (vma->vm_file &&
1383 (vma->vm_flags & (VM_WRITE|VM_SHARED)) == VM_WRITE &&
1384 test_bit(MMF_HAS_UPROBES, &vma->vm_mm->flags))
1385 delayed_ref_ctr_inc(vma);
1386
1387 if (!valid_vma(vma, true))
1388 return 0;
1389
1390 inode = file_inode(vma->vm_file);
1391 if (!inode)
1392 return 0;
1393
1394 mutex_lock(uprobes_mmap_hash(inode));
1395 build_probe_list(inode, vma, vma->vm_start, vma->vm_end, &tmp_list);
1396 /*
1397 * We can race with uprobe_unregister(), this uprobe can be already
1398 * removed. But in this case filter_chain() must return false, all
1399 * consumers have gone away.
1400 */
1401 list_for_each_entry_safe(uprobe, u, &tmp_list, pending_list) {
1402 if (!fatal_signal_pending(current) &&
1403 filter_chain(uprobe, UPROBE_FILTER_MMAP, vma->vm_mm)) {
1404 unsigned long vaddr = offset_to_vaddr(vma, uprobe->offset);
1405 install_breakpoint(uprobe, vma->vm_mm, vma, vaddr);
1406 }
1407 put_uprobe(uprobe);
1408 }
1409 mutex_unlock(uprobes_mmap_hash(inode));
1410
1411 return 0;
1412 }
1413
1414 static bool
vma_has_uprobes(struct vm_area_struct * vma,unsigned long start,unsigned long end)1415 vma_has_uprobes(struct vm_area_struct *vma, unsigned long start, unsigned long end)
1416 {
1417 loff_t min, max;
1418 struct inode *inode;
1419 struct rb_node *n;
1420
1421 inode = file_inode(vma->vm_file);
1422
1423 min = vaddr_to_offset(vma, start);
1424 max = min + (end - start) - 1;
1425
1426 spin_lock(&uprobes_treelock);
1427 n = find_node_in_range(inode, min, max);
1428 spin_unlock(&uprobes_treelock);
1429
1430 return !!n;
1431 }
1432
1433 /*
1434 * Called in context of a munmap of a vma.
1435 */
uprobe_munmap(struct vm_area_struct * vma,unsigned long start,unsigned long end)1436 void uprobe_munmap(struct vm_area_struct *vma, unsigned long start, unsigned long end)
1437 {
1438 if (no_uprobe_events() || !valid_vma(vma, false))
1439 return;
1440
1441 if (!atomic_read(&vma->vm_mm->mm_users)) /* called by mmput() ? */
1442 return;
1443
1444 if (!test_bit(MMF_HAS_UPROBES, &vma->vm_mm->flags) ||
1445 test_bit(MMF_RECALC_UPROBES, &vma->vm_mm->flags))
1446 return;
1447
1448 if (vma_has_uprobes(vma, start, end))
1449 set_bit(MMF_RECALC_UPROBES, &vma->vm_mm->flags);
1450 }
1451
1452 /* Slot allocation for XOL */
xol_add_vma(struct mm_struct * mm,struct xol_area * area)1453 static int xol_add_vma(struct mm_struct *mm, struct xol_area *area)
1454 {
1455 struct vm_area_struct *vma;
1456 int ret;
1457
1458 if (mmap_write_lock_killable(mm))
1459 return -EINTR;
1460
1461 if (mm->uprobes_state.xol_area) {
1462 ret = -EALREADY;
1463 goto fail;
1464 }
1465
1466 if (!area->vaddr) {
1467 /* Try to map as high as possible, this is only a hint. */
1468 area->vaddr = get_unmapped_area(NULL, TASK_SIZE - PAGE_SIZE,
1469 PAGE_SIZE, 0, 0);
1470 if (IS_ERR_VALUE(area->vaddr)) {
1471 ret = area->vaddr;
1472 goto fail;
1473 }
1474 }
1475
1476 vma = _install_special_mapping(mm, area->vaddr, PAGE_SIZE,
1477 VM_EXEC|VM_MAYEXEC|VM_DONTCOPY|VM_IO,
1478 &area->xol_mapping);
1479 if (IS_ERR(vma)) {
1480 ret = PTR_ERR(vma);
1481 goto fail;
1482 }
1483
1484 ret = 0;
1485 /* pairs with get_xol_area() */
1486 smp_store_release(&mm->uprobes_state.xol_area, area); /* ^^^ */
1487 fail:
1488 mmap_write_unlock(mm);
1489
1490 return ret;
1491 }
1492
__create_xol_area(unsigned long vaddr)1493 static struct xol_area *__create_xol_area(unsigned long vaddr)
1494 {
1495 struct mm_struct *mm = current->mm;
1496 uprobe_opcode_t insn = UPROBE_SWBP_INSN;
1497 struct xol_area *area;
1498
1499 area = kzalloc(sizeof(*area), GFP_KERNEL);
1500 if (unlikely(!area))
1501 goto out;
1502
1503 area->bitmap = kcalloc(BITS_TO_LONGS(UINSNS_PER_PAGE), sizeof(long),
1504 GFP_KERNEL);
1505 if (!area->bitmap)
1506 goto free_area;
1507
1508 area->xol_mapping.name = "[uprobes]";
1509 area->xol_mapping.pages = area->pages;
1510 area->pages[0] = alloc_page(GFP_HIGHUSER | __GFP_ZERO);
1511 if (!area->pages[0])
1512 goto free_bitmap;
1513 area->pages[1] = NULL;
1514
1515 area->vaddr = vaddr;
1516 init_waitqueue_head(&area->wq);
1517 /* Reserve the 1st slot for get_trampoline_vaddr() */
1518 set_bit(0, area->bitmap);
1519 atomic_set(&area->slot_count, 1);
1520 arch_uprobe_copy_ixol(area->pages[0], 0, &insn, UPROBE_SWBP_INSN_SIZE);
1521
1522 if (!xol_add_vma(mm, area))
1523 return area;
1524
1525 __free_page(area->pages[0]);
1526 free_bitmap:
1527 kfree(area->bitmap);
1528 free_area:
1529 kfree(area);
1530 out:
1531 return NULL;
1532 }
1533
1534 /*
1535 * get_xol_area - Allocate process's xol_area if necessary.
1536 * This area will be used for storing instructions for execution out of line.
1537 *
1538 * Returns the allocated area or NULL.
1539 */
get_xol_area(void)1540 static struct xol_area *get_xol_area(void)
1541 {
1542 struct mm_struct *mm = current->mm;
1543 struct xol_area *area;
1544
1545 if (!mm->uprobes_state.xol_area)
1546 __create_xol_area(0);
1547
1548 /* Pairs with xol_add_vma() smp_store_release() */
1549 area = READ_ONCE(mm->uprobes_state.xol_area); /* ^^^ */
1550 return area;
1551 }
1552
1553 /*
1554 * uprobe_clear_state - Free the area allocated for slots.
1555 */
uprobe_clear_state(struct mm_struct * mm)1556 void uprobe_clear_state(struct mm_struct *mm)
1557 {
1558 struct xol_area *area = mm->uprobes_state.xol_area;
1559
1560 mutex_lock(&delayed_uprobe_lock);
1561 delayed_uprobe_remove(NULL, mm);
1562 mutex_unlock(&delayed_uprobe_lock);
1563
1564 if (!area)
1565 return;
1566
1567 put_page(area->pages[0]);
1568 kfree(area->bitmap);
1569 kfree(area);
1570 }
1571
uprobe_start_dup_mmap(void)1572 void uprobe_start_dup_mmap(void)
1573 {
1574 percpu_down_read(&dup_mmap_sem);
1575 }
1576
uprobe_end_dup_mmap(void)1577 void uprobe_end_dup_mmap(void)
1578 {
1579 percpu_up_read(&dup_mmap_sem);
1580 }
1581
uprobe_dup_mmap(struct mm_struct * oldmm,struct mm_struct * newmm)1582 void uprobe_dup_mmap(struct mm_struct *oldmm, struct mm_struct *newmm)
1583 {
1584 if (test_bit(MMF_HAS_UPROBES, &oldmm->flags)) {
1585 set_bit(MMF_HAS_UPROBES, &newmm->flags);
1586 /* unconditionally, dup_mmap() skips VM_DONTCOPY vmas */
1587 set_bit(MMF_RECALC_UPROBES, &newmm->flags);
1588 }
1589 }
1590
1591 /*
1592 * - search for a free slot.
1593 */
xol_take_insn_slot(struct xol_area * area)1594 static unsigned long xol_take_insn_slot(struct xol_area *area)
1595 {
1596 unsigned long slot_addr;
1597 int slot_nr;
1598
1599 do {
1600 slot_nr = find_first_zero_bit(area->bitmap, UINSNS_PER_PAGE);
1601 if (slot_nr < UINSNS_PER_PAGE) {
1602 if (!test_and_set_bit(slot_nr, area->bitmap))
1603 break;
1604
1605 slot_nr = UINSNS_PER_PAGE;
1606 continue;
1607 }
1608 wait_event(area->wq, (atomic_read(&area->slot_count) < UINSNS_PER_PAGE));
1609 } while (slot_nr >= UINSNS_PER_PAGE);
1610
1611 slot_addr = area->vaddr + (slot_nr * UPROBE_XOL_SLOT_BYTES);
1612 atomic_inc(&area->slot_count);
1613
1614 return slot_addr;
1615 }
1616
1617 /*
1618 * xol_get_insn_slot - allocate a slot for xol.
1619 * Returns the allocated slot address or 0.
1620 */
xol_get_insn_slot(struct uprobe * uprobe)1621 static unsigned long xol_get_insn_slot(struct uprobe *uprobe)
1622 {
1623 struct xol_area *area;
1624 unsigned long xol_vaddr;
1625
1626 area = get_xol_area();
1627 if (!area)
1628 return 0;
1629
1630 xol_vaddr = xol_take_insn_slot(area);
1631 if (unlikely(!xol_vaddr))
1632 return 0;
1633
1634 arch_uprobe_copy_ixol(area->pages[0], xol_vaddr,
1635 &uprobe->arch.ixol, sizeof(uprobe->arch.ixol));
1636
1637 return xol_vaddr;
1638 }
1639
1640 /*
1641 * xol_free_insn_slot - If slot was earlier allocated by
1642 * @xol_get_insn_slot(), make the slot available for
1643 * subsequent requests.
1644 */
xol_free_insn_slot(struct task_struct * tsk)1645 static void xol_free_insn_slot(struct task_struct *tsk)
1646 {
1647 struct xol_area *area;
1648 unsigned long vma_end;
1649 unsigned long slot_addr;
1650
1651 if (!tsk->mm || !tsk->mm->uprobes_state.xol_area || !tsk->utask)
1652 return;
1653
1654 slot_addr = tsk->utask->xol_vaddr;
1655 if (unlikely(!slot_addr))
1656 return;
1657
1658 area = tsk->mm->uprobes_state.xol_area;
1659 vma_end = area->vaddr + PAGE_SIZE;
1660 if (area->vaddr <= slot_addr && slot_addr < vma_end) {
1661 unsigned long offset;
1662 int slot_nr;
1663
1664 offset = slot_addr - area->vaddr;
1665 slot_nr = offset / UPROBE_XOL_SLOT_BYTES;
1666 if (slot_nr >= UINSNS_PER_PAGE)
1667 return;
1668
1669 clear_bit(slot_nr, area->bitmap);
1670 atomic_dec(&area->slot_count);
1671 smp_mb__after_atomic(); /* pairs with prepare_to_wait() */
1672 if (waitqueue_active(&area->wq))
1673 wake_up(&area->wq);
1674
1675 tsk->utask->xol_vaddr = 0;
1676 }
1677 }
1678
arch_uprobe_copy_ixol(struct page * page,unsigned long vaddr,void * src,unsigned long len)1679 void __weak arch_uprobe_copy_ixol(struct page *page, unsigned long vaddr,
1680 void *src, unsigned long len)
1681 {
1682 /* Initialize the slot */
1683 copy_to_page(page, vaddr, src, len);
1684
1685 /*
1686 * We probably need flush_icache_user_page() but it needs vma.
1687 * This should work on most of architectures by default. If
1688 * architecture needs to do something different it can define
1689 * its own version of the function.
1690 */
1691 flush_dcache_page(page);
1692 }
1693
1694 /**
1695 * uprobe_get_swbp_addr - compute address of swbp given post-swbp regs
1696 * @regs: Reflects the saved state of the task after it has hit a breakpoint
1697 * instruction.
1698 * Return the address of the breakpoint instruction.
1699 */
uprobe_get_swbp_addr(struct pt_regs * regs)1700 unsigned long __weak uprobe_get_swbp_addr(struct pt_regs *regs)
1701 {
1702 return instruction_pointer(regs) - UPROBE_SWBP_INSN_SIZE;
1703 }
1704
uprobe_get_trap_addr(struct pt_regs * regs)1705 unsigned long uprobe_get_trap_addr(struct pt_regs *regs)
1706 {
1707 struct uprobe_task *utask = current->utask;
1708
1709 if (unlikely(utask && utask->active_uprobe))
1710 return utask->vaddr;
1711
1712 return instruction_pointer(regs);
1713 }
1714
free_ret_instance(struct return_instance * ri)1715 static struct return_instance *free_ret_instance(struct return_instance *ri)
1716 {
1717 struct return_instance *next = ri->next;
1718 put_uprobe(ri->uprobe);
1719 kfree(ri);
1720 return next;
1721 }
1722
1723 /*
1724 * Called with no locks held.
1725 * Called in context of an exiting or an exec-ing thread.
1726 */
uprobe_free_utask(struct task_struct * t)1727 void uprobe_free_utask(struct task_struct *t)
1728 {
1729 struct uprobe_task *utask = t->utask;
1730 struct return_instance *ri;
1731
1732 if (!utask)
1733 return;
1734
1735 t->utask = NULL;
1736 if (utask->active_uprobe)
1737 put_uprobe(utask->active_uprobe);
1738
1739 ri = utask->return_instances;
1740 while (ri)
1741 ri = free_ret_instance(ri);
1742
1743 xol_free_insn_slot(t);
1744 kfree(utask);
1745 }
1746
1747 /*
1748 * Allocate a uprobe_task object for the task if necessary.
1749 * Called when the thread hits a breakpoint.
1750 *
1751 * Returns:
1752 * - pointer to new uprobe_task on success
1753 * - NULL otherwise
1754 */
get_utask(void)1755 static struct uprobe_task *get_utask(void)
1756 {
1757 if (!current->utask)
1758 current->utask = kzalloc(sizeof(struct uprobe_task), GFP_KERNEL);
1759 return current->utask;
1760 }
1761
dup_utask(struct task_struct * t,struct uprobe_task * o_utask)1762 static int dup_utask(struct task_struct *t, struct uprobe_task *o_utask)
1763 {
1764 struct uprobe_task *n_utask;
1765 struct return_instance **p, *o, *n;
1766
1767 n_utask = kzalloc(sizeof(struct uprobe_task), GFP_KERNEL);
1768 if (!n_utask)
1769 return -ENOMEM;
1770 t->utask = n_utask;
1771
1772 p = &n_utask->return_instances;
1773 for (o = o_utask->return_instances; o; o = o->next) {
1774 n = kmalloc(sizeof(struct return_instance), GFP_KERNEL);
1775 if (!n)
1776 return -ENOMEM;
1777
1778 *n = *o;
1779 get_uprobe(n->uprobe);
1780 n->next = NULL;
1781
1782 *p = n;
1783 p = &n->next;
1784 n_utask->depth++;
1785 }
1786
1787 return 0;
1788 }
1789
uprobe_warn(struct task_struct * t,const char * msg)1790 static void uprobe_warn(struct task_struct *t, const char *msg)
1791 {
1792 pr_warn("uprobe: %s:%d failed to %s\n",
1793 current->comm, current->pid, msg);
1794 }
1795
dup_xol_work(struct callback_head * work)1796 static void dup_xol_work(struct callback_head *work)
1797 {
1798 if (current->flags & PF_EXITING)
1799 return;
1800
1801 if (!__create_xol_area(current->utask->dup_xol_addr) &&
1802 !fatal_signal_pending(current))
1803 uprobe_warn(current, "dup xol area");
1804 }
1805
1806 /*
1807 * Called in context of a new clone/fork from copy_process.
1808 */
uprobe_copy_process(struct task_struct * t,unsigned long flags)1809 void uprobe_copy_process(struct task_struct *t, unsigned long flags)
1810 {
1811 struct uprobe_task *utask = current->utask;
1812 struct mm_struct *mm = current->mm;
1813 struct xol_area *area;
1814
1815 t->utask = NULL;
1816
1817 if (!utask || !utask->return_instances)
1818 return;
1819
1820 if (mm == t->mm && !(flags & CLONE_VFORK))
1821 return;
1822
1823 if (dup_utask(t, utask))
1824 return uprobe_warn(t, "dup ret instances");
1825
1826 /* The task can fork() after dup_xol_work() fails */
1827 area = mm->uprobes_state.xol_area;
1828 if (!area)
1829 return uprobe_warn(t, "dup xol area");
1830
1831 if (mm == t->mm)
1832 return;
1833
1834 t->utask->dup_xol_addr = area->vaddr;
1835 init_task_work(&t->utask->dup_xol_work, dup_xol_work);
1836 task_work_add(t, &t->utask->dup_xol_work, TWA_RESUME);
1837 }
1838
1839 /*
1840 * Current area->vaddr notion assume the trampoline address is always
1841 * equal area->vaddr.
1842 *
1843 * Returns -1 in case the xol_area is not allocated.
1844 */
get_trampoline_vaddr(void)1845 static unsigned long get_trampoline_vaddr(void)
1846 {
1847 struct xol_area *area;
1848 unsigned long trampoline_vaddr = -1;
1849
1850 /* Pairs with xol_add_vma() smp_store_release() */
1851 area = READ_ONCE(current->mm->uprobes_state.xol_area); /* ^^^ */
1852 if (area)
1853 trampoline_vaddr = area->vaddr;
1854
1855 return trampoline_vaddr;
1856 }
1857
cleanup_return_instances(struct uprobe_task * utask,bool chained,struct pt_regs * regs)1858 static void cleanup_return_instances(struct uprobe_task *utask, bool chained,
1859 struct pt_regs *regs)
1860 {
1861 struct return_instance *ri = utask->return_instances;
1862 enum rp_check ctx = chained ? RP_CHECK_CHAIN_CALL : RP_CHECK_CALL;
1863
1864 while (ri && !arch_uretprobe_is_alive(ri, ctx, regs)) {
1865 ri = free_ret_instance(ri);
1866 utask->depth--;
1867 }
1868 utask->return_instances = ri;
1869 }
1870
prepare_uretprobe(struct uprobe * uprobe,struct pt_regs * regs)1871 static void prepare_uretprobe(struct uprobe *uprobe, struct pt_regs *regs)
1872 {
1873 struct return_instance *ri;
1874 struct uprobe_task *utask;
1875 unsigned long orig_ret_vaddr, trampoline_vaddr;
1876 bool chained;
1877
1878 if (!get_xol_area())
1879 return;
1880
1881 utask = get_utask();
1882 if (!utask)
1883 return;
1884
1885 if (utask->depth >= MAX_URETPROBE_DEPTH) {
1886 printk_ratelimited(KERN_INFO "uprobe: omit uretprobe due to"
1887 " nestedness limit pid/tgid=%d/%d\n",
1888 current->pid, current->tgid);
1889 return;
1890 }
1891
1892 ri = kmalloc(sizeof(struct return_instance), GFP_KERNEL);
1893 if (!ri)
1894 return;
1895
1896 trampoline_vaddr = get_trampoline_vaddr();
1897 orig_ret_vaddr = arch_uretprobe_hijack_return_addr(trampoline_vaddr, regs);
1898 if (orig_ret_vaddr == -1)
1899 goto fail;
1900
1901 /* drop the entries invalidated by longjmp() */
1902 chained = (orig_ret_vaddr == trampoline_vaddr);
1903 cleanup_return_instances(utask, chained, regs);
1904
1905 /*
1906 * We don't want to keep trampoline address in stack, rather keep the
1907 * original return address of first caller thru all the consequent
1908 * instances. This also makes breakpoint unwrapping easier.
1909 */
1910 if (chained) {
1911 if (!utask->return_instances) {
1912 /*
1913 * This situation is not possible. Likely we have an
1914 * attack from user-space.
1915 */
1916 uprobe_warn(current, "handle tail call");
1917 goto fail;
1918 }
1919 orig_ret_vaddr = utask->return_instances->orig_ret_vaddr;
1920 }
1921
1922 ri->uprobe = get_uprobe(uprobe);
1923 ri->func = instruction_pointer(regs);
1924 ri->stack = user_stack_pointer(regs);
1925 ri->orig_ret_vaddr = orig_ret_vaddr;
1926 ri->chained = chained;
1927
1928 utask->depth++;
1929 ri->next = utask->return_instances;
1930 utask->return_instances = ri;
1931
1932 return;
1933 fail:
1934 kfree(ri);
1935 }
1936
1937 /* Prepare to single-step probed instruction out of line. */
1938 static int
pre_ssout(struct uprobe * uprobe,struct pt_regs * regs,unsigned long bp_vaddr)1939 pre_ssout(struct uprobe *uprobe, struct pt_regs *regs, unsigned long bp_vaddr)
1940 {
1941 struct uprobe_task *utask;
1942 unsigned long xol_vaddr;
1943 int err;
1944
1945 utask = get_utask();
1946 if (!utask)
1947 return -ENOMEM;
1948
1949 xol_vaddr = xol_get_insn_slot(uprobe);
1950 if (!xol_vaddr)
1951 return -ENOMEM;
1952
1953 utask->xol_vaddr = xol_vaddr;
1954 utask->vaddr = bp_vaddr;
1955
1956 err = arch_uprobe_pre_xol(&uprobe->arch, regs);
1957 if (unlikely(err)) {
1958 xol_free_insn_slot(current);
1959 return err;
1960 }
1961
1962 utask->active_uprobe = uprobe;
1963 utask->state = UTASK_SSTEP;
1964 return 0;
1965 }
1966
1967 /*
1968 * If we are singlestepping, then ensure this thread is not connected to
1969 * non-fatal signals until completion of singlestep. When xol insn itself
1970 * triggers the signal, restart the original insn even if the task is
1971 * already SIGKILL'ed (since coredump should report the correct ip). This
1972 * is even more important if the task has a handler for SIGSEGV/etc, The
1973 * _same_ instruction should be repeated again after return from the signal
1974 * handler, and SSTEP can never finish in this case.
1975 */
uprobe_deny_signal(void)1976 bool uprobe_deny_signal(void)
1977 {
1978 struct task_struct *t = current;
1979 struct uprobe_task *utask = t->utask;
1980
1981 if (likely(!utask || !utask->active_uprobe))
1982 return false;
1983
1984 WARN_ON_ONCE(utask->state != UTASK_SSTEP);
1985
1986 if (task_sigpending(t)) {
1987 spin_lock_irq(&t->sighand->siglock);
1988 clear_tsk_thread_flag(t, TIF_SIGPENDING);
1989 spin_unlock_irq(&t->sighand->siglock);
1990
1991 if (__fatal_signal_pending(t) || arch_uprobe_xol_was_trapped(t)) {
1992 utask->state = UTASK_SSTEP_TRAPPED;
1993 set_tsk_thread_flag(t, TIF_UPROBE);
1994 }
1995 }
1996
1997 return true;
1998 }
1999
mmf_recalc_uprobes(struct mm_struct * mm)2000 static void mmf_recalc_uprobes(struct mm_struct *mm)
2001 {
2002 VMA_ITERATOR(vmi, mm, 0);
2003 struct vm_area_struct *vma;
2004
2005 for_each_vma(vmi, vma) {
2006 if (!valid_vma(vma, false))
2007 continue;
2008 /*
2009 * This is not strictly accurate, we can race with
2010 * uprobe_unregister() and see the already removed
2011 * uprobe if delete_uprobe() was not yet called.
2012 * Or this uprobe can be filtered out.
2013 */
2014 if (vma_has_uprobes(vma, vma->vm_start, vma->vm_end))
2015 return;
2016 }
2017
2018 clear_bit(MMF_HAS_UPROBES, &mm->flags);
2019 }
2020
is_trap_at_addr(struct mm_struct * mm,unsigned long vaddr)2021 static int is_trap_at_addr(struct mm_struct *mm, unsigned long vaddr)
2022 {
2023 struct page *page;
2024 uprobe_opcode_t opcode;
2025 int result;
2026
2027 if (WARN_ON_ONCE(!IS_ALIGNED(vaddr, UPROBE_SWBP_INSN_SIZE)))
2028 return -EINVAL;
2029
2030 pagefault_disable();
2031 result = __get_user(opcode, (uprobe_opcode_t __user *)vaddr);
2032 pagefault_enable();
2033
2034 if (likely(result == 0))
2035 goto out;
2036
2037 /*
2038 * The NULL 'tsk' here ensures that any faults that occur here
2039 * will not be accounted to the task. 'mm' *is* current->mm,
2040 * but we treat this as a 'remote' access since it is
2041 * essentially a kernel access to the memory.
2042 */
2043 result = get_user_pages_remote(mm, vaddr, 1, FOLL_FORCE, &page, NULL);
2044 if (result < 0)
2045 return result;
2046
2047 copy_from_page(page, vaddr, &opcode, UPROBE_SWBP_INSN_SIZE);
2048 put_page(page);
2049 out:
2050 /* This needs to return true for any variant of the trap insn */
2051 return is_trap_insn(&opcode);
2052 }
2053
find_active_uprobe(unsigned long bp_vaddr,int * is_swbp)2054 static struct uprobe *find_active_uprobe(unsigned long bp_vaddr, int *is_swbp)
2055 {
2056 struct mm_struct *mm = current->mm;
2057 struct uprobe *uprobe = NULL;
2058 struct vm_area_struct *vma;
2059
2060 mmap_read_lock(mm);
2061 vma = vma_lookup(mm, bp_vaddr);
2062 if (vma) {
2063 if (valid_vma(vma, false)) {
2064 struct inode *inode = file_inode(vma->vm_file);
2065 loff_t offset = vaddr_to_offset(vma, bp_vaddr);
2066
2067 uprobe = find_uprobe(inode, offset);
2068 }
2069
2070 if (!uprobe)
2071 *is_swbp = is_trap_at_addr(mm, bp_vaddr);
2072 } else {
2073 *is_swbp = -EFAULT;
2074 }
2075
2076 if (!uprobe && test_and_clear_bit(MMF_RECALC_UPROBES, &mm->flags))
2077 mmf_recalc_uprobes(mm);
2078 mmap_read_unlock(mm);
2079
2080 return uprobe;
2081 }
2082
handler_chain(struct uprobe * uprobe,struct pt_regs * regs)2083 static void handler_chain(struct uprobe *uprobe, struct pt_regs *regs)
2084 {
2085 struct uprobe_consumer *uc;
2086 int remove = UPROBE_HANDLER_REMOVE;
2087 bool need_prep = false; /* prepare return uprobe, when needed */
2088
2089 down_read(&uprobe->register_rwsem);
2090 current->utask->auprobe = &uprobe->arch;
2091 for (uc = uprobe->consumers; uc; uc = uc->next) {
2092 int rc = 0;
2093
2094 if (uc->handler) {
2095 rc = uc->handler(uc, regs);
2096 WARN(rc & ~UPROBE_HANDLER_MASK,
2097 "bad rc=0x%x from %ps()\n", rc, uc->handler);
2098 }
2099
2100 if (uc->ret_handler)
2101 need_prep = true;
2102
2103 remove &= rc;
2104 }
2105 current->utask->auprobe = NULL;
2106
2107 if (need_prep && !remove)
2108 prepare_uretprobe(uprobe, regs); /* put bp at return */
2109
2110 if (remove && uprobe->consumers) {
2111 WARN_ON(!uprobe_is_active(uprobe));
2112 unapply_uprobe(uprobe, current->mm);
2113 }
2114 up_read(&uprobe->register_rwsem);
2115 }
2116
2117 static void
handle_uretprobe_chain(struct return_instance * ri,struct pt_regs * regs)2118 handle_uretprobe_chain(struct return_instance *ri, struct pt_regs *regs)
2119 {
2120 struct uprobe *uprobe = ri->uprobe;
2121 struct uprobe_consumer *uc;
2122
2123 down_read(&uprobe->register_rwsem);
2124 for (uc = uprobe->consumers; uc; uc = uc->next) {
2125 if (uc->ret_handler)
2126 uc->ret_handler(uc, ri->func, regs);
2127 }
2128 up_read(&uprobe->register_rwsem);
2129 }
2130
find_next_ret_chain(struct return_instance * ri)2131 static struct return_instance *find_next_ret_chain(struct return_instance *ri)
2132 {
2133 bool chained;
2134
2135 do {
2136 chained = ri->chained;
2137 ri = ri->next; /* can't be NULL if chained */
2138 } while (chained);
2139
2140 return ri;
2141 }
2142
handle_trampoline(struct pt_regs * regs)2143 static void handle_trampoline(struct pt_regs *regs)
2144 {
2145 struct uprobe_task *utask;
2146 struct return_instance *ri, *next;
2147 bool valid;
2148
2149 utask = current->utask;
2150 if (!utask)
2151 goto sigill;
2152
2153 ri = utask->return_instances;
2154 if (!ri)
2155 goto sigill;
2156
2157 do {
2158 /*
2159 * We should throw out the frames invalidated by longjmp().
2160 * If this chain is valid, then the next one should be alive
2161 * or NULL; the latter case means that nobody but ri->func
2162 * could hit this trampoline on return. TODO: sigaltstack().
2163 */
2164 next = find_next_ret_chain(ri);
2165 valid = !next || arch_uretprobe_is_alive(next, RP_CHECK_RET, regs);
2166
2167 instruction_pointer_set(regs, ri->orig_ret_vaddr);
2168 do {
2169 if (valid)
2170 handle_uretprobe_chain(ri, regs);
2171 ri = free_ret_instance(ri);
2172 utask->depth--;
2173 } while (ri != next);
2174 } while (!valid);
2175
2176 utask->return_instances = ri;
2177 return;
2178
2179 sigill:
2180 uprobe_warn(current, "handle uretprobe, sending SIGILL.");
2181 force_sig(SIGILL);
2182
2183 }
2184
arch_uprobe_ignore(struct arch_uprobe * aup,struct pt_regs * regs)2185 bool __weak arch_uprobe_ignore(struct arch_uprobe *aup, struct pt_regs *regs)
2186 {
2187 return false;
2188 }
2189
arch_uretprobe_is_alive(struct return_instance * ret,enum rp_check ctx,struct pt_regs * regs)2190 bool __weak arch_uretprobe_is_alive(struct return_instance *ret, enum rp_check ctx,
2191 struct pt_regs *regs)
2192 {
2193 return true;
2194 }
2195
2196 /*
2197 * Run handler and ask thread to singlestep.
2198 * Ensure all non-fatal signals cannot interrupt thread while it singlesteps.
2199 */
handle_swbp(struct pt_regs * regs)2200 static void handle_swbp(struct pt_regs *regs)
2201 {
2202 struct uprobe *uprobe;
2203 unsigned long bp_vaddr;
2204 int is_swbp;
2205
2206 bp_vaddr = uprobe_get_swbp_addr(regs);
2207 if (bp_vaddr == get_trampoline_vaddr())
2208 return handle_trampoline(regs);
2209
2210 uprobe = find_active_uprobe(bp_vaddr, &is_swbp);
2211 if (!uprobe) {
2212 if (is_swbp > 0) {
2213 /* No matching uprobe; signal SIGTRAP. */
2214 force_sig(SIGTRAP);
2215 } else {
2216 /*
2217 * Either we raced with uprobe_unregister() or we can't
2218 * access this memory. The latter is only possible if
2219 * another thread plays with our ->mm. In both cases
2220 * we can simply restart. If this vma was unmapped we
2221 * can pretend this insn was not executed yet and get
2222 * the (correct) SIGSEGV after restart.
2223 */
2224 instruction_pointer_set(regs, bp_vaddr);
2225 }
2226 return;
2227 }
2228
2229 /* change it in advance for ->handler() and restart */
2230 instruction_pointer_set(regs, bp_vaddr);
2231
2232 /*
2233 * TODO: move copy_insn/etc into _register and remove this hack.
2234 * After we hit the bp, _unregister + _register can install the
2235 * new and not-yet-analyzed uprobe at the same address, restart.
2236 */
2237 if (unlikely(!test_bit(UPROBE_COPY_INSN, &uprobe->flags)))
2238 goto out;
2239
2240 /*
2241 * Pairs with the smp_wmb() in prepare_uprobe().
2242 *
2243 * Guarantees that if we see the UPROBE_COPY_INSN bit set, then
2244 * we must also see the stores to &uprobe->arch performed by the
2245 * prepare_uprobe() call.
2246 */
2247 smp_rmb();
2248
2249 /* Tracing handlers use ->utask to communicate with fetch methods */
2250 if (!get_utask())
2251 goto out;
2252
2253 if (arch_uprobe_ignore(&uprobe->arch, regs))
2254 goto out;
2255
2256 handler_chain(uprobe, regs);
2257
2258 if (arch_uprobe_skip_sstep(&uprobe->arch, regs))
2259 goto out;
2260
2261 if (!pre_ssout(uprobe, regs, bp_vaddr))
2262 return;
2263
2264 /* arch_uprobe_skip_sstep() succeeded, or restart if can't singlestep */
2265 out:
2266 put_uprobe(uprobe);
2267 }
2268
2269 /*
2270 * Perform required fix-ups and disable singlestep.
2271 * Allow pending signals to take effect.
2272 */
handle_singlestep(struct uprobe_task * utask,struct pt_regs * regs)2273 static void handle_singlestep(struct uprobe_task *utask, struct pt_regs *regs)
2274 {
2275 struct uprobe *uprobe;
2276 int err = 0;
2277
2278 uprobe = utask->active_uprobe;
2279 if (utask->state == UTASK_SSTEP_ACK)
2280 err = arch_uprobe_post_xol(&uprobe->arch, regs);
2281 else if (utask->state == UTASK_SSTEP_TRAPPED)
2282 arch_uprobe_abort_xol(&uprobe->arch, regs);
2283 else
2284 WARN_ON_ONCE(1);
2285
2286 put_uprobe(uprobe);
2287 utask->active_uprobe = NULL;
2288 utask->state = UTASK_RUNNING;
2289 xol_free_insn_slot(current);
2290
2291 spin_lock_irq(¤t->sighand->siglock);
2292 recalc_sigpending(); /* see uprobe_deny_signal() */
2293 spin_unlock_irq(¤t->sighand->siglock);
2294
2295 if (unlikely(err)) {
2296 uprobe_warn(current, "execute the probed insn, sending SIGILL.");
2297 force_sig(SIGILL);
2298 }
2299 }
2300
2301 /*
2302 * On breakpoint hit, breakpoint notifier sets the TIF_UPROBE flag and
2303 * allows the thread to return from interrupt. After that handle_swbp()
2304 * sets utask->active_uprobe.
2305 *
2306 * On singlestep exception, singlestep notifier sets the TIF_UPROBE flag
2307 * and allows the thread to return from interrupt.
2308 *
2309 * While returning to userspace, thread notices the TIF_UPROBE flag and calls
2310 * uprobe_notify_resume().
2311 */
uprobe_notify_resume(struct pt_regs * regs)2312 void uprobe_notify_resume(struct pt_regs *regs)
2313 {
2314 struct uprobe_task *utask;
2315
2316 clear_thread_flag(TIF_UPROBE);
2317
2318 utask = current->utask;
2319 if (utask && utask->active_uprobe)
2320 handle_singlestep(utask, regs);
2321 else
2322 handle_swbp(regs);
2323 }
2324
2325 /*
2326 * uprobe_pre_sstep_notifier gets called from interrupt context as part of
2327 * notifier mechanism. Set TIF_UPROBE flag and indicate breakpoint hit.
2328 */
uprobe_pre_sstep_notifier(struct pt_regs * regs)2329 int uprobe_pre_sstep_notifier(struct pt_regs *regs)
2330 {
2331 if (!current->mm)
2332 return 0;
2333
2334 if (!test_bit(MMF_HAS_UPROBES, ¤t->mm->flags) &&
2335 (!current->utask || !current->utask->return_instances))
2336 return 0;
2337
2338 set_thread_flag(TIF_UPROBE);
2339 return 1;
2340 }
2341
2342 /*
2343 * uprobe_post_sstep_notifier gets called in interrupt context as part of notifier
2344 * mechanism. Set TIF_UPROBE flag and indicate completion of singlestep.
2345 */
uprobe_post_sstep_notifier(struct pt_regs * regs)2346 int uprobe_post_sstep_notifier(struct pt_regs *regs)
2347 {
2348 struct uprobe_task *utask = current->utask;
2349
2350 if (!current->mm || !utask || !utask->active_uprobe)
2351 /* task is currently not uprobed */
2352 return 0;
2353
2354 utask->state = UTASK_SSTEP_ACK;
2355 set_thread_flag(TIF_UPROBE);
2356 return 1;
2357 }
2358
2359 static struct notifier_block uprobe_exception_nb = {
2360 .notifier_call = arch_uprobe_exception_notify,
2361 .priority = INT_MAX-1, /* notified after kprobes, kgdb */
2362 };
2363
uprobes_init(void)2364 void __init uprobes_init(void)
2365 {
2366 int i;
2367
2368 for (i = 0; i < UPROBES_HASH_SZ; i++)
2369 mutex_init(&uprobes_mmap_mutex[i]);
2370
2371 BUG_ON(register_die_notifier(&uprobe_exception_nb));
2372 }
2373