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/export.h>
19 #include <linux/rmap.h> /* anon_vma_prepare */
20 #include <linux/mmu_notifier.h>
21 #include <linux/swap.h> /* folio_free_swap */
22 #include <linux/ptrace.h> /* user_enable_single_step */
23 #include <linux/kdebug.h> /* notifier mechanism */
24 #include <linux/percpu-rwsem.h>
25 #include <linux/task_work.h>
26 #include <linux/shmem_fs.h>
27 #include <linux/khugepaged.h>
28 #include <linux/rcupdate_trace.h>
29 #include <linux/workqueue.h>
30 #include <linux/srcu.h>
31 #include <linux/oom.h> /* check_stable_address_space */
32 #include <linux/pagewalk.h>
33
34 #include <linux/uprobes.h>
35
36 #define UINSNS_PER_PAGE (PAGE_SIZE/UPROBE_XOL_SLOT_BYTES)
37 #define MAX_UPROBE_XOL_SLOTS UINSNS_PER_PAGE
38
39 static struct rb_root uprobes_tree = RB_ROOT;
40 /*
41 * allows us to skip the uprobe_mmap if there are no uprobe events active
42 * at this time. Probably a fine grained per inode count is better?
43 */
44 #define no_uprobe_events() RB_EMPTY_ROOT(&uprobes_tree)
45
46 static DEFINE_RWLOCK(uprobes_treelock); /* serialize rbtree access */
47 static seqcount_rwlock_t uprobes_seqcount = SEQCNT_RWLOCK_ZERO(uprobes_seqcount, &uprobes_treelock);
48
49 #define UPROBES_HASH_SZ 13
50 /* serialize uprobe->pending_list */
51 static struct mutex uprobes_mmap_mutex[UPROBES_HASH_SZ];
52 #define uprobes_mmap_hash(v) (&uprobes_mmap_mutex[((unsigned long)(v)) % UPROBES_HASH_SZ])
53
54 DEFINE_STATIC_PERCPU_RWSEM(dup_mmap_sem);
55
56 /* Covers return_instance's uprobe lifetime. */
57 DEFINE_STATIC_SRCU_FAST_UPDOWN(uretprobes_srcu);
58
59 /* Have a copy of original instruction */
60 #define UPROBE_COPY_INSN 0
61
62 struct uprobe {
63 struct rb_node rb_node; /* node in the rb tree */
64 refcount_t ref;
65 struct rw_semaphore register_rwsem;
66 struct rw_semaphore consumer_rwsem;
67 struct list_head pending_list;
68 struct list_head consumers;
69 struct inode *inode; /* Also hold a ref to inode */
70 union {
71 struct rcu_head rcu;
72 struct work_struct work;
73 };
74 loff_t offset;
75 loff_t ref_ctr_offset;
76 unsigned long flags; /* "unsigned long" so bitops work */
77
78 /*
79 * The generic code assumes that it has two members of unknown type
80 * owned by the arch-specific code:
81 *
82 * insn - copy_insn() saves the original instruction here for
83 * arch_uprobe_analyze_insn().
84 *
85 * ixol - potentially modified instruction to execute out of
86 * line, copied to xol_area by xol_get_insn_slot().
87 */
88 struct arch_uprobe arch;
89 };
90
91 struct delayed_uprobe {
92 struct list_head list;
93 struct uprobe *uprobe;
94 struct mm_struct *mm;
95 };
96
97 static DEFINE_MUTEX(delayed_uprobe_lock);
98 static LIST_HEAD(delayed_uprobe_list);
99
100 /*
101 * Execute out of line area: anonymous executable mapping installed
102 * by the probed task to execute the copy of the original instruction
103 * mangled by set_swbp().
104 *
105 * On a breakpoint hit, thread contests for a slot. It frees the
106 * slot after singlestep. Currently a fixed number of slots are
107 * allocated.
108 */
109 struct xol_area {
110 wait_queue_head_t wq; /* if all slots are busy */
111 unsigned long *bitmap; /* 0 = free slot */
112
113 struct page *page;
114 /*
115 * We keep the vma's vm_start rather than a pointer to the vma
116 * itself. The probed process or a naughty kernel module could make
117 * the vma go away, and we must handle that reasonably gracefully.
118 */
119 unsigned long vaddr; /* Page(s) of instruction slots */
120 };
121
uprobe_warn(struct task_struct * t,const char * msg)122 static void uprobe_warn(struct task_struct *t, const char *msg)
123 {
124 pr_warn("uprobe: %s:%d failed to %s\n", t->comm, t->pid, msg);
125 }
126
127 /*
128 * valid_vma: Verify if the specified vma is an executable vma
129 * Relax restrictions while unregistering: vm_flags might have
130 * changed after breakpoint was inserted.
131 * - is_register: indicates if we are in register context.
132 * - Return 1 if the specified virtual address is in an
133 * executable vma.
134 */
valid_vma(struct vm_area_struct * vma,bool is_register)135 static bool valid_vma(struct vm_area_struct *vma, bool is_register)
136 {
137 vm_flags_t flags = VM_HUGETLB | VM_MAYEXEC | VM_MAYSHARE;
138
139 if (is_register)
140 flags |= VM_WRITE;
141
142 return vma->vm_file && (vma->vm_flags & flags) == VM_MAYEXEC;
143 }
144
offset_to_vaddr(struct vm_area_struct * vma,loff_t offset)145 static unsigned long offset_to_vaddr(struct vm_area_struct *vma, loff_t offset)
146 {
147 return vma->vm_start + offset -
148 ((loff_t)vma_start_pgoff(vma) << PAGE_SHIFT);
149 }
150
vaddr_to_offset(struct vm_area_struct * vma,unsigned long vaddr)151 static loff_t vaddr_to_offset(struct vm_area_struct *vma, unsigned long vaddr)
152 {
153 return ((loff_t)vma_start_pgoff(vma) << PAGE_SHIFT) +
154 (vaddr - vma->vm_start);
155 }
156
157 /**
158 * is_swbp_insn - check if instruction is breakpoint instruction.
159 * @insn: instruction to be checked.
160 * Default implementation of is_swbp_insn
161 * Returns true if @insn is a breakpoint instruction.
162 */
is_swbp_insn(uprobe_opcode_t * insn)163 bool __weak is_swbp_insn(uprobe_opcode_t *insn)
164 {
165 return *insn == UPROBE_SWBP_INSN;
166 }
167
168 /**
169 * is_trap_insn - check if instruction is breakpoint instruction.
170 * @insn: instruction to be checked.
171 * Default implementation of is_trap_insn
172 * Returns true if @insn is a breakpoint instruction.
173 *
174 * This function is needed for the case where an architecture has multiple
175 * trap instructions (like powerpc).
176 */
is_trap_insn(uprobe_opcode_t * insn)177 bool __weak is_trap_insn(uprobe_opcode_t *insn)
178 {
179 return is_swbp_insn(insn);
180 }
181
uprobe_copy_from_page(struct page * page,unsigned long vaddr,void * dst,int len)182 void uprobe_copy_from_page(struct page *page, unsigned long vaddr, void *dst, int len)
183 {
184 void *kaddr = kmap_local_page(page);
185 memcpy(dst, kaddr + (vaddr & ~PAGE_MASK), len);
186 kunmap_local(kaddr);
187 }
188
copy_to_page(struct page * page,unsigned long vaddr,const void * src,int len)189 static void copy_to_page(struct page *page, unsigned long vaddr, const void *src, int len)
190 {
191 void *kaddr = kmap_local_page(page);
192 memcpy(kaddr + (vaddr & ~PAGE_MASK), src, len);
193 kunmap_local(kaddr);
194 }
195
verify_opcode(struct page * page,unsigned long vaddr,uprobe_opcode_t * insn,int nbytes,void * data)196 static int verify_opcode(struct page *page, unsigned long vaddr, uprobe_opcode_t *insn,
197 int nbytes, void *data)
198 {
199 uprobe_opcode_t old_opcode;
200 bool is_swbp;
201
202 /*
203 * Note: We only check if the old_opcode is UPROBE_SWBP_INSN here.
204 * We do not check if it is any other 'trap variant' which could
205 * be conditional trap instruction such as the one powerpc supports.
206 *
207 * The logic is that we do not care if the underlying instruction
208 * is a trap variant; uprobes always wins over any other (gdb)
209 * breakpoint.
210 */
211 uprobe_copy_from_page(page, vaddr, &old_opcode, UPROBE_SWBP_INSN_SIZE);
212 is_swbp = is_swbp_insn(&old_opcode);
213
214 if (is_swbp_insn(insn)) {
215 if (is_swbp) /* register: already installed? */
216 return 0;
217 } else {
218 if (!is_swbp) /* unregister: was it changed by us? */
219 return 0;
220 }
221
222 return 1;
223 }
224
225 static struct delayed_uprobe *
delayed_uprobe_check(struct uprobe * uprobe,struct mm_struct * mm)226 delayed_uprobe_check(struct uprobe *uprobe, struct mm_struct *mm)
227 {
228 struct delayed_uprobe *du;
229
230 list_for_each_entry(du, &delayed_uprobe_list, list)
231 if (du->uprobe == uprobe && du->mm == mm)
232 return du;
233 return NULL;
234 }
235
delayed_uprobe_add(struct uprobe * uprobe,struct mm_struct * mm)236 static int delayed_uprobe_add(struct uprobe *uprobe, struct mm_struct *mm)
237 {
238 struct delayed_uprobe *du;
239
240 if (delayed_uprobe_check(uprobe, mm))
241 return 0;
242
243 du = kzalloc_obj(*du);
244 if (!du)
245 return -ENOMEM;
246
247 du->uprobe = uprobe;
248 du->mm = mm;
249 list_add(&du->list, &delayed_uprobe_list);
250 return 0;
251 }
252
delayed_uprobe_delete(struct delayed_uprobe * du)253 static void delayed_uprobe_delete(struct delayed_uprobe *du)
254 {
255 if (WARN_ON(!du))
256 return;
257 list_del(&du->list);
258 kfree(du);
259 }
260
delayed_uprobe_remove(struct uprobe * uprobe,struct mm_struct * mm)261 static void delayed_uprobe_remove(struct uprobe *uprobe, struct mm_struct *mm)
262 {
263 struct list_head *pos, *q;
264 struct delayed_uprobe *du;
265
266 if (!uprobe && !mm)
267 return;
268
269 list_for_each_safe(pos, q, &delayed_uprobe_list) {
270 du = list_entry(pos, struct delayed_uprobe, list);
271
272 if (uprobe && du->uprobe != uprobe)
273 continue;
274 if (mm && du->mm != mm)
275 continue;
276
277 delayed_uprobe_delete(du);
278 }
279 }
280
valid_ref_ctr_vma(struct uprobe * uprobe,struct vm_area_struct * vma)281 static bool valid_ref_ctr_vma(struct uprobe *uprobe,
282 struct vm_area_struct *vma)
283 {
284 unsigned long vaddr = offset_to_vaddr(vma, uprobe->ref_ctr_offset);
285
286 return uprobe->ref_ctr_offset &&
287 vma->vm_file &&
288 file_inode(vma->vm_file) == uprobe->inode &&
289 (vma->vm_flags & (VM_WRITE|VM_SHARED)) == VM_WRITE &&
290 vma->vm_start <= vaddr &&
291 vma->vm_end > vaddr;
292 }
293
294 static struct vm_area_struct *
find_ref_ctr_vma(struct uprobe * uprobe,struct mm_struct * mm)295 find_ref_ctr_vma(struct uprobe *uprobe, struct mm_struct *mm)
296 {
297 VMA_ITERATOR(vmi, mm, 0);
298 struct vm_area_struct *tmp;
299
300 for_each_vma(vmi, tmp)
301 if (valid_ref_ctr_vma(uprobe, tmp))
302 return tmp;
303
304 return NULL;
305 }
306
307 static int
__update_ref_ctr(struct mm_struct * mm,unsigned long vaddr,short d)308 __update_ref_ctr(struct mm_struct *mm, unsigned long vaddr, short d)
309 {
310 void *kaddr;
311 struct page *page;
312 int ret;
313 short *ptr;
314
315 if (!vaddr || !d)
316 return -EINVAL;
317
318 ret = get_user_pages_remote(mm, vaddr, 1,
319 FOLL_WRITE, &page, NULL);
320 if (unlikely(ret <= 0)) {
321 /*
322 * We are asking for 1 page. If get_user_pages_remote() fails,
323 * it may return 0, in that case we have to return error.
324 */
325 return ret == 0 ? -EBUSY : ret;
326 }
327
328 kaddr = kmap_local_page(page);
329 ptr = kaddr + (vaddr & ~PAGE_MASK);
330
331 if (unlikely(*ptr + d < 0)) {
332 pr_warn("ref_ctr going negative. vaddr: 0x%lx, "
333 "curr val: %d, delta: %d\n", vaddr, *ptr, d);
334 ret = -EINVAL;
335 goto out;
336 }
337
338 *ptr += d;
339 ret = 0;
340 out:
341 kunmap_local(kaddr);
342 put_page(page);
343 return ret;
344 }
345
update_ref_ctr_warn(struct uprobe * uprobe,struct mm_struct * mm,short d)346 static void update_ref_ctr_warn(struct uprobe *uprobe,
347 struct mm_struct *mm, short d)
348 {
349 pr_warn("ref_ctr %s failed for inode: 0x%llx offset: "
350 "0x%llx ref_ctr_offset: 0x%llx of mm: 0x%p\n",
351 d > 0 ? "increment" : "decrement", uprobe->inode->i_ino,
352 (unsigned long long) uprobe->offset,
353 (unsigned long long) uprobe->ref_ctr_offset, mm);
354 }
355
update_ref_ctr(struct uprobe * uprobe,struct mm_struct * mm,short d)356 static int update_ref_ctr(struct uprobe *uprobe, struct mm_struct *mm,
357 short d)
358 {
359 struct vm_area_struct *rc_vma;
360 unsigned long rc_vaddr;
361 int ret = 0;
362
363 rc_vma = find_ref_ctr_vma(uprobe, mm);
364
365 if (rc_vma) {
366 rc_vaddr = offset_to_vaddr(rc_vma, uprobe->ref_ctr_offset);
367 ret = __update_ref_ctr(mm, rc_vaddr, d);
368 if (ret)
369 update_ref_ctr_warn(uprobe, mm, d);
370
371 if (d > 0)
372 return ret;
373 }
374
375 mutex_lock(&delayed_uprobe_lock);
376 if (d > 0)
377 ret = delayed_uprobe_add(uprobe, mm);
378 else
379 delayed_uprobe_remove(uprobe, mm);
380 mutex_unlock(&delayed_uprobe_lock);
381
382 return ret;
383 }
384
orig_page_is_identical(struct vm_area_struct * vma,unsigned long vaddr,struct page * page,bool * pmd_mappable)385 static bool orig_page_is_identical(struct vm_area_struct *vma,
386 unsigned long vaddr, struct page *page, bool *pmd_mappable)
387 {
388 const pgoff_t index = vaddr_to_offset(vma, vaddr) >> PAGE_SHIFT;
389 struct folio *orig_folio = filemap_get_folio(vma->vm_file->f_mapping,
390 index);
391 struct page *orig_page;
392 bool identical;
393
394 if (IS_ERR(orig_folio))
395 return false;
396 orig_page = folio_file_page(orig_folio, index);
397
398 *pmd_mappable = folio_test_pmd_mappable(orig_folio);
399 identical = folio_test_uptodate(orig_folio) &&
400 pages_identical(page, orig_page);
401 folio_put(orig_folio);
402 return identical;
403 }
404
__uprobe_write(struct vm_area_struct * vma,struct folio_walk * fw,struct folio * folio,unsigned long insn_vaddr,uprobe_opcode_t * insn,int nbytes,bool is_register)405 static int __uprobe_write(struct vm_area_struct *vma,
406 struct folio_walk *fw, struct folio *folio,
407 unsigned long insn_vaddr, uprobe_opcode_t *insn, int nbytes,
408 bool is_register)
409 {
410 const unsigned long vaddr = insn_vaddr & PAGE_MASK;
411 bool pmd_mappable;
412
413 /* For now, we'll only handle PTE-mapped folios. */
414 if (fw->level != FW_LEVEL_PTE)
415 return -EFAULT;
416
417 /*
418 * See can_follow_write_pte(): we'd actually prefer a writable PTE here,
419 * but the VMA might not be writable.
420 */
421 if (!pte_write(fw->pte)) {
422 if (!PageAnonExclusive(fw->page))
423 return -EFAULT;
424 if (unlikely(userfaultfd_pte_wp(vma, fw->pte)))
425 return -EFAULT;
426 /* SOFTDIRTY is handled via pte_mkdirty() below. */
427 }
428
429 /*
430 * We'll temporarily unmap the page and flush the TLB, such that we can
431 * modify the page atomically.
432 */
433 flush_cache_page(vma, vaddr, pte_pfn(fw->pte));
434 fw->pte = ptep_clear_flush(vma, vaddr, fw->ptep);
435 copy_to_page(fw->page, insn_vaddr, insn, nbytes);
436
437 /*
438 * When unregistering, we may only zap a PTE if uffd is disabled and
439 * there are no unexpected folio references ...
440 */
441 if (is_register || userfaultfd_missing(vma) ||
442 (folio_ref_count(folio) != folio_expected_ref_count(folio) + 1))
443 goto remap;
444
445 /*
446 * ... and the mapped page is identical to the original page that
447 * would get faulted in on next access.
448 */
449 if (!orig_page_is_identical(vma, vaddr, fw->page, &pmd_mappable))
450 goto remap;
451
452 dec_mm_counter(vma->vm_mm, MM_ANONPAGES);
453 folio_remove_rmap_pte(folio, fw->page, vma);
454 if (!folio_mapped(folio) && folio_test_swapcache(folio) &&
455 folio_trylock(folio)) {
456 folio_free_swap(folio);
457 folio_unlock(folio);
458 }
459 folio_put(folio);
460
461 return pmd_mappable;
462 remap:
463 /*
464 * Make sure that our copy_to_page() changes become visible before the
465 * set_pte_at() write.
466 */
467 smp_wmb();
468 /* We modified the page. Make sure to mark the PTE dirty. */
469 set_pte_at(vma->vm_mm, vaddr, fw->ptep, pte_mkdirty(fw->pte));
470 return 0;
471 }
472
473 /*
474 * NOTE:
475 * Expect the breakpoint instruction to be the smallest size instruction for
476 * the architecture. If an arch has variable length instruction and the
477 * breakpoint instruction is not of the smallest length instruction
478 * supported by that architecture then we need to modify is_trap_at_addr and
479 * uprobe_write_opcode accordingly. This would never be a problem for archs
480 * that have fixed length instructions.
481 *
482 * uprobe_write_opcode - write the opcode at a given virtual address.
483 * @auprobe: arch specific probepoint information.
484 * @vma: the probed virtual memory area.
485 * @opcode_vaddr: the virtual address to store the opcode.
486 * @opcode: opcode to be written at @opcode_vaddr.
487 *
488 * Called with mm->mmap_lock held for write.
489 * Return 0 (success) or a negative errno.
490 */
uprobe_write_opcode(struct arch_uprobe * auprobe,struct vm_area_struct * vma,const unsigned long opcode_vaddr,uprobe_opcode_t opcode,bool is_register)491 int uprobe_write_opcode(struct arch_uprobe *auprobe, struct vm_area_struct *vma,
492 const unsigned long opcode_vaddr, uprobe_opcode_t opcode,
493 bool is_register)
494 {
495 return uprobe_write(auprobe, vma, opcode_vaddr, &opcode, UPROBE_SWBP_INSN_SIZE,
496 verify_opcode, is_register, true /* do_update_ref_ctr */, NULL);
497 }
498
uprobe_write(struct arch_uprobe * auprobe,struct vm_area_struct * vma,const unsigned long insn_vaddr,uprobe_opcode_t * insn,int nbytes,uprobe_write_verify_t verify,bool is_register,bool do_update_ref_ctr,void * data)499 int uprobe_write(struct arch_uprobe *auprobe, struct vm_area_struct *vma,
500 const unsigned long insn_vaddr, uprobe_opcode_t *insn, int nbytes,
501 uprobe_write_verify_t verify, bool is_register, bool do_update_ref_ctr,
502 void *data)
503 {
504 const unsigned long vaddr = insn_vaddr & PAGE_MASK;
505 struct mm_struct *mm = vma->vm_mm;
506 struct uprobe *uprobe;
507 int ret, ref_ctr_updated = 0;
508 unsigned int gup_flags = FOLL_FORCE;
509 struct mmu_notifier_range range;
510 struct folio_walk fw;
511 struct folio *folio;
512 struct page *page;
513
514 uprobe = container_of(auprobe, struct uprobe, arch);
515
516 if (WARN_ON_ONCE(!vma_is_cow_mapping(vma)))
517 return -EINVAL;
518
519 /*
520 * When registering, we have to break COW to get an exclusive anonymous
521 * page that we can safely modify. Use FOLL_WRITE to trigger a write
522 * fault if required. When unregistering, we might be lucky and the
523 * anon page is already gone. So defer write faults until really
524 * required. Use FOLL_SPLIT_PMD, because __uprobe_write()
525 * cannot deal with PMDs yet.
526 */
527 if (is_register)
528 gup_flags |= FOLL_WRITE | FOLL_SPLIT_PMD;
529
530 retry:
531 ret = get_user_pages_remote(mm, vaddr, 1, gup_flags, &page, NULL);
532 if (ret <= 0)
533 goto out;
534 folio = page_folio(page);
535
536 ret = verify(page, insn_vaddr, insn, nbytes, data);
537 if (ret <= 0) {
538 folio_put(folio);
539 goto out;
540 }
541
542 /* We are going to replace instruction, update ref_ctr. */
543 if (do_update_ref_ctr && !ref_ctr_updated && uprobe->ref_ctr_offset) {
544 ret = update_ref_ctr(uprobe, mm, is_register ? 1 : -1);
545 if (ret) {
546 folio_put(folio);
547 goto out;
548 }
549
550 ref_ctr_updated = 1;
551 }
552
553 ret = 0;
554 if (unlikely(!folio_test_anon(folio) || folio_is_zone_device(folio))) {
555 VM_WARN_ON_ONCE(is_register);
556 folio_put(folio);
557 goto out;
558 }
559
560 if (!is_register) {
561 /*
562 * In the common case, we'll be able to zap the page when
563 * unregistering. So trigger MMU notifiers now, as we won't
564 * be able to do it under PTL.
565 */
566 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
567 vaddr, vaddr + PAGE_SIZE);
568 mmu_notifier_invalidate_range_start(&range);
569 }
570
571 ret = -EAGAIN;
572 /* Walk the page tables again, to perform the actual update. */
573 if (folio_walk_start(&fw, vma, vaddr, 0)) {
574 if (fw.page == page)
575 ret = __uprobe_write(vma, &fw, folio, insn_vaddr, insn, nbytes, is_register);
576 folio_walk_end(&fw, vma);
577 }
578
579 if (!is_register)
580 mmu_notifier_invalidate_range_end(&range);
581
582 folio_put(folio);
583 switch (ret) {
584 case -EFAULT:
585 gup_flags |= FOLL_WRITE | FOLL_SPLIT_PMD;
586 fallthrough;
587 case -EAGAIN:
588 goto retry;
589 default:
590 break;
591 }
592
593 out:
594 /* Revert back reference counter if instruction update failed. */
595 if (do_update_ref_ctr && ret < 0 && ref_ctr_updated)
596 update_ref_ctr(uprobe, mm, is_register ? -1 : 1);
597
598 /* try collapse pmd for compound page */
599 if (ret > 0)
600 collapse_pte_mapped_thp(mm, vaddr, false);
601
602 return ret < 0 ? ret : 0;
603 }
604
605 /**
606 * set_swbp - store breakpoint at a given address.
607 * @auprobe: arch specific probepoint information.
608 * @vma: the probed virtual memory area.
609 * @vaddr: the virtual address to insert the opcode.
610 *
611 * For mm @mm, store the breakpoint instruction at @vaddr.
612 * Return 0 (success) or a negative errno.
613 */
set_swbp(struct arch_uprobe * auprobe,struct vm_area_struct * vma,unsigned long vaddr)614 int __weak set_swbp(struct arch_uprobe *auprobe, struct vm_area_struct *vma,
615 unsigned long vaddr)
616 {
617 return uprobe_write_opcode(auprobe, vma, vaddr, UPROBE_SWBP_INSN, true);
618 }
619
620 /**
621 * set_orig_insn - Restore the original instruction.
622 * @vma: the probed virtual memory area.
623 * @auprobe: arch specific probepoint information.
624 * @vaddr: the virtual address to insert the opcode.
625 *
626 * For mm @mm, restore the original opcode (opcode) at @vaddr.
627 * Return 0 (success) or a negative errno.
628 */
set_orig_insn(struct arch_uprobe * auprobe,struct vm_area_struct * vma,unsigned long vaddr)629 int __weak set_orig_insn(struct arch_uprobe *auprobe,
630 struct vm_area_struct *vma, unsigned long vaddr)
631 {
632 return uprobe_write_opcode(auprobe, vma, vaddr,
633 *(uprobe_opcode_t *)&auprobe->insn, false);
634 }
635
636 /* uprobe should have guaranteed positive refcount */
get_uprobe(struct uprobe * uprobe)637 static struct uprobe *get_uprobe(struct uprobe *uprobe)
638 {
639 refcount_inc(&uprobe->ref);
640 return uprobe;
641 }
642
643 /*
644 * uprobe should have guaranteed lifetime, which can be either of:
645 * - caller already has refcount taken (and wants an extra one);
646 * - uprobe is RCU protected and won't be freed until after grace period;
647 * - we are holding uprobes_treelock (for read or write, doesn't matter).
648 */
try_get_uprobe(struct uprobe * uprobe)649 static struct uprobe *try_get_uprobe(struct uprobe *uprobe)
650 {
651 if (refcount_inc_not_zero(&uprobe->ref))
652 return uprobe;
653 return NULL;
654 }
655
uprobe_is_active(struct uprobe * uprobe)656 static inline bool uprobe_is_active(struct uprobe *uprobe)
657 {
658 return !RB_EMPTY_NODE(&uprobe->rb_node);
659 }
660
uprobe_free_rcu_tasks_trace(struct rcu_head * rcu)661 static void uprobe_free_rcu_tasks_trace(struct rcu_head *rcu)
662 {
663 struct uprobe *uprobe = container_of(rcu, struct uprobe, rcu);
664
665 kfree(uprobe);
666 }
667
uprobe_free_srcu(struct rcu_head * rcu)668 static void uprobe_free_srcu(struct rcu_head *rcu)
669 {
670 struct uprobe *uprobe = container_of(rcu, struct uprobe, rcu);
671
672 call_rcu_tasks_trace(&uprobe->rcu, uprobe_free_rcu_tasks_trace);
673 }
674
uprobe_free_deferred(struct work_struct * work)675 static void uprobe_free_deferred(struct work_struct *work)
676 {
677 struct uprobe *uprobe = container_of(work, struct uprobe, work);
678
679 write_lock(&uprobes_treelock);
680
681 if (uprobe_is_active(uprobe)) {
682 write_seqcount_begin(&uprobes_seqcount);
683 rb_erase(&uprobe->rb_node, &uprobes_tree);
684 write_seqcount_end(&uprobes_seqcount);
685 }
686
687 write_unlock(&uprobes_treelock);
688
689 /*
690 * If application munmap(exec_vma) before uprobe_unregister()
691 * gets called, we don't get a chance to remove uprobe from
692 * delayed_uprobe_list from remove_breakpoint(). Do it here.
693 */
694 mutex_lock(&delayed_uprobe_lock);
695 delayed_uprobe_remove(uprobe, NULL);
696 mutex_unlock(&delayed_uprobe_lock);
697
698 /* start srcu -> rcu_tasks_trace -> kfree chain */
699 call_srcu(&uretprobes_srcu, &uprobe->rcu, uprobe_free_srcu);
700 }
701
put_uprobe(struct uprobe * uprobe)702 static void put_uprobe(struct uprobe *uprobe)
703 {
704 if (!refcount_dec_and_test(&uprobe->ref))
705 return;
706
707 INIT_WORK(&uprobe->work, uprobe_free_deferred);
708 schedule_work(&uprobe->work);
709 }
710
711 /* Initialize hprobe as SRCU-protected "leased" uprobe */
hprobe_init_leased(struct hprobe * hprobe,struct uprobe * uprobe,struct srcu_ctr __percpu * srcu_scp)712 static void hprobe_init_leased(struct hprobe *hprobe, struct uprobe *uprobe,
713 struct srcu_ctr __percpu *srcu_scp)
714 {
715 WARN_ON(!uprobe);
716 hprobe->state = HPROBE_LEASED;
717 hprobe->uprobe = uprobe;
718 hprobe->srcu_scp = srcu_scp;
719 }
720
721 /* Initialize hprobe as refcounted ("stable") uprobe (uprobe can be NULL). */
hprobe_init_stable(struct hprobe * hprobe,struct uprobe * uprobe)722 static void hprobe_init_stable(struct hprobe *hprobe, struct uprobe *uprobe)
723 {
724 hprobe->state = uprobe ? HPROBE_STABLE : HPROBE_GONE;
725 hprobe->uprobe = uprobe;
726 hprobe->srcu_scp = NULL;
727 }
728
729 /*
730 * hprobe_consume() fetches hprobe's underlying uprobe and detects whether
731 * uprobe is SRCU protected or is refcounted. hprobe_consume() can be
732 * used only once for a given hprobe.
733 *
734 * Caller has to call hprobe_finalize() and pass previous hprobe_state, so
735 * that hprobe_finalize() can perform SRCU unlock or put uprobe, whichever
736 * is appropriate.
737 */
hprobe_consume(struct hprobe * hprobe,enum hprobe_state * hstate)738 static inline struct uprobe *hprobe_consume(struct hprobe *hprobe, enum hprobe_state *hstate)
739 {
740 *hstate = xchg(&hprobe->state, HPROBE_CONSUMED);
741 switch (*hstate) {
742 case HPROBE_LEASED:
743 case HPROBE_STABLE:
744 return hprobe->uprobe;
745 case HPROBE_GONE: /* uprobe is NULL, no SRCU */
746 case HPROBE_CONSUMED: /* uprobe was finalized already, do nothing */
747 return NULL;
748 default:
749 WARN(1, "hprobe invalid state %d", *hstate);
750 return NULL;
751 }
752 }
753
754 /*
755 * Reset hprobe state and, if hprobe was LEASED, release SRCU lock.
756 * hprobe_finalize() can only be used from current context after
757 * hprobe_consume() call (which determines uprobe and hstate value).
758 */
hprobe_finalize(struct hprobe * hprobe,enum hprobe_state hstate)759 static void hprobe_finalize(struct hprobe *hprobe, enum hprobe_state hstate)
760 {
761 switch (hstate) {
762 case HPROBE_LEASED:
763 srcu_up_read_fast(&uretprobes_srcu, hprobe->srcu_scp);
764 break;
765 case HPROBE_STABLE:
766 put_uprobe(hprobe->uprobe);
767 break;
768 case HPROBE_GONE:
769 case HPROBE_CONSUMED:
770 break;
771 default:
772 WARN(1, "hprobe invalid state %d", hstate);
773 break;
774 }
775 }
776
777 /*
778 * Attempt to switch (atomically) uprobe from being SRCU protected (LEASED)
779 * to refcounted (STABLE) state. Competes with hprobe_consume(); only one of
780 * them can win the race to perform SRCU unlocking. Whoever wins must perform
781 * SRCU unlock.
782 *
783 * Returns underlying valid uprobe or NULL, if there was no underlying uprobe
784 * to begin with or we failed to bump its refcount and it's going away.
785 *
786 * Returned non-NULL uprobe can be still safely used within an ongoing SRCU
787 * locked region. If `get` is true, it's guaranteed that non-NULL uprobe has
788 * an extra refcount for caller to assume and use. Otherwise, it's not
789 * guaranteed that returned uprobe has a positive refcount, so caller has to
790 * attempt try_get_uprobe(), if it needs to preserve uprobe beyond current
791 * SRCU lock region. See dup_utask().
792 */
hprobe_expire(struct hprobe * hprobe,bool get)793 static struct uprobe *hprobe_expire(struct hprobe *hprobe, bool get)
794 {
795 enum hprobe_state hstate;
796
797 /*
798 * Caller should guarantee that return_instance is not going to be
799 * freed from under us. This can be achieved either through holding
800 * rcu_read_lock() or by owning return_instance in the first place.
801 *
802 * Underlying uprobe is itself protected from reuse by SRCU, so ensure
803 * SRCU lock is held properly.
804 */
805 lockdep_assert(srcu_read_lock_held(&uretprobes_srcu));
806
807 hstate = READ_ONCE(hprobe->state);
808 switch (hstate) {
809 case HPROBE_STABLE:
810 /* uprobe has positive refcount, bump refcount, if necessary */
811 return get ? get_uprobe(hprobe->uprobe) : hprobe->uprobe;
812 case HPROBE_GONE:
813 /*
814 * SRCU was unlocked earlier and we didn't manage to take
815 * uprobe refcnt, so it's effectively NULL
816 */
817 return NULL;
818 case HPROBE_CONSUMED:
819 /*
820 * uprobe was consumed, so it's effectively NULL as far as
821 * uretprobe processing logic is concerned
822 */
823 return NULL;
824 case HPROBE_LEASED: {
825 struct uprobe *uprobe = try_get_uprobe(hprobe->uprobe);
826 /*
827 * Try to switch hprobe state, guarding against
828 * hprobe_consume() or another hprobe_expire() racing with us.
829 * Note, if we failed to get uprobe refcount, we use special
830 * HPROBE_GONE state to signal that hprobe->uprobe shouldn't
831 * be used as it will be freed after SRCU is unlocked.
832 */
833 if (try_cmpxchg(&hprobe->state, &hstate, uprobe ? HPROBE_STABLE : HPROBE_GONE)) {
834 /* We won the race, we are the ones to unlock SRCU */
835 srcu_up_read_fast(&uretprobes_srcu, hprobe->srcu_scp);
836 return get && uprobe ? get_uprobe(uprobe) : uprobe;
837 }
838
839 /*
840 * We lost the race, undo refcount bump (if it ever happened),
841 * unless caller would like an extra refcount anyways.
842 */
843 if (uprobe && !get)
844 put_uprobe(uprobe);
845 /*
846 * Even if hprobe_consume() or another hprobe_expire() wins
847 * the state update race and unlocks SRCU from under us, we
848 * still have a guarantee that underyling uprobe won't be
849 * freed due to ongoing caller's SRCU lock region, so we can
850 * return it regardless. Also, if `get` was true, we also have
851 * an extra ref for the caller to own. This is used in dup_utask().
852 */
853 return uprobe;
854 }
855 default:
856 WARN(1, "unknown hprobe state %d", hstate);
857 return NULL;
858 }
859 }
860
861 static __always_inline
uprobe_cmp(const struct inode * l_inode,const loff_t l_offset,const struct uprobe * r)862 int uprobe_cmp(const struct inode *l_inode, const loff_t l_offset,
863 const struct uprobe *r)
864 {
865 if (l_inode < r->inode)
866 return -1;
867
868 if (l_inode > r->inode)
869 return 1;
870
871 if (l_offset < r->offset)
872 return -1;
873
874 if (l_offset > r->offset)
875 return 1;
876
877 return 0;
878 }
879
880 #define __node_2_uprobe(node) \
881 rb_entry((node), struct uprobe, rb_node)
882
883 struct __uprobe_key {
884 struct inode *inode;
885 loff_t offset;
886 };
887
__uprobe_cmp_key(const void * key,const struct rb_node * b)888 static inline int __uprobe_cmp_key(const void *key, const struct rb_node *b)
889 {
890 const struct __uprobe_key *a = key;
891 return uprobe_cmp(a->inode, a->offset, __node_2_uprobe(b));
892 }
893
__uprobe_cmp(struct rb_node * a,const struct rb_node * b)894 static inline int __uprobe_cmp(struct rb_node *a, const struct rb_node *b)
895 {
896 struct uprobe *u = __node_2_uprobe(a);
897 return uprobe_cmp(u->inode, u->offset, __node_2_uprobe(b));
898 }
899
900 /*
901 * Assumes being inside RCU protected region.
902 * No refcount is taken on returned uprobe.
903 */
find_uprobe_rcu(struct inode * inode,loff_t offset)904 static struct uprobe *find_uprobe_rcu(struct inode *inode, loff_t offset)
905 {
906 struct __uprobe_key key = {
907 .inode = inode,
908 .offset = offset,
909 };
910 struct rb_node *node;
911 unsigned int seq;
912
913 lockdep_assert(rcu_read_lock_trace_held());
914
915 do {
916 seq = read_seqcount_begin(&uprobes_seqcount);
917 node = rb_find_rcu(&key, &uprobes_tree, __uprobe_cmp_key);
918 /*
919 * Lockless RB-tree lookups can result only in false negatives.
920 * If the element is found, it is correct and can be returned
921 * under RCU protection. If we find nothing, we need to
922 * validate that seqcount didn't change. If it did, we have to
923 * try again as we might have missed the element (false
924 * negative). If seqcount is unchanged, search truly failed.
925 */
926 if (node)
927 return __node_2_uprobe(node);
928 } while (read_seqcount_retry(&uprobes_seqcount, seq));
929
930 return NULL;
931 }
932
933 /*
934 * Attempt to insert a new uprobe into uprobes_tree.
935 *
936 * If uprobe already exists (for given inode+offset), we just increment
937 * refcount of previously existing uprobe.
938 *
939 * If not, a provided new instance of uprobe is inserted into the tree (with
940 * assumed initial refcount == 1).
941 *
942 * In any case, we return a uprobe instance that ends up being in uprobes_tree.
943 * Caller has to clean up new uprobe instance, if it ended up not being
944 * inserted into the tree.
945 *
946 * We assume that uprobes_treelock is held for writing.
947 */
__insert_uprobe(struct uprobe * uprobe)948 static struct uprobe *__insert_uprobe(struct uprobe *uprobe)
949 {
950 struct rb_node *node;
951 again:
952 node = rb_find_add_rcu(&uprobe->rb_node, &uprobes_tree, __uprobe_cmp);
953 if (node) {
954 struct uprobe *u = __node_2_uprobe(node);
955
956 if (!try_get_uprobe(u)) {
957 rb_erase(node, &uprobes_tree);
958 RB_CLEAR_NODE(&u->rb_node);
959 goto again;
960 }
961
962 return u;
963 }
964
965 return uprobe;
966 }
967
968 /*
969 * Acquire uprobes_treelock and insert uprobe into uprobes_tree
970 * (or reuse existing one, see __insert_uprobe() comments above).
971 */
insert_uprobe(struct uprobe * uprobe)972 static struct uprobe *insert_uprobe(struct uprobe *uprobe)
973 {
974 struct uprobe *u;
975
976 write_lock(&uprobes_treelock);
977 write_seqcount_begin(&uprobes_seqcount);
978 u = __insert_uprobe(uprobe);
979 write_seqcount_end(&uprobes_seqcount);
980 write_unlock(&uprobes_treelock);
981
982 return u;
983 }
984
985 static void
ref_ctr_mismatch_warn(struct uprobe * cur_uprobe,struct uprobe * uprobe)986 ref_ctr_mismatch_warn(struct uprobe *cur_uprobe, struct uprobe *uprobe)
987 {
988 pr_warn("ref_ctr_offset mismatch. inode: 0x%llx offset: 0x%llx "
989 "ref_ctr_offset(old): 0x%llx ref_ctr_offset(new): 0x%llx\n",
990 uprobe->inode->i_ino, (unsigned long long) uprobe->offset,
991 (unsigned long long) cur_uprobe->ref_ctr_offset,
992 (unsigned long long) uprobe->ref_ctr_offset);
993 }
994
alloc_uprobe(struct inode * inode,loff_t offset,loff_t ref_ctr_offset)995 static struct uprobe *alloc_uprobe(struct inode *inode, loff_t offset,
996 loff_t ref_ctr_offset)
997 {
998 struct uprobe *uprobe, *cur_uprobe;
999
1000 uprobe = kzalloc_obj(struct uprobe);
1001 if (!uprobe)
1002 return ERR_PTR(-ENOMEM);
1003
1004 uprobe->inode = inode;
1005 uprobe->offset = offset;
1006 uprobe->ref_ctr_offset = ref_ctr_offset;
1007 INIT_LIST_HEAD(&uprobe->consumers);
1008 init_rwsem(&uprobe->register_rwsem);
1009 init_rwsem(&uprobe->consumer_rwsem);
1010 RB_CLEAR_NODE(&uprobe->rb_node);
1011 refcount_set(&uprobe->ref, 1);
1012
1013 /* add to uprobes_tree, sorted on inode:offset */
1014 cur_uprobe = insert_uprobe(uprobe);
1015 /* a uprobe exists for this inode:offset combination */
1016 if (cur_uprobe != uprobe) {
1017 if (cur_uprobe->ref_ctr_offset != uprobe->ref_ctr_offset) {
1018 ref_ctr_mismatch_warn(cur_uprobe, uprobe);
1019 put_uprobe(cur_uprobe);
1020 kfree(uprobe);
1021 return ERR_PTR(-EINVAL);
1022 }
1023 kfree(uprobe);
1024 uprobe = cur_uprobe;
1025 }
1026
1027 return uprobe;
1028 }
1029
consumer_add(struct uprobe * uprobe,struct uprobe_consumer * uc)1030 static void consumer_add(struct uprobe *uprobe, struct uprobe_consumer *uc)
1031 {
1032 static atomic64_t id;
1033
1034 down_write(&uprobe->consumer_rwsem);
1035 list_add_rcu(&uc->cons_node, &uprobe->consumers);
1036 uc->id = (__u64) atomic64_inc_return(&id);
1037 up_write(&uprobe->consumer_rwsem);
1038 }
1039
1040 /*
1041 * For uprobe @uprobe, delete the consumer @uc.
1042 * Should never be called with consumer that's not part of @uprobe->consumers.
1043 */
consumer_del(struct uprobe * uprobe,struct uprobe_consumer * uc)1044 static void consumer_del(struct uprobe *uprobe, struct uprobe_consumer *uc)
1045 {
1046 down_write(&uprobe->consumer_rwsem);
1047 list_del_rcu(&uc->cons_node);
1048 up_write(&uprobe->consumer_rwsem);
1049 }
1050
__copy_insn(struct address_space * mapping,struct file * filp,void * insn,int nbytes,loff_t offset)1051 static int __copy_insn(struct address_space *mapping, struct file *filp,
1052 void *insn, int nbytes, loff_t offset)
1053 {
1054 struct page *page;
1055 /*
1056 * Ensure that the page that has the original instruction is populated
1057 * and in page-cache. If ->read_folio == NULL it must be shmem_mapping(),
1058 * see uprobe_register().
1059 */
1060 if (mapping->a_ops->read_folio)
1061 page = read_mapping_page(mapping, offset >> PAGE_SHIFT, filp);
1062 else
1063 page = shmem_read_mapping_page(mapping, offset >> PAGE_SHIFT);
1064 if (IS_ERR(page))
1065 return PTR_ERR(page);
1066
1067 uprobe_copy_from_page(page, offset, insn, nbytes);
1068 put_page(page);
1069
1070 return 0;
1071 }
1072
copy_insn(struct uprobe * uprobe,struct file * filp)1073 static int copy_insn(struct uprobe *uprobe, struct file *filp)
1074 {
1075 struct address_space *mapping = uprobe->inode->i_mapping;
1076 loff_t offs = uprobe->offset;
1077 void *insn = &uprobe->arch.insn;
1078 int size = sizeof(uprobe->arch.insn);
1079 int len, err = -EIO;
1080
1081 /* Copy only available bytes, -EIO if nothing was read */
1082 do {
1083 if (offs >= i_size_read(uprobe->inode))
1084 break;
1085
1086 len = min_t(int, size, PAGE_SIZE - (offs & ~PAGE_MASK));
1087 err = __copy_insn(mapping, filp, insn, len, offs);
1088 if (err)
1089 break;
1090
1091 insn += len;
1092 offs += len;
1093 size -= len;
1094 } while (size);
1095
1096 return err;
1097 }
1098
prepare_uprobe(struct uprobe * uprobe,struct file * file,struct mm_struct * mm,unsigned long vaddr)1099 static int prepare_uprobe(struct uprobe *uprobe, struct file *file,
1100 struct mm_struct *mm, unsigned long vaddr)
1101 {
1102 int ret = 0;
1103
1104 if (test_bit(UPROBE_COPY_INSN, &uprobe->flags))
1105 return ret;
1106
1107 /* TODO: move this into _register, until then we abuse this sem. */
1108 down_write(&uprobe->consumer_rwsem);
1109 if (test_bit(UPROBE_COPY_INSN, &uprobe->flags))
1110 goto out;
1111
1112 ret = copy_insn(uprobe, file);
1113 if (ret)
1114 goto out;
1115
1116 ret = -ENOTSUPP;
1117 if (is_trap_insn((uprobe_opcode_t *)&uprobe->arch.insn))
1118 goto out;
1119
1120 ret = arch_uprobe_analyze_insn(&uprobe->arch, mm, vaddr);
1121 if (ret)
1122 goto out;
1123
1124 smp_wmb(); /* pairs with the smp_rmb() in handle_swbp() */
1125 set_bit(UPROBE_COPY_INSN, &uprobe->flags);
1126
1127 out:
1128 up_write(&uprobe->consumer_rwsem);
1129
1130 return ret;
1131 }
1132
consumer_filter(struct uprobe_consumer * uc,struct mm_struct * mm)1133 static inline bool consumer_filter(struct uprobe_consumer *uc, struct mm_struct *mm)
1134 {
1135 return !uc->filter || uc->filter(uc, mm);
1136 }
1137
filter_chain(struct uprobe * uprobe,struct mm_struct * mm)1138 static bool filter_chain(struct uprobe *uprobe, struct mm_struct *mm)
1139 {
1140 struct uprobe_consumer *uc;
1141 bool ret = false;
1142
1143 down_read(&uprobe->consumer_rwsem);
1144 list_for_each_entry(uc, &uprobe->consumers, cons_node) {
1145 ret = consumer_filter(uc, mm);
1146 if (ret)
1147 break;
1148 }
1149 up_read(&uprobe->consumer_rwsem);
1150
1151 return ret;
1152 }
1153
install_breakpoint(struct uprobe * uprobe,struct vm_area_struct * vma,unsigned long vaddr)1154 static int install_breakpoint(struct uprobe *uprobe, struct vm_area_struct *vma,
1155 unsigned long vaddr)
1156 {
1157 struct mm_struct *mm = vma->vm_mm;
1158 bool first_uprobe;
1159 int ret;
1160
1161 ret = prepare_uprobe(uprobe, vma->vm_file, mm, vaddr);
1162 if (ret)
1163 return ret;
1164
1165 /*
1166 * set MMF_HAS_UPROBES in advance for uprobe_pre_sstep_notifier(),
1167 * the task can hit this breakpoint right after __replace_page().
1168 */
1169 first_uprobe = !mm_flags_test(MMF_HAS_UPROBES, mm);
1170 if (first_uprobe)
1171 mm_flags_set(MMF_HAS_UPROBES, mm);
1172
1173 ret = set_swbp(&uprobe->arch, vma, vaddr);
1174 if (!ret)
1175 mm_flags_clear(MMF_RECALC_UPROBES, mm);
1176 else if (first_uprobe)
1177 mm_flags_clear(MMF_HAS_UPROBES, mm);
1178
1179 return ret;
1180 }
1181
remove_breakpoint(struct uprobe * uprobe,struct vm_area_struct * vma,unsigned long vaddr)1182 static int remove_breakpoint(struct uprobe *uprobe, struct vm_area_struct *vma,
1183 unsigned long vaddr)
1184 {
1185 struct mm_struct *mm = vma->vm_mm;
1186
1187 mm_flags_set(MMF_RECALC_UPROBES, mm);
1188 return set_orig_insn(&uprobe->arch, vma, vaddr);
1189 }
1190
1191 struct map_info {
1192 struct map_info *next;
1193 struct mm_struct *mm;
1194 unsigned long vaddr;
1195 };
1196
free_map_info(struct map_info * info)1197 static inline struct map_info *free_map_info(struct map_info *info)
1198 {
1199 struct map_info *next = info->next;
1200 kfree(info);
1201 return next;
1202 }
1203
1204 static struct map_info *
build_map_info(struct address_space * mapping,loff_t offset,bool is_register)1205 build_map_info(struct address_space *mapping, loff_t offset, bool is_register)
1206 {
1207 unsigned long pgoff = offset >> PAGE_SHIFT;
1208 struct vm_area_struct *vma;
1209 struct map_info *curr = NULL;
1210 struct map_info *prev = NULL;
1211 struct map_info *info;
1212 int more = 0;
1213
1214 again:
1215 i_mmap_lock_read(mapping);
1216 mapping_rmap_tree_foreach(vma, mapping, pgoff, pgoff) {
1217 if (!valid_vma(vma, is_register))
1218 continue;
1219
1220 if (!prev && !more) {
1221 /*
1222 * Needs GFP_NOWAIT to avoid i_mmap_rwsem recursion through
1223 * reclaim. This is optimistic, no harm done if it fails.
1224 */
1225 prev = kmalloc_obj(struct map_info,
1226 GFP_NOWAIT | __GFP_NOMEMALLOC);
1227 if (prev)
1228 prev->next = NULL;
1229 }
1230 if (!prev) {
1231 more++;
1232 continue;
1233 }
1234
1235 if (!mmget_not_zero(vma->vm_mm))
1236 continue;
1237
1238 info = prev;
1239 prev = prev->next;
1240 info->next = curr;
1241 curr = info;
1242
1243 info->mm = vma->vm_mm;
1244 info->vaddr = offset_to_vaddr(vma, offset);
1245 }
1246 i_mmap_unlock_read(mapping);
1247
1248 if (!more)
1249 goto out;
1250
1251 prev = curr;
1252 while (curr) {
1253 mmput(curr->mm);
1254 curr = curr->next;
1255 }
1256
1257 do {
1258 info = kmalloc_obj(struct map_info);
1259 if (!info) {
1260 curr = ERR_PTR(-ENOMEM);
1261 goto out;
1262 }
1263 info->next = prev;
1264 prev = info;
1265 } while (--more);
1266
1267 goto again;
1268 out:
1269 while (prev)
1270 prev = free_map_info(prev);
1271 return curr;
1272 }
1273
1274 static int
register_for_each_vma(struct uprobe * uprobe,struct uprobe_consumer * new)1275 register_for_each_vma(struct uprobe *uprobe, struct uprobe_consumer *new)
1276 {
1277 bool is_register = !!new;
1278 struct map_info *info;
1279 int err = 0;
1280
1281 percpu_down_write(&dup_mmap_sem);
1282 info = build_map_info(uprobe->inode->i_mapping,
1283 uprobe->offset, is_register);
1284 if (IS_ERR(info)) {
1285 err = PTR_ERR(info);
1286 goto out;
1287 }
1288
1289 while (info) {
1290 struct mm_struct *mm = info->mm;
1291 struct vm_area_struct *vma;
1292
1293 if (err && is_register)
1294 goto free;
1295 /*
1296 * We take mmap_lock for writing to avoid the race with
1297 * find_active_uprobe_rcu() which takes mmap_lock for reading.
1298 * Thus this install_breakpoint() can not make
1299 * is_trap_at_addr() true right after find_uprobe_rcu()
1300 * returns NULL in find_active_uprobe_rcu().
1301 */
1302 mmap_write_lock(mm);
1303 if (check_stable_address_space(mm))
1304 goto unlock;
1305
1306 vma = find_vma(mm, info->vaddr);
1307 if (!vma || !valid_vma(vma, is_register) ||
1308 file_inode(vma->vm_file) != uprobe->inode)
1309 goto unlock;
1310
1311 if (vma->vm_start > info->vaddr ||
1312 vaddr_to_offset(vma, info->vaddr) != uprobe->offset)
1313 goto unlock;
1314
1315 if (is_register) {
1316 /* consult only the "caller", new consumer. */
1317 if (consumer_filter(new, mm))
1318 err = install_breakpoint(uprobe, vma, info->vaddr);
1319 } else if (mm_flags_test(MMF_HAS_UPROBES, mm)) {
1320 if (!filter_chain(uprobe, mm))
1321 err |= remove_breakpoint(uprobe, vma, info->vaddr);
1322 }
1323
1324 unlock:
1325 mmap_write_unlock(mm);
1326 free:
1327 mmput(mm);
1328 info = free_map_info(info);
1329 }
1330 out:
1331 percpu_up_write(&dup_mmap_sem);
1332 return err;
1333 }
1334
1335 /**
1336 * uprobe_unregister_nosync - unregister an already registered probe.
1337 * @uprobe: uprobe to remove
1338 * @uc: identify which probe if multiple probes are colocated.
1339 */
uprobe_unregister_nosync(struct uprobe * uprobe,struct uprobe_consumer * uc)1340 void uprobe_unregister_nosync(struct uprobe *uprobe, struct uprobe_consumer *uc)
1341 {
1342 int err;
1343
1344 down_write(&uprobe->register_rwsem);
1345 consumer_del(uprobe, uc);
1346 err = register_for_each_vma(uprobe, NULL);
1347 up_write(&uprobe->register_rwsem);
1348
1349 /* TODO : cant unregister? schedule a worker thread */
1350 if (unlikely(err)) {
1351 uprobe_warn(current, "unregister, leaking uprobe");
1352 return;
1353 }
1354
1355 put_uprobe(uprobe);
1356 }
1357 EXPORT_SYMBOL_GPL(uprobe_unregister_nosync);
1358
uprobe_unregister_sync(void)1359 void uprobe_unregister_sync(void)
1360 {
1361 /*
1362 * Now that handler_chain() and handle_uretprobe_chain() iterate over
1363 * uprobe->consumers list under RCU protection without holding
1364 * uprobe->register_rwsem, we need to wait for RCU grace period to
1365 * make sure that we can't call into just unregistered
1366 * uprobe_consumer's callbacks anymore. If we don't do that, fast and
1367 * unlucky enough caller can free consumer's memory and cause
1368 * handler_chain() or handle_uretprobe_chain() to do an use-after-free.
1369 */
1370 synchronize_rcu_tasks_trace();
1371 synchronize_srcu(&uretprobes_srcu);
1372 }
1373 EXPORT_SYMBOL_GPL(uprobe_unregister_sync);
1374
1375 /**
1376 * uprobe_register - register a probe
1377 * @inode: the file in which the probe has to be placed.
1378 * @offset: offset from the start of the file.
1379 * @ref_ctr_offset: offset of SDT marker / reference counter
1380 * @uc: information on howto handle the probe..
1381 *
1382 * Apart from the access refcount, uprobe_register() takes a creation
1383 * refcount (thro alloc_uprobe) if and only if this @uprobe is getting
1384 * inserted into the rbtree (i.e first consumer for a @inode:@offset
1385 * tuple). Creation refcount stops uprobe_unregister from freeing the
1386 * @uprobe even before the register operation is complete. Creation
1387 * refcount is released when the last @uc for the @uprobe
1388 * unregisters. Caller of uprobe_register() is required to keep @inode
1389 * (and the containing mount) referenced.
1390 *
1391 * Return: pointer to the new uprobe on success or an ERR_PTR on failure.
1392 */
uprobe_register(struct inode * inode,loff_t offset,loff_t ref_ctr_offset,struct uprobe_consumer * uc)1393 struct uprobe *uprobe_register(struct inode *inode,
1394 loff_t offset, loff_t ref_ctr_offset,
1395 struct uprobe_consumer *uc)
1396 {
1397 struct uprobe *uprobe;
1398 int ret;
1399
1400 /* Uprobe must have at least one set consumer */
1401 if (!uc->handler && !uc->ret_handler)
1402 return ERR_PTR(-EINVAL);
1403
1404 /* copy_insn() uses read_mapping_page() or shmem_read_mapping_page() */
1405 if (!inode->i_mapping->a_ops->read_folio &&
1406 !shmem_mapping(inode->i_mapping))
1407 return ERR_PTR(-EIO);
1408 /* Racy, just to catch the obvious mistakes */
1409 if (offset > i_size_read(inode))
1410 return ERR_PTR(-EINVAL);
1411
1412 /*
1413 * This ensures that uprobe_copy_from_page(), copy_to_page() and
1414 * __update_ref_ctr() can't cross page boundary.
1415 */
1416 if (!IS_ALIGNED(offset, UPROBE_SWBP_INSN_SIZE))
1417 return ERR_PTR(-EINVAL);
1418 if (!IS_ALIGNED(ref_ctr_offset, sizeof(short)))
1419 return ERR_PTR(-EINVAL);
1420
1421 uprobe = alloc_uprobe(inode, offset, ref_ctr_offset);
1422 if (IS_ERR(uprobe))
1423 return uprobe;
1424
1425 down_write(&uprobe->register_rwsem);
1426 consumer_add(uprobe, uc);
1427 ret = register_for_each_vma(uprobe, uc);
1428 up_write(&uprobe->register_rwsem);
1429
1430 if (ret) {
1431 uprobe_unregister_nosync(uprobe, uc);
1432 /*
1433 * Registration might have partially succeeded, so we can have
1434 * this consumer being called right at this time. We need to
1435 * sync here. It's ok, it's unlikely slow path.
1436 */
1437 uprobe_unregister_sync();
1438 return ERR_PTR(ret);
1439 }
1440
1441 return uprobe;
1442 }
1443 EXPORT_SYMBOL_GPL(uprobe_register);
1444
1445 /**
1446 * uprobe_apply - add or remove the breakpoints according to @uc->filter
1447 * @uprobe: uprobe which "owns" the breakpoint
1448 * @uc: consumer which wants to add more or remove some breakpoints
1449 * @add: add or remove the breakpoints
1450 * Return: 0 on success or negative error code.
1451 */
uprobe_apply(struct uprobe * uprobe,struct uprobe_consumer * uc,bool add)1452 int uprobe_apply(struct uprobe *uprobe, struct uprobe_consumer *uc, bool add)
1453 {
1454 struct uprobe_consumer *con;
1455 int ret = -ENOENT;
1456
1457 down_write(&uprobe->register_rwsem);
1458
1459 rcu_read_lock_trace();
1460 list_for_each_entry_rcu(con, &uprobe->consumers, cons_node, rcu_read_lock_trace_held()) {
1461 if (con == uc) {
1462 ret = register_for_each_vma(uprobe, add ? uc : NULL);
1463 break;
1464 }
1465 }
1466 rcu_read_unlock_trace();
1467
1468 up_write(&uprobe->register_rwsem);
1469
1470 return ret;
1471 }
1472
unapply_uprobe(struct uprobe * uprobe,struct mm_struct * mm)1473 static int unapply_uprobe(struct uprobe *uprobe, struct mm_struct *mm)
1474 {
1475 VMA_ITERATOR(vmi, mm, 0);
1476 struct vm_area_struct *vma;
1477 int err = 0;
1478
1479 mmap_write_lock(mm);
1480 for_each_vma(vmi, vma) {
1481 unsigned long vaddr;
1482 loff_t offset;
1483
1484 if (!valid_vma(vma, false) ||
1485 file_inode(vma->vm_file) != uprobe->inode)
1486 continue;
1487
1488 offset = (loff_t)vma_start_pgoff(vma) << PAGE_SHIFT;
1489 if (uprobe->offset < offset ||
1490 uprobe->offset >= offset + vma->vm_end - vma->vm_start)
1491 continue;
1492
1493 vaddr = offset_to_vaddr(vma, uprobe->offset);
1494 err |= remove_breakpoint(uprobe, vma, vaddr);
1495 }
1496 mmap_write_unlock(mm);
1497
1498 return err;
1499 }
1500
1501 static struct rb_node *
find_node_in_range(struct inode * inode,loff_t min,loff_t max)1502 find_node_in_range(struct inode *inode, loff_t min, loff_t max)
1503 {
1504 struct rb_node *n = uprobes_tree.rb_node;
1505
1506 while (n) {
1507 struct uprobe *u = rb_entry(n, struct uprobe, rb_node);
1508
1509 if (inode < u->inode) {
1510 n = n->rb_left;
1511 } else if (inode > u->inode) {
1512 n = n->rb_right;
1513 } else {
1514 if (max < u->offset)
1515 n = n->rb_left;
1516 else if (min > u->offset)
1517 n = n->rb_right;
1518 else
1519 break;
1520 }
1521 }
1522
1523 return n;
1524 }
1525
1526 /*
1527 * For a given range in vma, build a list of probes that need to be inserted.
1528 */
build_probe_list(struct inode * inode,struct vm_area_struct * vma,unsigned long start,unsigned long end,struct list_head * head)1529 static void build_probe_list(struct inode *inode,
1530 struct vm_area_struct *vma,
1531 unsigned long start, unsigned long end,
1532 struct list_head *head)
1533 {
1534 loff_t min, max;
1535 struct rb_node *n, *t;
1536 struct uprobe *u;
1537
1538 INIT_LIST_HEAD(head);
1539 min = vaddr_to_offset(vma, start);
1540 max = min + (end - start) - 1;
1541
1542 read_lock(&uprobes_treelock);
1543 n = find_node_in_range(inode, min, max);
1544 if (n) {
1545 for (t = n; t; t = rb_prev(t)) {
1546 u = rb_entry(t, struct uprobe, rb_node);
1547 if (u->inode != inode || u->offset < min)
1548 break;
1549 /* if uprobe went away, it's safe to ignore it */
1550 if (try_get_uprobe(u))
1551 list_add(&u->pending_list, head);
1552 }
1553 for (t = n; (t = rb_next(t)); ) {
1554 u = rb_entry(t, struct uprobe, rb_node);
1555 if (u->inode != inode || u->offset > max)
1556 break;
1557 /* if uprobe went away, it's safe to ignore it */
1558 if (try_get_uprobe(u))
1559 list_add(&u->pending_list, head);
1560 }
1561 }
1562 read_unlock(&uprobes_treelock);
1563 }
1564
1565 /* @vma contains reference counter, not the probed instruction. */
delayed_ref_ctr_inc(struct vm_area_struct * vma)1566 static int delayed_ref_ctr_inc(struct vm_area_struct *vma)
1567 {
1568 struct list_head *pos, *q;
1569 struct delayed_uprobe *du;
1570 unsigned long vaddr;
1571 int ret = 0, err = 0;
1572
1573 mutex_lock(&delayed_uprobe_lock);
1574 list_for_each_safe(pos, q, &delayed_uprobe_list) {
1575 du = list_entry(pos, struct delayed_uprobe, list);
1576
1577 if (du->mm != vma->vm_mm ||
1578 !valid_ref_ctr_vma(du->uprobe, vma))
1579 continue;
1580
1581 vaddr = offset_to_vaddr(vma, du->uprobe->ref_ctr_offset);
1582 ret = __update_ref_ctr(vma->vm_mm, vaddr, 1);
1583 if (ret) {
1584 update_ref_ctr_warn(du->uprobe, vma->vm_mm, 1);
1585 if (!err)
1586 err = ret;
1587 }
1588 delayed_uprobe_delete(du);
1589 }
1590 mutex_unlock(&delayed_uprobe_lock);
1591 return err;
1592 }
1593
1594 /*
1595 * Called from mmap_region/vma_merge with mm->mmap_lock acquired.
1596 *
1597 * Currently we ignore all errors and always return 0, the callers
1598 * can't handle the failure anyway.
1599 */
uprobe_mmap(struct vm_area_struct * vma)1600 int uprobe_mmap(struct vm_area_struct *vma)
1601 {
1602 struct list_head tmp_list;
1603 struct uprobe *uprobe, *u;
1604 struct inode *inode;
1605
1606 if (no_uprobe_events())
1607 return 0;
1608
1609 if (vma->vm_file &&
1610 (vma->vm_flags & (VM_WRITE|VM_SHARED)) == VM_WRITE &&
1611 mm_flags_test(MMF_HAS_UPROBES, vma->vm_mm))
1612 delayed_ref_ctr_inc(vma);
1613
1614 if (!valid_vma(vma, true))
1615 return 0;
1616
1617 inode = file_inode(vma->vm_file);
1618 if (!inode)
1619 return 0;
1620
1621 mutex_lock(uprobes_mmap_hash(inode));
1622 build_probe_list(inode, vma, vma->vm_start, vma->vm_end, &tmp_list);
1623 /*
1624 * We can race with uprobe_unregister(), this uprobe can be already
1625 * removed. But in this case filter_chain() must return false, all
1626 * consumers have gone away.
1627 */
1628 list_for_each_entry_safe(uprobe, u, &tmp_list, pending_list) {
1629 if (!fatal_signal_pending(current) &&
1630 filter_chain(uprobe, vma->vm_mm)) {
1631 unsigned long vaddr = offset_to_vaddr(vma, uprobe->offset);
1632 install_breakpoint(uprobe, vma, vaddr);
1633 }
1634 put_uprobe(uprobe);
1635 }
1636 mutex_unlock(uprobes_mmap_hash(inode));
1637
1638 return 0;
1639 }
1640
1641 static bool
vma_has_uprobes(struct vm_area_struct * vma,unsigned long start,unsigned long end)1642 vma_has_uprobes(struct vm_area_struct *vma, unsigned long start, unsigned long end)
1643 {
1644 loff_t min, max;
1645 struct inode *inode;
1646 struct rb_node *n;
1647
1648 inode = file_inode(vma->vm_file);
1649
1650 min = vaddr_to_offset(vma, start);
1651 max = min + (end - start) - 1;
1652
1653 read_lock(&uprobes_treelock);
1654 n = find_node_in_range(inode, min, max);
1655 read_unlock(&uprobes_treelock);
1656
1657 return !!n;
1658 }
1659
1660 /*
1661 * Called in context of a munmap of a vma.
1662 */
uprobe_munmap(struct vm_area_struct * vma,unsigned long start,unsigned long end)1663 void uprobe_munmap(struct vm_area_struct *vma, unsigned long start, unsigned long end)
1664 {
1665 if (no_uprobe_events() || !valid_vma(vma, false))
1666 return;
1667
1668 if (!atomic_read(&vma->vm_mm->mm_users)) /* called by mmput() ? */
1669 return;
1670
1671 if (!mm_flags_test(MMF_HAS_UPROBES, vma->vm_mm) ||
1672 mm_flags_test(MMF_RECALC_UPROBES, vma->vm_mm))
1673 return;
1674
1675 if (vma_has_uprobes(vma, start, end))
1676 mm_flags_set(MMF_RECALC_UPROBES, vma->vm_mm);
1677 }
1678
xol_fault(const struct vm_special_mapping * sm,struct vm_area_struct * vma,struct vm_fault * vmf)1679 static vm_fault_t xol_fault(const struct vm_special_mapping *sm,
1680 struct vm_area_struct *vma, struct vm_fault *vmf)
1681 {
1682 struct xol_area *area = vma->vm_mm->uprobes_state.xol_area;
1683
1684 vmf->page = area->page;
1685 get_page(vmf->page);
1686 return 0;
1687 }
1688
xol_mremap(const struct vm_special_mapping * sm,struct vm_area_struct * new_vma)1689 static int xol_mremap(const struct vm_special_mapping *sm, struct vm_area_struct *new_vma)
1690 {
1691 return -EPERM;
1692 }
1693
1694 static const struct vm_special_mapping xol_mapping = {
1695 .name = "[uprobes]",
1696 .fault = xol_fault,
1697 .mremap = xol_mremap,
1698 };
1699
arch_uprobe_get_xol_area(void)1700 unsigned long __weak arch_uprobe_get_xol_area(void)
1701 {
1702 /* Try to map as high as possible, this is only a hint. */
1703 return get_unmapped_area(NULL, TASK_SIZE - PAGE_SIZE, PAGE_SIZE, 0, 0);
1704 }
1705
1706 /* Slot allocation for XOL */
xol_add_vma(struct mm_struct * mm,struct xol_area * area)1707 static int xol_add_vma(struct mm_struct *mm, struct xol_area *area)
1708 {
1709 struct vm_area_struct *vma;
1710 int ret;
1711
1712 if (mmap_write_lock_killable(mm))
1713 return -EINTR;
1714
1715 if (mm->uprobes_state.xol_area) {
1716 ret = -EALREADY;
1717 goto fail;
1718 }
1719
1720 if (!area->vaddr) {
1721 area->vaddr = arch_uprobe_get_xol_area();
1722 if (IS_ERR_VALUE(area->vaddr)) {
1723 ret = area->vaddr;
1724 goto fail;
1725 }
1726 }
1727
1728 vma = _install_special_mapping(mm, area->vaddr, PAGE_SIZE,
1729 VM_EXEC|VM_MAYEXEC|VM_DONTCOPY|VM_IO|
1730 VM_SEALED_SYSMAP,
1731 &xol_mapping);
1732 if (IS_ERR(vma)) {
1733 ret = PTR_ERR(vma);
1734 goto fail;
1735 }
1736
1737 ret = 0;
1738 /* pairs with get_xol_area() */
1739 smp_store_release(&mm->uprobes_state.xol_area, area); /* ^^^ */
1740 fail:
1741 mmap_write_unlock(mm);
1742
1743 return ret;
1744 }
1745
arch_uretprobe_trampoline(unsigned long * psize)1746 void * __weak arch_uretprobe_trampoline(unsigned long *psize)
1747 {
1748 static uprobe_opcode_t insn = UPROBE_SWBP_INSN;
1749
1750 *psize = UPROBE_SWBP_INSN_SIZE;
1751 return &insn;
1752 }
1753
__create_xol_area(unsigned long vaddr)1754 static struct xol_area *__create_xol_area(unsigned long vaddr)
1755 {
1756 struct mm_struct *mm = current->mm;
1757 unsigned long insns_size;
1758 struct xol_area *area;
1759 void *insns;
1760
1761 area = kzalloc_obj(*area);
1762 if (unlikely(!area))
1763 goto out;
1764
1765 area->bitmap = kcalloc(BITS_TO_LONGS(UINSNS_PER_PAGE), sizeof(long),
1766 GFP_KERNEL);
1767 if (!area->bitmap)
1768 goto free_area;
1769
1770 area->page = alloc_page(GFP_HIGHUSER | __GFP_ZERO);
1771 if (!area->page)
1772 goto free_bitmap;
1773
1774 area->vaddr = vaddr;
1775 init_waitqueue_head(&area->wq);
1776 /* Reserve the 1st slot for get_trampoline_vaddr() */
1777 set_bit(0, area->bitmap);
1778 insns = arch_uretprobe_trampoline(&insns_size);
1779 arch_uprobe_copy_ixol(area->page, 0, insns, insns_size);
1780
1781 if (!xol_add_vma(mm, area))
1782 return area;
1783
1784 __free_page(area->page);
1785 free_bitmap:
1786 kfree(area->bitmap);
1787 free_area:
1788 kfree(area);
1789 out:
1790 return NULL;
1791 }
1792
1793 /*
1794 * get_xol_area - Allocate process's xol_area if necessary.
1795 * This area will be used for storing instructions for execution out of line.
1796 *
1797 * Returns the allocated area or NULL.
1798 */
get_xol_area(void)1799 static struct xol_area *get_xol_area(void)
1800 {
1801 struct mm_struct *mm = current->mm;
1802 struct xol_area *area;
1803
1804 if (!mm->uprobes_state.xol_area)
1805 __create_xol_area(0);
1806
1807 /* Pairs with xol_add_vma() smp_store_release() */
1808 area = READ_ONCE(mm->uprobes_state.xol_area); /* ^^^ */
1809 return area;
1810 }
1811
1812 /*
1813 * uprobe_clear_state - Free the area allocated for slots.
1814 */
uprobe_clear_state(struct mm_struct * mm)1815 void uprobe_clear_state(struct mm_struct *mm)
1816 {
1817 struct xol_area *area = mm->uprobes_state.xol_area;
1818
1819 mutex_lock(&delayed_uprobe_lock);
1820 delayed_uprobe_remove(NULL, mm);
1821 mutex_unlock(&delayed_uprobe_lock);
1822
1823 if (!area)
1824 return;
1825
1826 put_page(area->page);
1827 kfree(area->bitmap);
1828 kfree(area);
1829 }
1830
uprobe_start_dup_mmap(void)1831 void uprobe_start_dup_mmap(void)
1832 {
1833 percpu_down_read(&dup_mmap_sem);
1834 }
1835
uprobe_end_dup_mmap(void)1836 void uprobe_end_dup_mmap(void)
1837 {
1838 percpu_up_read(&dup_mmap_sem);
1839 }
1840
uprobe_dup_mmap(struct mm_struct * oldmm,struct mm_struct * newmm)1841 void uprobe_dup_mmap(struct mm_struct *oldmm, struct mm_struct *newmm)
1842 {
1843 if (mm_flags_test(MMF_HAS_UPROBES, oldmm)) {
1844 mm_flags_set(MMF_HAS_UPROBES, newmm);
1845 /* unconditionally, dup_mmap() skips VM_DONTCOPY vmas */
1846 mm_flags_set(MMF_RECALC_UPROBES, newmm);
1847 }
1848 }
1849
xol_get_slot_nr(struct xol_area * area)1850 static unsigned long xol_get_slot_nr(struct xol_area *area)
1851 {
1852 unsigned long slot_nr;
1853
1854 slot_nr = find_first_zero_bit(area->bitmap, UINSNS_PER_PAGE);
1855 if (slot_nr < UINSNS_PER_PAGE) {
1856 if (!test_and_set_bit(slot_nr, area->bitmap))
1857 return slot_nr;
1858 }
1859
1860 return UINSNS_PER_PAGE;
1861 }
1862
1863 /*
1864 * xol_get_insn_slot - allocate a slot for xol.
1865 */
xol_get_insn_slot(struct uprobe * uprobe,struct uprobe_task * utask)1866 static bool xol_get_insn_slot(struct uprobe *uprobe, struct uprobe_task *utask)
1867 {
1868 struct xol_area *area = get_xol_area();
1869 unsigned long slot_nr;
1870
1871 if (!area)
1872 return false;
1873
1874 wait_event(area->wq, (slot_nr = xol_get_slot_nr(area)) < UINSNS_PER_PAGE);
1875
1876 utask->xol_vaddr = area->vaddr + slot_nr * UPROBE_XOL_SLOT_BYTES;
1877 arch_uprobe_copy_ixol(area->page, utask->xol_vaddr,
1878 &uprobe->arch.ixol, sizeof(uprobe->arch.ixol));
1879 return true;
1880 }
1881
1882 /*
1883 * xol_free_insn_slot - free the slot allocated by xol_get_insn_slot()
1884 */
xol_free_insn_slot(struct uprobe_task * utask)1885 static void xol_free_insn_slot(struct uprobe_task *utask)
1886 {
1887 struct xol_area *area = current->mm->uprobes_state.xol_area;
1888 unsigned long offset = utask->xol_vaddr - area->vaddr;
1889 unsigned int slot_nr;
1890
1891 utask->xol_vaddr = 0;
1892 /* xol_vaddr must fit into [area->vaddr, area->vaddr + PAGE_SIZE) */
1893 if (WARN_ON_ONCE(offset >= PAGE_SIZE))
1894 return;
1895
1896 slot_nr = offset / UPROBE_XOL_SLOT_BYTES;
1897 clear_bit(slot_nr, area->bitmap);
1898 smp_mb__after_atomic(); /* pairs with prepare_to_wait() */
1899 if (waitqueue_active(&area->wq))
1900 wake_up(&area->wq);
1901 }
1902
arch_uprobe_copy_ixol(struct page * page,unsigned long vaddr,void * src,unsigned long len)1903 void __weak arch_uprobe_copy_ixol(struct page *page, unsigned long vaddr,
1904 void *src, unsigned long len)
1905 {
1906 /* Initialize the slot */
1907 copy_to_page(page, vaddr, src, len);
1908
1909 /*
1910 * We probably need flush_icache_user_page() but it needs vma.
1911 * This should work on most of architectures by default. If
1912 * architecture needs to do something different it can define
1913 * its own version of the function.
1914 */
1915 flush_dcache_page(page);
1916 }
1917
1918 /**
1919 * uprobe_get_swbp_addr - compute address of swbp given post-swbp regs
1920 * @regs: Reflects the saved state of the task after it has hit a breakpoint
1921 * instruction.
1922 * Return the address of the breakpoint instruction.
1923 */
uprobe_get_swbp_addr(struct pt_regs * regs)1924 unsigned long __weak uprobe_get_swbp_addr(struct pt_regs *regs)
1925 {
1926 return instruction_pointer(regs) - UPROBE_SWBP_INSN_SIZE;
1927 }
1928
uprobe_get_trap_addr(struct pt_regs * regs)1929 unsigned long uprobe_get_trap_addr(struct pt_regs *regs)
1930 {
1931 struct uprobe_task *utask = current->utask;
1932
1933 if (unlikely(utask && utask->active_uprobe))
1934 return utask->vaddr;
1935
1936 return instruction_pointer(regs);
1937 }
1938
ri_pool_push(struct uprobe_task * utask,struct return_instance * ri)1939 static void ri_pool_push(struct uprobe_task *utask, struct return_instance *ri)
1940 {
1941 ri->cons_cnt = 0;
1942 ri->next = utask->ri_pool;
1943 utask->ri_pool = ri;
1944 }
1945
ri_pool_pop(struct uprobe_task * utask)1946 static struct return_instance *ri_pool_pop(struct uprobe_task *utask)
1947 {
1948 struct return_instance *ri = utask->ri_pool;
1949
1950 if (likely(ri))
1951 utask->ri_pool = ri->next;
1952
1953 return ri;
1954 }
1955
ri_free(struct return_instance * ri)1956 static void ri_free(struct return_instance *ri)
1957 {
1958 kfree(ri->extra_consumers);
1959 kfree_rcu(ri, rcu);
1960 }
1961
free_ret_instance(struct uprobe_task * utask,struct return_instance * ri,bool cleanup_hprobe)1962 static void free_ret_instance(struct uprobe_task *utask,
1963 struct return_instance *ri, bool cleanup_hprobe)
1964 {
1965 unsigned seq;
1966
1967 if (cleanup_hprobe) {
1968 enum hprobe_state hstate;
1969
1970 (void)hprobe_consume(&ri->hprobe, &hstate);
1971 hprobe_finalize(&ri->hprobe, hstate);
1972 }
1973
1974 /*
1975 * At this point return_instance is unlinked from utask's
1976 * return_instances list and this has become visible to ri_timer().
1977 * If seqcount now indicates that ri_timer's return instance
1978 * processing loop isn't active, we can return ri into the pool of
1979 * to-be-reused return instances for future uretprobes. If ri_timer()
1980 * happens to be running right now, though, we fallback to safety and
1981 * just perform RCU-delated freeing of ri.
1982 * Admittedly, this is a rather simple use of seqcount, but it nicely
1983 * abstracts away all the necessary memory barriers, so we use
1984 * a well-supported kernel primitive here.
1985 */
1986 if (raw_seqcount_try_begin(&utask->ri_seqcount, seq)) {
1987 /* immediate reuse of ri without RCU GP is OK */
1988 ri_pool_push(utask, ri);
1989 } else {
1990 /* we might be racing with ri_timer(), so play it safe */
1991 ri_free(ri);
1992 }
1993 }
1994
1995 /*
1996 * Called with no locks held.
1997 * Called in context of an exiting or an exec-ing thread.
1998 */
uprobe_free_utask(struct task_struct * t)1999 void uprobe_free_utask(struct task_struct *t)
2000 {
2001 struct uprobe_task *utask = t->utask;
2002 struct return_instance *ri, *ri_next;
2003
2004 if (!utask)
2005 return;
2006
2007 t->utask = NULL;
2008 WARN_ON_ONCE(utask->active_uprobe || utask->xol_vaddr);
2009
2010 timer_delete_sync(&utask->ri_timer);
2011
2012 ri = utask->return_instances;
2013 while (ri) {
2014 ri_next = ri->next;
2015 free_ret_instance(utask, ri, true /* cleanup_hprobe */);
2016 ri = ri_next;
2017 }
2018
2019 /* free_ret_instance() above might add to ri_pool, so this loop should come last */
2020 ri = utask->ri_pool;
2021 while (ri) {
2022 ri_next = ri->next;
2023 ri_free(ri);
2024 ri = ri_next;
2025 }
2026
2027 kfree(utask);
2028 }
2029
2030 #define RI_TIMER_PERIOD (HZ / 10) /* 100 ms */
2031
2032 #define for_each_ret_instance_rcu(pos, head) \
2033 for (pos = rcu_dereference_raw(head); pos; pos = rcu_dereference_raw(pos->next))
2034
ri_timer(struct timer_list * timer)2035 static void ri_timer(struct timer_list *timer)
2036 {
2037 struct uprobe_task *utask = container_of(timer, struct uprobe_task, ri_timer);
2038 struct return_instance *ri;
2039
2040 /* SRCU protects uprobe from reuse for the cmpxchg() inside hprobe_expire(). */
2041 guard(srcu_fast_updown)(&uretprobes_srcu);
2042 /* RCU protects return_instance from freeing. */
2043 guard(rcu)();
2044
2045 /*
2046 * See free_ret_instance() for notes on seqcount use.
2047 * We also employ raw API variants to avoid lockdep false-positive
2048 * warning complaining about enabled preemption. The timer can only be
2049 * invoked once for a uprobe_task. Therefore there can only be one
2050 * writer. The reader does not require an even sequence count to make
2051 * progress, so it is OK to remain preemptible on PREEMPT_RT.
2052 */
2053 raw_write_seqcount_begin(&utask->ri_seqcount);
2054
2055 for_each_ret_instance_rcu(ri, utask->return_instances)
2056 hprobe_expire(&ri->hprobe, false);
2057
2058 raw_write_seqcount_end(&utask->ri_seqcount);
2059 }
2060
alloc_utask(void)2061 static struct uprobe_task *alloc_utask(void)
2062 {
2063 struct uprobe_task *utask;
2064
2065 utask = kzalloc_obj(*utask);
2066 if (!utask)
2067 return NULL;
2068
2069 timer_setup(&utask->ri_timer, ri_timer, 0);
2070 seqcount_init(&utask->ri_seqcount);
2071
2072 return utask;
2073 }
2074
2075 /*
2076 * Allocate a uprobe_task object for the task if necessary.
2077 * Called when the thread hits a breakpoint.
2078 *
2079 * Returns:
2080 * - pointer to new uprobe_task on success
2081 * - NULL otherwise
2082 */
get_utask(void)2083 static struct uprobe_task *get_utask(void)
2084 {
2085 if (!current->utask)
2086 current->utask = alloc_utask();
2087 return current->utask;
2088 }
2089
alloc_return_instance(struct uprobe_task * utask)2090 static struct return_instance *alloc_return_instance(struct uprobe_task *utask)
2091 {
2092 struct return_instance *ri;
2093
2094 ri = ri_pool_pop(utask);
2095 if (ri)
2096 return ri;
2097
2098 ri = kzalloc_obj(*ri);
2099 if (!ri)
2100 return ZERO_SIZE_PTR;
2101
2102 return ri;
2103 }
2104
dup_return_instance(struct return_instance * old)2105 static struct return_instance *dup_return_instance(struct return_instance *old)
2106 {
2107 struct return_instance *ri;
2108
2109 ri = kmemdup(old, sizeof(*ri), GFP_KERNEL);
2110 if (!ri)
2111 return NULL;
2112
2113 if (unlikely(old->cons_cnt > 1)) {
2114 ri->extra_consumers = kmemdup(old->extra_consumers,
2115 sizeof(ri->extra_consumers[0]) * (old->cons_cnt - 1),
2116 GFP_KERNEL);
2117 if (!ri->extra_consumers) {
2118 kfree(ri);
2119 return NULL;
2120 }
2121 }
2122
2123 return ri;
2124 }
2125
dup_utask(struct task_struct * t,struct uprobe_task * o_utask)2126 static int dup_utask(struct task_struct *t, struct uprobe_task *o_utask)
2127 {
2128 struct uprobe_task *n_utask;
2129 struct return_instance **p, *o, *n;
2130 struct uprobe *uprobe;
2131
2132 n_utask = alloc_utask();
2133 if (!n_utask)
2134 return -ENOMEM;
2135 t->utask = n_utask;
2136
2137 /* protect uprobes from freeing, we'll need try_get_uprobe() them */
2138 guard(srcu_fast_updown)(&uretprobes_srcu);
2139
2140 p = &n_utask->return_instances;
2141 for (o = o_utask->return_instances; o; o = o->next) {
2142 n = dup_return_instance(o);
2143 if (!n)
2144 return -ENOMEM;
2145
2146 /* if uprobe is non-NULL, we'll have an extra refcount for uprobe */
2147 uprobe = hprobe_expire(&o->hprobe, true);
2148
2149 /*
2150 * New utask will have stable properly refcounted uprobe or
2151 * NULL. Even if we failed to get refcounted uprobe, we still
2152 * need to preserve full set of return_instances for proper
2153 * uretprobe handling and nesting in forked task.
2154 */
2155 hprobe_init_stable(&n->hprobe, uprobe);
2156
2157 n->next = NULL;
2158 rcu_assign_pointer(*p, n);
2159 p = &n->next;
2160
2161 n_utask->depth++;
2162 }
2163
2164 return 0;
2165 }
2166
dup_xol_work(struct callback_head * work)2167 static void dup_xol_work(struct callback_head *work)
2168 {
2169 if (current->flags & PF_EXITING)
2170 return;
2171
2172 if (!__create_xol_area(current->utask->dup_xol_addr) &&
2173 !fatal_signal_pending(current))
2174 uprobe_warn(current, "dup xol area");
2175 }
2176
2177 /*
2178 * Called in context of a new clone/fork from copy_process.
2179 */
uprobe_copy_process(struct task_struct * t,u64 flags)2180 void uprobe_copy_process(struct task_struct *t, u64 flags)
2181 {
2182 struct uprobe_task *utask = current->utask;
2183 struct mm_struct *mm = current->mm;
2184 struct xol_area *area;
2185
2186 t->utask = NULL;
2187
2188 if (!utask || !utask->return_instances)
2189 return;
2190
2191 if (mm == t->mm && !(flags & CLONE_VFORK))
2192 return;
2193
2194 if (dup_utask(t, utask))
2195 return uprobe_warn(t, "dup ret instances");
2196
2197 /* The task can fork() after dup_xol_work() fails */
2198 area = mm->uprobes_state.xol_area;
2199 if (!area)
2200 return uprobe_warn(t, "dup xol area");
2201
2202 if (mm == t->mm)
2203 return;
2204
2205 t->utask->dup_xol_addr = area->vaddr;
2206 init_task_work(&t->utask->dup_xol_work, dup_xol_work);
2207 task_work_add(t, &t->utask->dup_xol_work, TWA_RESUME);
2208 }
2209
2210 /*
2211 * Current area->vaddr notion assume the trampoline address is always
2212 * equal area->vaddr.
2213 *
2214 * Returns -1 in case the xol_area is not allocated.
2215 */
uprobe_get_trampoline_vaddr(void)2216 unsigned long uprobe_get_trampoline_vaddr(void)
2217 {
2218 unsigned long trampoline_vaddr = UPROBE_NO_TRAMPOLINE_VADDR;
2219 struct xol_area *area;
2220
2221 /* Pairs with xol_add_vma() smp_store_release() */
2222 area = READ_ONCE(current->mm->uprobes_state.xol_area); /* ^^^ */
2223 if (area)
2224 trampoline_vaddr = area->vaddr;
2225
2226 return trampoline_vaddr;
2227 }
2228
cleanup_return_instances(struct uprobe_task * utask,bool chained,struct pt_regs * regs)2229 static void cleanup_return_instances(struct uprobe_task *utask, bool chained,
2230 struct pt_regs *regs)
2231 {
2232 struct return_instance *ri = utask->return_instances, *ri_next;
2233 enum rp_check ctx = chained ? RP_CHECK_CHAIN_CALL : RP_CHECK_CALL;
2234
2235 while (ri && !arch_uretprobe_is_alive(ri, ctx, regs)) {
2236 ri_next = ri->next;
2237 rcu_assign_pointer(utask->return_instances, ri_next);
2238 utask->depth--;
2239
2240 free_ret_instance(utask, ri, true /* cleanup_hprobe */);
2241 ri = ri_next;
2242 }
2243 }
2244
prepare_uretprobe(struct uprobe * uprobe,struct pt_regs * regs,struct return_instance * ri)2245 static void prepare_uretprobe(struct uprobe *uprobe, struct pt_regs *regs,
2246 struct return_instance *ri)
2247 {
2248 struct uprobe_task *utask = current->utask;
2249 unsigned long orig_ret_vaddr, trampoline_vaddr;
2250 struct srcu_ctr __percpu *srcu_scp;
2251 bool chained;
2252
2253 if (!get_xol_area())
2254 goto free;
2255
2256 if (utask->depth >= MAX_URETPROBE_DEPTH) {
2257 printk_ratelimited(KERN_INFO "uprobe: omit uretprobe due to"
2258 " nestedness limit pid/tgid=%d/%d\n",
2259 current->pid, current->tgid);
2260 goto free;
2261 }
2262
2263 trampoline_vaddr = uprobe_get_trampoline_vaddr();
2264 orig_ret_vaddr = arch_uretprobe_hijack_return_addr(trampoline_vaddr, regs);
2265 if (orig_ret_vaddr == -1)
2266 goto free;
2267
2268 /* drop the entries invalidated by longjmp() */
2269 chained = (orig_ret_vaddr == trampoline_vaddr);
2270 cleanup_return_instances(utask, chained, regs);
2271
2272 /*
2273 * We don't want to keep trampoline address in stack, rather keep the
2274 * original return address of first caller thru all the consequent
2275 * instances. This also makes breakpoint unwrapping easier.
2276 */
2277 if (chained) {
2278 if (!utask->return_instances) {
2279 /*
2280 * This situation is not possible. Likely we have an
2281 * attack from user-space.
2282 */
2283 uprobe_warn(current, "handle tail call");
2284 goto free;
2285 }
2286 orig_ret_vaddr = utask->return_instances->orig_ret_vaddr;
2287 }
2288
2289 /*
2290 * Use srcu_down_read_fast() because the SRCU lock survives a switch to
2291 * user space and can be unlocked from a different context by ri_timer()
2292 * or dup_utask().
2293 */
2294 srcu_scp = srcu_down_read_fast(&uretprobes_srcu);
2295
2296 ri->func = instruction_pointer(regs);
2297 ri->stack = user_stack_pointer(regs);
2298 ri->orig_ret_vaddr = orig_ret_vaddr;
2299 ri->chained = chained;
2300
2301 utask->depth++;
2302
2303 hprobe_init_leased(&ri->hprobe, uprobe, srcu_scp);
2304 ri->next = utask->return_instances;
2305 rcu_assign_pointer(utask->return_instances, ri);
2306
2307 mod_timer(&utask->ri_timer, jiffies + RI_TIMER_PERIOD);
2308
2309 return;
2310 free:
2311 ri_free(ri);
2312 }
2313
2314 /* Prepare to single-step probed instruction out of line. */
2315 static int
pre_ssout(struct uprobe * uprobe,struct pt_regs * regs,unsigned long bp_vaddr)2316 pre_ssout(struct uprobe *uprobe, struct pt_regs *regs, unsigned long bp_vaddr)
2317 {
2318 struct uprobe_task *utask = current->utask;
2319 int err;
2320
2321 if (!try_get_uprobe(uprobe))
2322 return -EINVAL;
2323
2324 if (!xol_get_insn_slot(uprobe, utask)) {
2325 err = -ENOMEM;
2326 goto err_out;
2327 }
2328
2329 utask->vaddr = bp_vaddr;
2330 err = arch_uprobe_pre_xol(&uprobe->arch, regs);
2331 if (unlikely(err)) {
2332 xol_free_insn_slot(utask);
2333 goto err_out;
2334 }
2335
2336 utask->active_uprobe = uprobe;
2337 utask->state = UTASK_SSTEP;
2338 return 0;
2339 err_out:
2340 put_uprobe(uprobe);
2341 return err;
2342 }
2343
2344 /*
2345 * If we are singlestepping, then ensure this thread is not connected to
2346 * non-fatal signals until completion of singlestep. When xol insn itself
2347 * triggers the signal, restart the original insn even if the task is
2348 * already SIGKILL'ed (since coredump should report the correct ip). This
2349 * is even more important if the task has a handler for SIGSEGV/etc, The
2350 * _same_ instruction should be repeated again after return from the signal
2351 * handler, and SSTEP can never finish in this case.
2352 */
uprobe_deny_signal(void)2353 bool uprobe_deny_signal(void)
2354 {
2355 struct task_struct *t = current;
2356 struct uprobe_task *utask = t->utask;
2357
2358 if (likely(!utask || !utask->active_uprobe))
2359 return false;
2360
2361 WARN_ON_ONCE(utask->state != UTASK_SSTEP);
2362
2363 if (task_sigpending(t)) {
2364 utask->signal_denied = true;
2365 clear_tsk_thread_flag(t, TIF_SIGPENDING);
2366
2367 if (__fatal_signal_pending(t) || arch_uprobe_xol_was_trapped(t)) {
2368 utask->state = UTASK_SSTEP_TRAPPED;
2369 set_tsk_thread_flag(t, TIF_UPROBE);
2370 }
2371 }
2372
2373 return true;
2374 }
2375
mmf_recalc_uprobes(struct mm_struct * mm)2376 static void mmf_recalc_uprobes(struct mm_struct *mm)
2377 {
2378 VMA_ITERATOR(vmi, mm, 0);
2379 struct vm_area_struct *vma;
2380
2381 for_each_vma(vmi, vma) {
2382 if (!valid_vma(vma, false))
2383 continue;
2384 /*
2385 * This is not strictly accurate, we can race with
2386 * uprobe_unregister() and see the already removed
2387 * uprobe if delete_uprobe() was not yet called.
2388 * Or this uprobe can be filtered out.
2389 */
2390 if (vma_has_uprobes(vma, vma->vm_start, vma->vm_end))
2391 return;
2392 }
2393
2394 mm_flags_clear(MMF_HAS_UPROBES, mm);
2395 }
2396
is_trap_at_addr(struct mm_struct * mm,unsigned long vaddr)2397 static int is_trap_at_addr(struct mm_struct *mm, unsigned long vaddr)
2398 {
2399 struct page *page;
2400 uprobe_opcode_t opcode;
2401 int result;
2402
2403 if (WARN_ON_ONCE(!IS_ALIGNED(vaddr, UPROBE_SWBP_INSN_SIZE)))
2404 return -EINVAL;
2405
2406 pagefault_disable();
2407 result = __get_user(opcode, (uprobe_opcode_t __user *)vaddr);
2408 pagefault_enable();
2409
2410 if (likely(result == 0))
2411 goto out;
2412
2413 result = get_user_pages(vaddr, 1, FOLL_FORCE, &page);
2414 if (result < 0)
2415 return result;
2416
2417 uprobe_copy_from_page(page, vaddr, &opcode, UPROBE_SWBP_INSN_SIZE);
2418 put_page(page);
2419 out:
2420 /* This needs to return true for any variant of the trap insn */
2421 return is_trap_insn(&opcode);
2422 }
2423
find_active_uprobe_speculative(unsigned long bp_vaddr)2424 static struct uprobe *find_active_uprobe_speculative(unsigned long bp_vaddr)
2425 {
2426 struct mm_struct *mm = current->mm;
2427 struct uprobe *uprobe = NULL;
2428 struct vm_area_struct *vma;
2429 struct file *vm_file;
2430 loff_t offset;
2431 unsigned int seq;
2432
2433 guard(rcu)();
2434
2435 if (!mmap_lock_speculate_try_begin(mm, &seq))
2436 return NULL;
2437
2438 vma = vma_lookup(mm, bp_vaddr);
2439 if (!vma)
2440 return NULL;
2441
2442 /*
2443 * vm_file memory can be reused for another instance of struct file,
2444 * but can't be freed from under us, so it's safe to read fields from
2445 * it, even if the values are some garbage values; ultimately
2446 * find_uprobe_rcu() + mmap_lock_speculation_end() check will ensure
2447 * that whatever we speculatively found is correct
2448 */
2449 vm_file = READ_ONCE(vma->vm_file);
2450 if (!vm_file)
2451 return NULL;
2452
2453 offset = (loff_t)(vma_start_pgoff(vma) << PAGE_SHIFT) +
2454 (bp_vaddr - vma->vm_start);
2455 uprobe = find_uprobe_rcu(vm_file->f_inode, offset);
2456 if (!uprobe)
2457 return NULL;
2458
2459 /* now double check that nothing about MM changed */
2460 if (mmap_lock_speculate_retry(mm, seq))
2461 return NULL;
2462
2463 return uprobe;
2464 }
2465
2466 /* assumes being inside RCU protected region */
find_active_uprobe_rcu(unsigned long bp_vaddr,int * is_swbp)2467 static struct uprobe *find_active_uprobe_rcu(unsigned long bp_vaddr, int *is_swbp)
2468 {
2469 struct mm_struct *mm = current->mm;
2470 struct uprobe *uprobe = NULL;
2471 struct vm_area_struct *vma;
2472
2473 uprobe = find_active_uprobe_speculative(bp_vaddr);
2474 if (uprobe)
2475 return uprobe;
2476
2477 mmap_read_lock(mm);
2478 vma = vma_lookup(mm, bp_vaddr);
2479 if (vma) {
2480 if (vma->vm_file) {
2481 struct inode *inode = file_inode(vma->vm_file);
2482 loff_t offset = vaddr_to_offset(vma, bp_vaddr);
2483
2484 uprobe = find_uprobe_rcu(inode, offset);
2485 }
2486
2487 if (!uprobe)
2488 *is_swbp = is_trap_at_addr(mm, bp_vaddr);
2489 } else {
2490 *is_swbp = -EFAULT;
2491 }
2492
2493 if (!uprobe && mm_flags_test_and_clear(MMF_RECALC_UPROBES, mm))
2494 mmf_recalc_uprobes(mm);
2495 mmap_read_unlock(mm);
2496
2497 return uprobe;
2498 }
2499
push_consumer(struct return_instance * ri,__u64 id,__u64 cookie)2500 static struct return_instance *push_consumer(struct return_instance *ri, __u64 id, __u64 cookie)
2501 {
2502 struct return_consumer *ric;
2503
2504 if (unlikely(ri == ZERO_SIZE_PTR))
2505 return ri;
2506
2507 if (unlikely(ri->cons_cnt > 0)) {
2508 ric = krealloc(ri->extra_consumers, sizeof(*ric) * ri->cons_cnt, GFP_KERNEL);
2509 if (!ric) {
2510 ri_free(ri);
2511 return ZERO_SIZE_PTR;
2512 }
2513 ri->extra_consumers = ric;
2514 }
2515
2516 ric = likely(ri->cons_cnt == 0) ? &ri->consumer : &ri->extra_consumers[ri->cons_cnt - 1];
2517 ric->id = id;
2518 ric->cookie = cookie;
2519
2520 ri->cons_cnt++;
2521 return ri;
2522 }
2523
2524 static struct return_consumer *
return_consumer_find(struct return_instance * ri,int * iter,int id)2525 return_consumer_find(struct return_instance *ri, int *iter, int id)
2526 {
2527 struct return_consumer *ric;
2528 int idx;
2529
2530 for (idx = *iter; idx < ri->cons_cnt; idx++)
2531 {
2532 ric = likely(idx == 0) ? &ri->consumer : &ri->extra_consumers[idx - 1];
2533 if (ric->id == id) {
2534 *iter = idx + 1;
2535 return ric;
2536 }
2537 }
2538
2539 return NULL;
2540 }
2541
ignore_ret_handler(int rc)2542 static bool ignore_ret_handler(int rc)
2543 {
2544 return rc == UPROBE_HANDLER_REMOVE || rc == UPROBE_HANDLER_IGNORE;
2545 }
2546
handler_chain(struct uprobe * uprobe,struct pt_regs * regs)2547 static void handler_chain(struct uprobe *uprobe, struct pt_regs *regs)
2548 {
2549 struct uprobe_consumer *uc;
2550 bool has_consumers = false, remove = true;
2551 struct return_instance *ri = NULL;
2552 struct uprobe_task *utask = current->utask;
2553
2554 utask->auprobe = &uprobe->arch;
2555
2556 list_for_each_entry_rcu(uc, &uprobe->consumers, cons_node, rcu_read_lock_trace_held()) {
2557 bool session = uc->handler && uc->ret_handler;
2558 __u64 cookie = 0;
2559 int rc = 0;
2560
2561 if (uc->handler) {
2562 rc = uc->handler(uc, regs, &cookie);
2563 WARN(rc < 0 || rc > 2,
2564 "bad rc=0x%x from %ps()\n", rc, uc->handler);
2565 }
2566
2567 remove &= rc == UPROBE_HANDLER_REMOVE;
2568 has_consumers = true;
2569
2570 if (!uc->ret_handler || ignore_ret_handler(rc))
2571 continue;
2572
2573 if (!ri)
2574 ri = alloc_return_instance(utask);
2575
2576 if (session)
2577 ri = push_consumer(ri, uc->id, cookie);
2578 }
2579 utask->auprobe = NULL;
2580
2581 if (!ZERO_OR_NULL_PTR(ri))
2582 prepare_uretprobe(uprobe, regs, ri);
2583
2584 if (remove && has_consumers) {
2585 down_read(&uprobe->register_rwsem);
2586
2587 /* re-check that removal is still required, this time under lock */
2588 if (!filter_chain(uprobe, current->mm)) {
2589 WARN_ON(!uprobe_is_active(uprobe));
2590 unapply_uprobe(uprobe, current->mm);
2591 }
2592
2593 up_read(&uprobe->register_rwsem);
2594 }
2595 }
2596
2597 static void
handle_uretprobe_chain(struct return_instance * ri,struct uprobe * uprobe,struct pt_regs * regs)2598 handle_uretprobe_chain(struct return_instance *ri, struct uprobe *uprobe, struct pt_regs *regs)
2599 {
2600 struct return_consumer *ric;
2601 struct uprobe_consumer *uc;
2602 int ric_idx = 0;
2603
2604 /* all consumers unsubscribed meanwhile */
2605 if (unlikely(!uprobe))
2606 return;
2607
2608 rcu_read_lock_trace();
2609 list_for_each_entry_rcu(uc, &uprobe->consumers, cons_node, rcu_read_lock_trace_held()) {
2610 bool session = uc->handler && uc->ret_handler;
2611
2612 if (uc->ret_handler) {
2613 ric = return_consumer_find(ri, &ric_idx, uc->id);
2614 if (!session || ric)
2615 uc->ret_handler(uc, ri->func, regs, ric ? &ric->cookie : NULL);
2616 }
2617 }
2618 rcu_read_unlock_trace();
2619 }
2620
find_next_ret_chain(struct return_instance * ri)2621 static struct return_instance *find_next_ret_chain(struct return_instance *ri)
2622 {
2623 bool chained;
2624
2625 do {
2626 chained = ri->chained;
2627 ri = ri->next; /* can't be NULL if chained */
2628 } while (chained);
2629
2630 return ri;
2631 }
2632
uprobe_handle_trampoline(struct pt_regs * regs)2633 void uprobe_handle_trampoline(struct pt_regs *regs)
2634 {
2635 struct uprobe_task *utask;
2636 struct return_instance *ri, *ri_next, *next_chain;
2637 struct uprobe *uprobe;
2638 enum hprobe_state hstate;
2639 bool valid;
2640
2641 utask = current->utask;
2642 if (!utask)
2643 goto sigill;
2644
2645 ri = utask->return_instances;
2646 if (!ri)
2647 goto sigill;
2648
2649 do {
2650 /*
2651 * We should throw out the frames invalidated by longjmp().
2652 * If this chain is valid, then the next one should be alive
2653 * or NULL; the latter case means that nobody but ri->func
2654 * could hit this trampoline on return. TODO: sigaltstack().
2655 */
2656 next_chain = find_next_ret_chain(ri);
2657 valid = !next_chain || arch_uretprobe_is_alive(next_chain, RP_CHECK_RET, regs);
2658
2659 instruction_pointer_set(regs, ri->orig_ret_vaddr);
2660 do {
2661 /* pop current instance from the stack of pending return instances,
2662 * as it's not pending anymore: we just fixed up original
2663 * instruction pointer in regs and are about to call handlers;
2664 * this allows fixup_uretprobe_trampoline_entries() to properly fix up
2665 * captured stack traces from uretprobe handlers, in which pending
2666 * trampoline addresses on the stack are replaced with correct
2667 * original return addresses
2668 */
2669 ri_next = ri->next;
2670 rcu_assign_pointer(utask->return_instances, ri_next);
2671 utask->depth--;
2672
2673 uprobe = hprobe_consume(&ri->hprobe, &hstate);
2674 if (valid)
2675 handle_uretprobe_chain(ri, uprobe, regs);
2676 hprobe_finalize(&ri->hprobe, hstate);
2677
2678 /* We already took care of hprobe, no need to waste more time on that. */
2679 free_ret_instance(utask, ri, false /* !cleanup_hprobe */);
2680 ri = ri_next;
2681 } while (ri != next_chain);
2682 } while (!valid);
2683
2684 return;
2685
2686 sigill:
2687 uprobe_warn(current, "handle uretprobe, sending SIGILL.");
2688 force_sig(SIGILL);
2689 }
2690
arch_uprobe_ignore(struct arch_uprobe * aup,struct pt_regs * regs)2691 bool __weak arch_uprobe_ignore(struct arch_uprobe *aup, struct pt_regs *regs)
2692 {
2693 return false;
2694 }
2695
arch_uretprobe_is_alive(struct return_instance * ret,enum rp_check ctx,struct pt_regs * regs)2696 bool __weak arch_uretprobe_is_alive(struct return_instance *ret, enum rp_check ctx,
2697 struct pt_regs *regs)
2698 {
2699 return true;
2700 }
2701
arch_uprobe_optimize(struct arch_uprobe * auprobe,unsigned long vaddr)2702 void __weak arch_uprobe_optimize(struct arch_uprobe *auprobe, unsigned long vaddr)
2703 {
2704 }
2705
2706 /*
2707 * Run handler and ask thread to singlestep.
2708 * Ensure all non-fatal signals cannot interrupt thread while it singlesteps.
2709 */
handle_swbp(struct pt_regs * regs)2710 static void handle_swbp(struct pt_regs *regs)
2711 {
2712 struct uprobe *uprobe;
2713 unsigned long bp_vaddr;
2714 int is_swbp;
2715
2716 bp_vaddr = uprobe_get_swbp_addr(regs);
2717 if (bp_vaddr == uprobe_get_trampoline_vaddr())
2718 return uprobe_handle_trampoline(regs);
2719
2720 rcu_read_lock_trace();
2721
2722 uprobe = find_active_uprobe_rcu(bp_vaddr, &is_swbp);
2723 if (!uprobe) {
2724 if (is_swbp > 0) {
2725 /* No matching uprobe; signal SIGTRAP. */
2726 force_sig(SIGTRAP);
2727 } else {
2728 /*
2729 * Either we raced with uprobe_unregister() or we can't
2730 * access this memory. The latter is only possible if
2731 * another thread plays with our ->mm. In both cases
2732 * we can simply restart. If this vma was unmapped we
2733 * can pretend this insn was not executed yet and get
2734 * the (correct) SIGSEGV after restart.
2735 */
2736 instruction_pointer_set(regs, bp_vaddr);
2737 }
2738 goto out;
2739 }
2740
2741 /* change it in advance for ->handler() and restart */
2742 instruction_pointer_set(regs, bp_vaddr);
2743
2744 /*
2745 * TODO: move copy_insn/etc into _register and remove this hack.
2746 * After we hit the bp, _unregister + _register can install the
2747 * new and not-yet-analyzed uprobe at the same address, restart.
2748 */
2749 if (unlikely(!test_bit(UPROBE_COPY_INSN, &uprobe->flags)))
2750 goto out;
2751
2752 /*
2753 * Pairs with the smp_wmb() in prepare_uprobe().
2754 *
2755 * Guarantees that if we see the UPROBE_COPY_INSN bit set, then
2756 * we must also see the stores to &uprobe->arch performed by the
2757 * prepare_uprobe() call.
2758 */
2759 smp_rmb();
2760
2761 /* Tracing handlers use ->utask to communicate with fetch methods */
2762 if (!get_utask())
2763 goto out;
2764
2765 if (arch_uprobe_ignore(&uprobe->arch, regs))
2766 goto out;
2767
2768 handler_chain(uprobe, regs);
2769
2770 /* Try to optimize after first hit. */
2771 arch_uprobe_optimize(&uprobe->arch, bp_vaddr);
2772
2773 /*
2774 * If user decided to take execution elsewhere, it makes little sense
2775 * to execute the original instruction, so let's skip it.
2776 */
2777 if (instruction_pointer(regs) != bp_vaddr)
2778 goto out;
2779
2780 if (arch_uprobe_skip_sstep(&uprobe->arch, regs))
2781 goto out;
2782
2783 if (pre_ssout(uprobe, regs, bp_vaddr))
2784 goto out;
2785
2786 out:
2787 /* arch_uprobe_skip_sstep() succeeded, or restart if can't singlestep */
2788 rcu_read_unlock_trace();
2789 }
2790
handle_syscall_uprobe(struct pt_regs * regs,unsigned long bp_vaddr)2791 void handle_syscall_uprobe(struct pt_regs *regs, unsigned long bp_vaddr)
2792 {
2793 struct uprobe *uprobe;
2794 int is_swbp;
2795
2796 guard(rcu_tasks_trace)();
2797
2798 uprobe = find_active_uprobe_rcu(bp_vaddr, &is_swbp);
2799 if (!uprobe)
2800 return;
2801 if (!get_utask())
2802 return;
2803 if (arch_uprobe_ignore(&uprobe->arch, regs))
2804 return;
2805 handler_chain(uprobe, regs);
2806 }
2807
2808 /*
2809 * Perform required fix-ups and disable singlestep.
2810 * Allow pending signals to take effect.
2811 */
handle_singlestep(struct uprobe_task * utask,struct pt_regs * regs)2812 static void handle_singlestep(struct uprobe_task *utask, struct pt_regs *regs)
2813 {
2814 struct uprobe *uprobe;
2815 int err = 0;
2816
2817 uprobe = utask->active_uprobe;
2818 if (utask->state == UTASK_SSTEP_ACK)
2819 err = arch_uprobe_post_xol(&uprobe->arch, regs);
2820 else if (utask->state == UTASK_SSTEP_TRAPPED)
2821 arch_uprobe_abort_xol(&uprobe->arch, regs);
2822 else
2823 WARN_ON_ONCE(1);
2824
2825 put_uprobe(uprobe);
2826 utask->active_uprobe = NULL;
2827 utask->state = UTASK_RUNNING;
2828 xol_free_insn_slot(utask);
2829
2830 if (utask->signal_denied) {
2831 set_thread_flag(TIF_SIGPENDING);
2832 utask->signal_denied = false;
2833 }
2834
2835 if (unlikely(err)) {
2836 uprobe_warn(current, "execute the probed insn, sending SIGILL.");
2837 force_sig(SIGILL);
2838 }
2839 }
2840
2841 /*
2842 * On breakpoint hit, breakpoint notifier sets the TIF_UPROBE flag and
2843 * allows the thread to return from interrupt. After that handle_swbp()
2844 * sets utask->active_uprobe.
2845 *
2846 * On singlestep exception, singlestep notifier sets the TIF_UPROBE flag
2847 * and allows the thread to return from interrupt.
2848 *
2849 * While returning to userspace, thread notices the TIF_UPROBE flag and calls
2850 * uprobe_notify_resume().
2851 */
uprobe_notify_resume(struct pt_regs * regs)2852 void uprobe_notify_resume(struct pt_regs *regs)
2853 {
2854 struct uprobe_task *utask;
2855
2856 clear_thread_flag(TIF_UPROBE);
2857
2858 utask = current->utask;
2859 if (utask && utask->active_uprobe)
2860 handle_singlestep(utask, regs);
2861 else
2862 handle_swbp(regs);
2863 }
2864
2865 /*
2866 * uprobe_pre_sstep_notifier gets called from interrupt context as part of
2867 * notifier mechanism. Set TIF_UPROBE flag and indicate breakpoint hit.
2868 */
uprobe_pre_sstep_notifier(struct pt_regs * regs)2869 int uprobe_pre_sstep_notifier(struct pt_regs *regs)
2870 {
2871 if (!current->mm)
2872 return 0;
2873
2874 if (!mm_flags_test(MMF_HAS_UPROBES, current->mm) &&
2875 (!current->utask || !current->utask->return_instances))
2876 return 0;
2877
2878 set_thread_flag(TIF_UPROBE);
2879 return 1;
2880 }
2881
2882 /*
2883 * uprobe_post_sstep_notifier gets called in interrupt context as part of notifier
2884 * mechanism. Set TIF_UPROBE flag and indicate completion of singlestep.
2885 */
uprobe_post_sstep_notifier(struct pt_regs * regs)2886 int uprobe_post_sstep_notifier(struct pt_regs *regs)
2887 {
2888 struct uprobe_task *utask = current->utask;
2889
2890 if (!current->mm || !utask || !utask->active_uprobe)
2891 /* task is currently not uprobed */
2892 return 0;
2893
2894 utask->state = UTASK_SSTEP_ACK;
2895 set_thread_flag(TIF_UPROBE);
2896 return 1;
2897 }
2898
2899 static struct notifier_block uprobe_exception_nb = {
2900 .notifier_call = arch_uprobe_exception_notify,
2901 .priority = INT_MAX-1, /* notified after kprobes, kgdb */
2902 };
2903
uprobes_init(void)2904 void __init uprobes_init(void)
2905 {
2906 int i;
2907
2908 for (i = 0; i < UPROBES_HASH_SZ; i++)
2909 mutex_init(&uprobes_mmap_mutex[i]);
2910
2911 BUG_ON(register_die_notifier(&uprobe_exception_nb));
2912 }
2913