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