• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Kernel Probes (KProbes)
4  *  kernel/kprobes.c
5  *
6  * Copyright (C) IBM Corporation, 2002, 2004
7  *
8  * 2002-Oct	Created by Vamsi Krishna S <vamsi_krishna@in.ibm.com> Kernel
9  *		Probes initial implementation (includes suggestions from
10  *		Rusty Russell).
11  * 2004-Aug	Updated by Prasanna S Panchamukhi <prasanna@in.ibm.com> with
12  *		hlists and exceptions notifier as suggested by Andi Kleen.
13  * 2004-July	Suparna Bhattacharya <suparna@in.ibm.com> added jumper probes
14  *		interface to access function arguments.
15  * 2004-Sep	Prasanna S Panchamukhi <prasanna@in.ibm.com> Changed Kprobes
16  *		exceptions notifier to be first on the priority list.
17  * 2005-May	Hien Nguyen <hien@us.ibm.com>, Jim Keniston
18  *		<jkenisto@us.ibm.com> and Prasanna S Panchamukhi
19  *		<prasanna@in.ibm.com> added function-return probes.
20  */
21 
22 #define pr_fmt(fmt) "kprobes: " fmt
23 
24 #include <linux/kprobes.h>
25 #include <linux/hash.h>
26 #include <linux/init.h>
27 #include <linux/slab.h>
28 #include <linux/stddef.h>
29 #include <linux/export.h>
30 #include <linux/moduleloader.h>
31 #include <linux/kallsyms.h>
32 #include <linux/freezer.h>
33 #include <linux/seq_file.h>
34 #include <linux/debugfs.h>
35 #include <linux/sysctl.h>
36 #include <linux/kdebug.h>
37 #include <linux/memory.h>
38 #include <linux/ftrace.h>
39 #include <linux/cpu.h>
40 #include <linux/jump_label.h>
41 #include <linux/static_call.h>
42 #include <linux/perf_event.h>
43 
44 #include <asm/sections.h>
45 #include <asm/cacheflush.h>
46 #include <asm/errno.h>
47 #include <linux/uaccess.h>
48 
49 #define KPROBE_HASH_BITS 6
50 #define KPROBE_TABLE_SIZE (1 << KPROBE_HASH_BITS)
51 
52 
53 static int kprobes_initialized;
54 /* kprobe_table can be accessed by
55  * - Normal hlist traversal and RCU add/del under kprobe_mutex is held.
56  * Or
57  * - RCU hlist traversal under disabling preempt (breakpoint handlers)
58  */
59 static struct hlist_head kprobe_table[KPROBE_TABLE_SIZE];
60 
61 /* NOTE: change this value only with kprobe_mutex held */
62 static bool kprobes_all_disarmed;
63 
64 /* This protects kprobe_table and optimizing_list */
65 static DEFINE_MUTEX(kprobe_mutex);
66 static DEFINE_PER_CPU(struct kprobe *, kprobe_instance) = NULL;
67 
kprobe_lookup_name(const char * name,unsigned int __unused)68 kprobe_opcode_t * __weak kprobe_lookup_name(const char *name,
69 					unsigned int __unused)
70 {
71 	return ((kprobe_opcode_t *)(kallsyms_lookup_name(name)));
72 }
73 
74 /* Blacklist -- list of struct kprobe_blacklist_entry */
75 static LIST_HEAD(kprobe_blacklist);
76 
77 #ifdef __ARCH_WANT_KPROBES_INSN_SLOT
78 /*
79  * kprobe->ainsn.insn points to the copy of the instruction to be
80  * single-stepped. x86_64, POWER4 and above have no-exec support and
81  * stepping on the instruction on a vmalloced/kmalloced/data page
82  * is a recipe for disaster
83  */
84 struct kprobe_insn_page {
85 	struct list_head list;
86 	kprobe_opcode_t *insns;		/* Page of instruction slots */
87 	struct kprobe_insn_cache *cache;
88 	int nused;
89 	int ngarbage;
90 	char slot_used[];
91 };
92 
93 #define KPROBE_INSN_PAGE_SIZE(slots)			\
94 	(offsetof(struct kprobe_insn_page, slot_used) +	\
95 	 (sizeof(char) * (slots)))
96 
slots_per_page(struct kprobe_insn_cache * c)97 static int slots_per_page(struct kprobe_insn_cache *c)
98 {
99 	return PAGE_SIZE/(c->insn_size * sizeof(kprobe_opcode_t));
100 }
101 
102 enum kprobe_slot_state {
103 	SLOT_CLEAN = 0,
104 	SLOT_DIRTY = 1,
105 	SLOT_USED = 2,
106 };
107 
alloc_insn_page(void)108 void __weak *alloc_insn_page(void)
109 {
110 	return module_alloc(PAGE_SIZE);
111 }
112 
free_insn_page(void * page)113 static void free_insn_page(void *page)
114 {
115 	module_memfree(page);
116 }
117 
118 struct kprobe_insn_cache kprobe_insn_slots = {
119 	.mutex = __MUTEX_INITIALIZER(kprobe_insn_slots.mutex),
120 	.alloc = alloc_insn_page,
121 	.free = free_insn_page,
122 	.sym = KPROBE_INSN_PAGE_SYM,
123 	.pages = LIST_HEAD_INIT(kprobe_insn_slots.pages),
124 	.insn_size = MAX_INSN_SIZE,
125 	.nr_garbage = 0,
126 };
127 static int collect_garbage_slots(struct kprobe_insn_cache *c);
128 
129 /**
130  * __get_insn_slot() - Find a slot on an executable page for an instruction.
131  * We allocate an executable page if there's no room on existing ones.
132  */
__get_insn_slot(struct kprobe_insn_cache * c)133 kprobe_opcode_t *__get_insn_slot(struct kprobe_insn_cache *c)
134 {
135 	struct kprobe_insn_page *kip;
136 	kprobe_opcode_t *slot = NULL;
137 
138 	/* Since the slot array is not protected by rcu, we need a mutex */
139 	mutex_lock(&c->mutex);
140  retry:
141 	rcu_read_lock();
142 	list_for_each_entry_rcu(kip, &c->pages, list) {
143 		if (kip->nused < slots_per_page(c)) {
144 			int i;
145 			for (i = 0; i < slots_per_page(c); i++) {
146 				if (kip->slot_used[i] == SLOT_CLEAN) {
147 					kip->slot_used[i] = SLOT_USED;
148 					kip->nused++;
149 					slot = kip->insns + (i * c->insn_size);
150 					rcu_read_unlock();
151 					goto out;
152 				}
153 			}
154 			/* kip->nused is broken. Fix it. */
155 			kip->nused = slots_per_page(c);
156 			WARN_ON(1);
157 		}
158 	}
159 	rcu_read_unlock();
160 
161 	/* If there are any garbage slots, collect it and try again. */
162 	if (c->nr_garbage && collect_garbage_slots(c) == 0)
163 		goto retry;
164 
165 	/* All out of space.  Need to allocate a new page. */
166 	kip = kmalloc(KPROBE_INSN_PAGE_SIZE(slots_per_page(c)), GFP_KERNEL);
167 	if (!kip)
168 		goto out;
169 
170 	/*
171 	 * Use module_alloc so this page is within +/- 2GB of where the
172 	 * kernel image and loaded module images reside. This is required
173 	 * so x86_64 can correctly handle the %rip-relative fixups.
174 	 */
175 	kip->insns = c->alloc();
176 	if (!kip->insns) {
177 		kfree(kip);
178 		goto out;
179 	}
180 	INIT_LIST_HEAD(&kip->list);
181 	memset(kip->slot_used, SLOT_CLEAN, slots_per_page(c));
182 	kip->slot_used[0] = SLOT_USED;
183 	kip->nused = 1;
184 	kip->ngarbage = 0;
185 	kip->cache = c;
186 	list_add_rcu(&kip->list, &c->pages);
187 	slot = kip->insns;
188 
189 	/* Record the perf ksymbol register event after adding the page */
190 	perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_OOL, (unsigned long)kip->insns,
191 			   PAGE_SIZE, false, c->sym);
192 out:
193 	mutex_unlock(&c->mutex);
194 	return slot;
195 }
196 
197 /* Return 1 if all garbages are collected, otherwise 0. */
collect_one_slot(struct kprobe_insn_page * kip,int idx)198 static int collect_one_slot(struct kprobe_insn_page *kip, int idx)
199 {
200 	kip->slot_used[idx] = SLOT_CLEAN;
201 	kip->nused--;
202 	if (kip->nused == 0) {
203 		/*
204 		 * Page is no longer in use.  Free it unless
205 		 * it's the last one.  We keep the last one
206 		 * so as not to have to set it up again the
207 		 * next time somebody inserts a probe.
208 		 */
209 		if (!list_is_singular(&kip->list)) {
210 			/*
211 			 * Record perf ksymbol unregister event before removing
212 			 * the page.
213 			 */
214 			perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_OOL,
215 					   (unsigned long)kip->insns, PAGE_SIZE, true,
216 					   kip->cache->sym);
217 			list_del_rcu(&kip->list);
218 			synchronize_rcu();
219 			kip->cache->free(kip->insns);
220 			kfree(kip);
221 		}
222 		return 1;
223 	}
224 	return 0;
225 }
226 
collect_garbage_slots(struct kprobe_insn_cache * c)227 static int collect_garbage_slots(struct kprobe_insn_cache *c)
228 {
229 	struct kprobe_insn_page *kip, *next;
230 
231 	/* Ensure no-one is interrupted on the garbages */
232 	synchronize_rcu();
233 
234 	list_for_each_entry_safe(kip, next, &c->pages, list) {
235 		int i;
236 		if (kip->ngarbage == 0)
237 			continue;
238 		kip->ngarbage = 0;	/* we will collect all garbages */
239 		for (i = 0; i < slots_per_page(c); i++) {
240 			if (kip->slot_used[i] == SLOT_DIRTY && collect_one_slot(kip, i))
241 				break;
242 		}
243 	}
244 	c->nr_garbage = 0;
245 	return 0;
246 }
247 
__free_insn_slot(struct kprobe_insn_cache * c,kprobe_opcode_t * slot,int dirty)248 void __free_insn_slot(struct kprobe_insn_cache *c,
249 		      kprobe_opcode_t *slot, int dirty)
250 {
251 	struct kprobe_insn_page *kip;
252 	long idx;
253 
254 	mutex_lock(&c->mutex);
255 	rcu_read_lock();
256 	list_for_each_entry_rcu(kip, &c->pages, list) {
257 		idx = ((long)slot - (long)kip->insns) /
258 			(c->insn_size * sizeof(kprobe_opcode_t));
259 		if (idx >= 0 && idx < slots_per_page(c))
260 			goto out;
261 	}
262 	/* Could not find this slot. */
263 	WARN_ON(1);
264 	kip = NULL;
265 out:
266 	rcu_read_unlock();
267 	/* Mark and sweep: this may sleep */
268 	if (kip) {
269 		/* Check double free */
270 		WARN_ON(kip->slot_used[idx] != SLOT_USED);
271 		if (dirty) {
272 			kip->slot_used[idx] = SLOT_DIRTY;
273 			kip->ngarbage++;
274 			if (++c->nr_garbage > slots_per_page(c))
275 				collect_garbage_slots(c);
276 		} else {
277 			collect_one_slot(kip, idx);
278 		}
279 	}
280 	mutex_unlock(&c->mutex);
281 }
282 
283 /*
284  * Check given address is on the page of kprobe instruction slots.
285  * This will be used for checking whether the address on a stack
286  * is on a text area or not.
287  */
__is_insn_slot_addr(struct kprobe_insn_cache * c,unsigned long addr)288 bool __is_insn_slot_addr(struct kprobe_insn_cache *c, unsigned long addr)
289 {
290 	struct kprobe_insn_page *kip;
291 	bool ret = false;
292 
293 	rcu_read_lock();
294 	list_for_each_entry_rcu(kip, &c->pages, list) {
295 		if (addr >= (unsigned long)kip->insns &&
296 		    addr < (unsigned long)kip->insns + PAGE_SIZE) {
297 			ret = true;
298 			break;
299 		}
300 	}
301 	rcu_read_unlock();
302 
303 	return ret;
304 }
305 
kprobe_cache_get_kallsym(struct kprobe_insn_cache * c,unsigned int * symnum,unsigned long * value,char * type,char * sym)306 int kprobe_cache_get_kallsym(struct kprobe_insn_cache *c, unsigned int *symnum,
307 			     unsigned long *value, char *type, char *sym)
308 {
309 	struct kprobe_insn_page *kip;
310 	int ret = -ERANGE;
311 
312 	rcu_read_lock();
313 	list_for_each_entry_rcu(kip, &c->pages, list) {
314 		if ((*symnum)--)
315 			continue;
316 		strlcpy(sym, c->sym, KSYM_NAME_LEN);
317 		*type = 't';
318 		*value = (unsigned long)kip->insns;
319 		ret = 0;
320 		break;
321 	}
322 	rcu_read_unlock();
323 
324 	return ret;
325 }
326 
327 #ifdef CONFIG_OPTPROBES
alloc_optinsn_page(void)328 void __weak *alloc_optinsn_page(void)
329 {
330 	return alloc_insn_page();
331 }
332 
free_optinsn_page(void * page)333 void __weak free_optinsn_page(void *page)
334 {
335 	free_insn_page(page);
336 }
337 
338 /* For optimized_kprobe buffer */
339 struct kprobe_insn_cache kprobe_optinsn_slots = {
340 	.mutex = __MUTEX_INITIALIZER(kprobe_optinsn_slots.mutex),
341 	.alloc = alloc_optinsn_page,
342 	.free = free_optinsn_page,
343 	.sym = KPROBE_OPTINSN_PAGE_SYM,
344 	.pages = LIST_HEAD_INIT(kprobe_optinsn_slots.pages),
345 	/* .insn_size is initialized later */
346 	.nr_garbage = 0,
347 };
348 #endif
349 #endif
350 
351 /* We have preemption disabled.. so it is safe to use __ versions */
set_kprobe_instance(struct kprobe * kp)352 static inline void set_kprobe_instance(struct kprobe *kp)
353 {
354 	__this_cpu_write(kprobe_instance, kp);
355 }
356 
reset_kprobe_instance(void)357 static inline void reset_kprobe_instance(void)
358 {
359 	__this_cpu_write(kprobe_instance, NULL);
360 }
361 
362 /*
363  * This routine is called either:
364  * 	- under the kprobe_mutex - during kprobe_[un]register()
365  * 				OR
366  * 	- with preemption disabled - from arch/xxx/kernel/kprobes.c
367  */
get_kprobe(void * addr)368 struct kprobe *get_kprobe(void *addr)
369 {
370 	struct hlist_head *head;
371 	struct kprobe *p;
372 
373 	head = &kprobe_table[hash_ptr(addr, KPROBE_HASH_BITS)];
374 	hlist_for_each_entry_rcu(p, head, hlist,
375 				 lockdep_is_held(&kprobe_mutex)) {
376 		if (p->addr == addr)
377 			return p;
378 	}
379 
380 	return NULL;
381 }
382 NOKPROBE_SYMBOL(get_kprobe);
383 
384 static int aggr_pre_handler(struct kprobe *p, struct pt_regs *regs);
385 
386 /* Return true if the kprobe is an aggregator */
kprobe_aggrprobe(struct kprobe * p)387 static inline int kprobe_aggrprobe(struct kprobe *p)
388 {
389 	return p->pre_handler == aggr_pre_handler;
390 }
391 
392 /* Return true(!0) if the kprobe is unused */
kprobe_unused(struct kprobe * p)393 static inline int kprobe_unused(struct kprobe *p)
394 {
395 	return kprobe_aggrprobe(p) && kprobe_disabled(p) &&
396 	       list_empty(&p->list);
397 }
398 
399 /*
400  * Keep all fields in the kprobe consistent
401  */
copy_kprobe(struct kprobe * ap,struct kprobe * p)402 static inline void copy_kprobe(struct kprobe *ap, struct kprobe *p)
403 {
404 	memcpy(&p->opcode, &ap->opcode, sizeof(kprobe_opcode_t));
405 	memcpy(&p->ainsn, &ap->ainsn, sizeof(struct arch_specific_insn));
406 }
407 
408 #ifdef CONFIG_OPTPROBES
409 /* NOTE: change this value only with kprobe_mutex held */
410 static bool kprobes_allow_optimization;
411 
412 /*
413  * Call all pre_handler on the list, but ignores its return value.
414  * This must be called from arch-dep optimized caller.
415  */
opt_pre_handler(struct kprobe * p,struct pt_regs * regs)416 void opt_pre_handler(struct kprobe *p, struct pt_regs *regs)
417 {
418 	struct kprobe *kp;
419 
420 	list_for_each_entry_rcu(kp, &p->list, list) {
421 		if (kp->pre_handler && likely(!kprobe_disabled(kp))) {
422 			set_kprobe_instance(kp);
423 			kp->pre_handler(kp, regs);
424 		}
425 		reset_kprobe_instance();
426 	}
427 }
428 NOKPROBE_SYMBOL(opt_pre_handler);
429 
430 /* Free optimized instructions and optimized_kprobe */
free_aggr_kprobe(struct kprobe * p)431 static void free_aggr_kprobe(struct kprobe *p)
432 {
433 	struct optimized_kprobe *op;
434 
435 	op = container_of(p, struct optimized_kprobe, kp);
436 	arch_remove_optimized_kprobe(op);
437 	arch_remove_kprobe(p);
438 	kfree(op);
439 }
440 
441 /* Return true(!0) if the kprobe is ready for optimization. */
kprobe_optready(struct kprobe * p)442 static inline int kprobe_optready(struct kprobe *p)
443 {
444 	struct optimized_kprobe *op;
445 
446 	if (kprobe_aggrprobe(p)) {
447 		op = container_of(p, struct optimized_kprobe, kp);
448 		return arch_prepared_optinsn(&op->optinsn);
449 	}
450 
451 	return 0;
452 }
453 
454 /* Return true if the kprobe is disarmed. Note: p must be on hash list */
kprobe_disarmed(struct kprobe * p)455 bool kprobe_disarmed(struct kprobe *p)
456 {
457 	struct optimized_kprobe *op;
458 
459 	/* If kprobe is not aggr/opt probe, just return kprobe is disabled */
460 	if (!kprobe_aggrprobe(p))
461 		return kprobe_disabled(p);
462 
463 	op = container_of(p, struct optimized_kprobe, kp);
464 
465 	return kprobe_disabled(p) && list_empty(&op->list);
466 }
467 
468 /* Return true(!0) if the probe is queued on (un)optimizing lists */
kprobe_queued(struct kprobe * p)469 static int kprobe_queued(struct kprobe *p)
470 {
471 	struct optimized_kprobe *op;
472 
473 	if (kprobe_aggrprobe(p)) {
474 		op = container_of(p, struct optimized_kprobe, kp);
475 		if (!list_empty(&op->list))
476 			return 1;
477 	}
478 	return 0;
479 }
480 
481 /*
482  * Return an optimized kprobe whose optimizing code replaces
483  * instructions including addr (exclude breakpoint).
484  */
get_optimized_kprobe(unsigned long addr)485 static struct kprobe *get_optimized_kprobe(unsigned long addr)
486 {
487 	int i;
488 	struct kprobe *p = NULL;
489 	struct optimized_kprobe *op;
490 
491 	/* Don't check i == 0, since that is a breakpoint case. */
492 	for (i = 1; !p && i < MAX_OPTIMIZED_LENGTH; i++)
493 		p = get_kprobe((void *)(addr - i));
494 
495 	if (p && kprobe_optready(p)) {
496 		op = container_of(p, struct optimized_kprobe, kp);
497 		if (arch_within_optimized_kprobe(op, addr))
498 			return p;
499 	}
500 
501 	return NULL;
502 }
503 
504 /* Optimization staging list, protected by kprobe_mutex */
505 static LIST_HEAD(optimizing_list);
506 static LIST_HEAD(unoptimizing_list);
507 static LIST_HEAD(freeing_list);
508 
509 static void kprobe_optimizer(struct work_struct *work);
510 static DECLARE_DELAYED_WORK(optimizing_work, kprobe_optimizer);
511 #define OPTIMIZE_DELAY 5
512 
513 /*
514  * Optimize (replace a breakpoint with a jump) kprobes listed on
515  * optimizing_list.
516  */
do_optimize_kprobes(void)517 static void do_optimize_kprobes(void)
518 {
519 	lockdep_assert_held(&text_mutex);
520 	/*
521 	 * The optimization/unoptimization refers online_cpus via
522 	 * stop_machine() and cpu-hotplug modifies online_cpus.
523 	 * And same time, text_mutex will be held in cpu-hotplug and here.
524 	 * This combination can cause a deadlock (cpu-hotplug try to lock
525 	 * text_mutex but stop_machine can not be done because online_cpus
526 	 * has been changed)
527 	 * To avoid this deadlock, caller must have locked cpu hotplug
528 	 * for preventing cpu-hotplug outside of text_mutex locking.
529 	 */
530 	lockdep_assert_cpus_held();
531 
532 	/* Optimization never be done when disarmed */
533 	if (kprobes_all_disarmed || !kprobes_allow_optimization ||
534 	    list_empty(&optimizing_list))
535 		return;
536 
537 	arch_optimize_kprobes(&optimizing_list);
538 }
539 
540 /*
541  * Unoptimize (replace a jump with a breakpoint and remove the breakpoint
542  * if need) kprobes listed on unoptimizing_list.
543  */
do_unoptimize_kprobes(void)544 static void do_unoptimize_kprobes(void)
545 {
546 	struct optimized_kprobe *op, *tmp;
547 
548 	lockdep_assert_held(&text_mutex);
549 	/* See comment in do_optimize_kprobes() */
550 	lockdep_assert_cpus_held();
551 
552 	if (!list_empty(&unoptimizing_list))
553 		arch_unoptimize_kprobes(&unoptimizing_list, &freeing_list);
554 
555 	/* Loop on 'freeing_list' for disarming and removing from kprobe hash list */
556 	list_for_each_entry_safe(op, tmp, &freeing_list, list) {
557 		/* Switching from detour code to origin */
558 		op->kp.flags &= ~KPROBE_FLAG_OPTIMIZED;
559 		/* Disarm probes if marked disabled and not gone */
560 		if (kprobe_disabled(&op->kp) && !kprobe_gone(&op->kp))
561 			arch_disarm_kprobe(&op->kp);
562 		if (kprobe_unused(&op->kp)) {
563 			/*
564 			 * Remove unused probes from hash list. After waiting
565 			 * for synchronization, these probes are reclaimed.
566 			 * (reclaiming is done by do_free_cleaned_kprobes.)
567 			 */
568 			hlist_del_rcu(&op->kp.hlist);
569 		} else
570 			list_del_init(&op->list);
571 	}
572 }
573 
574 /* Reclaim all kprobes on the free_list */
do_free_cleaned_kprobes(void)575 static void do_free_cleaned_kprobes(void)
576 {
577 	struct optimized_kprobe *op, *tmp;
578 
579 	list_for_each_entry_safe(op, tmp, &freeing_list, list) {
580 		list_del_init(&op->list);
581 		if (WARN_ON_ONCE(!kprobe_unused(&op->kp))) {
582 			/*
583 			 * This must not happen, but if there is a kprobe
584 			 * still in use, keep it on kprobes hash list.
585 			 */
586 			continue;
587 		}
588 		free_aggr_kprobe(&op->kp);
589 	}
590 }
591 
592 /* Start optimizer after OPTIMIZE_DELAY passed */
kick_kprobe_optimizer(void)593 static void kick_kprobe_optimizer(void)
594 {
595 	schedule_delayed_work(&optimizing_work, OPTIMIZE_DELAY);
596 }
597 
598 /* Kprobe jump optimizer */
kprobe_optimizer(struct work_struct * work)599 static void kprobe_optimizer(struct work_struct *work)
600 {
601 	mutex_lock(&kprobe_mutex);
602 	cpus_read_lock();
603 	mutex_lock(&text_mutex);
604 
605 	/*
606 	 * Step 1: Unoptimize kprobes and collect cleaned (unused and disarmed)
607 	 * kprobes before waiting for quiesence period.
608 	 */
609 	do_unoptimize_kprobes();
610 
611 	/*
612 	 * Step 2: Wait for quiesence period to ensure all potentially
613 	 * preempted tasks to have normally scheduled. Because optprobe
614 	 * may modify multiple instructions, there is a chance that Nth
615 	 * instruction is preempted. In that case, such tasks can return
616 	 * to 2nd-Nth byte of jump instruction. This wait is for avoiding it.
617 	 * Note that on non-preemptive kernel, this is transparently converted
618 	 * to synchronoze_sched() to wait for all interrupts to have completed.
619 	 */
620 	synchronize_rcu_tasks();
621 
622 	/* Step 3: Optimize kprobes after quiesence period */
623 	do_optimize_kprobes();
624 
625 	/* Step 4: Free cleaned kprobes after quiesence period */
626 	do_free_cleaned_kprobes();
627 
628 	mutex_unlock(&text_mutex);
629 	cpus_read_unlock();
630 
631 	/* Step 5: Kick optimizer again if needed */
632 	if (!list_empty(&optimizing_list) || !list_empty(&unoptimizing_list))
633 		kick_kprobe_optimizer();
634 
635 	mutex_unlock(&kprobe_mutex);
636 }
637 
638 /* Wait for completing optimization and unoptimization */
wait_for_kprobe_optimizer(void)639 void wait_for_kprobe_optimizer(void)
640 {
641 	mutex_lock(&kprobe_mutex);
642 
643 	while (!list_empty(&optimizing_list) || !list_empty(&unoptimizing_list)) {
644 		mutex_unlock(&kprobe_mutex);
645 
646 		/* this will also make optimizing_work execute immmediately */
647 		flush_delayed_work(&optimizing_work);
648 		/* @optimizing_work might not have been queued yet, relax */
649 		cpu_relax();
650 
651 		mutex_lock(&kprobe_mutex);
652 	}
653 
654 	mutex_unlock(&kprobe_mutex);
655 }
656 
optprobe_queued_unopt(struct optimized_kprobe * op)657 bool optprobe_queued_unopt(struct optimized_kprobe *op)
658 {
659 	struct optimized_kprobe *_op;
660 
661 	list_for_each_entry(_op, &unoptimizing_list, list) {
662 		if (op == _op)
663 			return true;
664 	}
665 
666 	return false;
667 }
668 
669 /* Optimize kprobe if p is ready to be optimized */
optimize_kprobe(struct kprobe * p)670 static void optimize_kprobe(struct kprobe *p)
671 {
672 	struct optimized_kprobe *op;
673 
674 	/* Check if the kprobe is disabled or not ready for optimization. */
675 	if (!kprobe_optready(p) || !kprobes_allow_optimization ||
676 	    (kprobe_disabled(p) || kprobes_all_disarmed))
677 		return;
678 
679 	/* kprobes with post_handler can not be optimized */
680 	if (p->post_handler)
681 		return;
682 
683 	op = container_of(p, struct optimized_kprobe, kp);
684 
685 	/* Check there is no other kprobes at the optimized instructions */
686 	if (arch_check_optimized_kprobe(op) < 0)
687 		return;
688 
689 	/* Check if it is already optimized. */
690 	if (op->kp.flags & KPROBE_FLAG_OPTIMIZED) {
691 		if (optprobe_queued_unopt(op)) {
692 			/* This is under unoptimizing. Just dequeue the probe */
693 			list_del_init(&op->list);
694 		}
695 		return;
696 	}
697 	op->kp.flags |= KPROBE_FLAG_OPTIMIZED;
698 
699 	/* On unoptimizing/optimizing_list, op must have OPTIMIZED flag */
700 	if (WARN_ON_ONCE(!list_empty(&op->list)))
701 		return;
702 
703 	list_add(&op->list, &optimizing_list);
704 	kick_kprobe_optimizer();
705 }
706 
707 /* Short cut to direct unoptimizing */
force_unoptimize_kprobe(struct optimized_kprobe * op)708 static void force_unoptimize_kprobe(struct optimized_kprobe *op)
709 {
710 	lockdep_assert_cpus_held();
711 	arch_unoptimize_kprobe(op);
712 	op->kp.flags &= ~KPROBE_FLAG_OPTIMIZED;
713 }
714 
715 /* Unoptimize a kprobe if p is optimized */
unoptimize_kprobe(struct kprobe * p,bool force)716 static void unoptimize_kprobe(struct kprobe *p, bool force)
717 {
718 	struct optimized_kprobe *op;
719 
720 	if (!kprobe_aggrprobe(p) || kprobe_disarmed(p))
721 		return; /* This is not an optprobe nor optimized */
722 
723 	op = container_of(p, struct optimized_kprobe, kp);
724 	if (!kprobe_optimized(p))
725 		return;
726 
727 	if (!list_empty(&op->list)) {
728 		if (optprobe_queued_unopt(op)) {
729 			/* Queued in unoptimizing queue */
730 			if (force) {
731 				/*
732 				 * Forcibly unoptimize the kprobe here, and queue it
733 				 * in the freeing list for release afterwards.
734 				 */
735 				force_unoptimize_kprobe(op);
736 				list_move(&op->list, &freeing_list);
737 			}
738 		} else {
739 			/* Dequeue from the optimizing queue */
740 			list_del_init(&op->list);
741 			op->kp.flags &= ~KPROBE_FLAG_OPTIMIZED;
742 		}
743 		return;
744 	}
745 
746 	/* Optimized kprobe case */
747 	if (force) {
748 		/* Forcibly update the code: this is a special case */
749 		force_unoptimize_kprobe(op);
750 	} else {
751 		list_add(&op->list, &unoptimizing_list);
752 		kick_kprobe_optimizer();
753 	}
754 }
755 
756 /* Cancel unoptimizing for reusing */
reuse_unused_kprobe(struct kprobe * ap)757 static int reuse_unused_kprobe(struct kprobe *ap)
758 {
759 	struct optimized_kprobe *op;
760 
761 	/*
762 	 * Unused kprobe MUST be on the way of delayed unoptimizing (means
763 	 * there is still a relative jump) and disabled.
764 	 */
765 	op = container_of(ap, struct optimized_kprobe, kp);
766 	WARN_ON_ONCE(list_empty(&op->list));
767 	/* Enable the probe again */
768 	ap->flags &= ~KPROBE_FLAG_DISABLED;
769 	/* Optimize it again (remove from op->list) */
770 	if (!kprobe_optready(ap))
771 		return -EINVAL;
772 
773 	optimize_kprobe(ap);
774 	return 0;
775 }
776 
777 /* Remove optimized instructions */
kill_optimized_kprobe(struct kprobe * p)778 static void kill_optimized_kprobe(struct kprobe *p)
779 {
780 	struct optimized_kprobe *op;
781 
782 	op = container_of(p, struct optimized_kprobe, kp);
783 	if (!list_empty(&op->list))
784 		/* Dequeue from the (un)optimization queue */
785 		list_del_init(&op->list);
786 	op->kp.flags &= ~KPROBE_FLAG_OPTIMIZED;
787 
788 	if (kprobe_unused(p)) {
789 		/*
790 		 * Unused kprobe is on unoptimizing or freeing list. We move it
791 		 * to freeing_list and let the kprobe_optimizer() remove it from
792 		 * the kprobe hash list and free it.
793 		 */
794 		if (optprobe_queued_unopt(op))
795 			list_move(&op->list, &freeing_list);
796 	}
797 
798 	/* Don't touch the code, because it is already freed. */
799 	arch_remove_optimized_kprobe(op);
800 }
801 
802 static inline
__prepare_optimized_kprobe(struct optimized_kprobe * op,struct kprobe * p)803 void __prepare_optimized_kprobe(struct optimized_kprobe *op, struct kprobe *p)
804 {
805 	if (!kprobe_ftrace(p))
806 		arch_prepare_optimized_kprobe(op, p);
807 }
808 
809 /* Try to prepare optimized instructions */
prepare_optimized_kprobe(struct kprobe * p)810 static void prepare_optimized_kprobe(struct kprobe *p)
811 {
812 	struct optimized_kprobe *op;
813 
814 	op = container_of(p, struct optimized_kprobe, kp);
815 	__prepare_optimized_kprobe(op, p);
816 }
817 
818 /* Allocate new optimized_kprobe and try to prepare optimized instructions */
alloc_aggr_kprobe(struct kprobe * p)819 static struct kprobe *alloc_aggr_kprobe(struct kprobe *p)
820 {
821 	struct optimized_kprobe *op;
822 
823 	op = kzalloc(sizeof(struct optimized_kprobe), GFP_KERNEL);
824 	if (!op)
825 		return NULL;
826 
827 	INIT_LIST_HEAD(&op->list);
828 	op->kp.addr = p->addr;
829 	__prepare_optimized_kprobe(op, p);
830 
831 	return &op->kp;
832 }
833 
834 static void init_aggr_kprobe(struct kprobe *ap, struct kprobe *p);
835 
836 /*
837  * Prepare an optimized_kprobe and optimize it
838  * NOTE: p must be a normal registered kprobe
839  */
try_to_optimize_kprobe(struct kprobe * p)840 static void try_to_optimize_kprobe(struct kprobe *p)
841 {
842 	struct kprobe *ap;
843 	struct optimized_kprobe *op;
844 
845 	/* Impossible to optimize ftrace-based kprobe */
846 	if (kprobe_ftrace(p))
847 		return;
848 
849 	/* For preparing optimization, jump_label_text_reserved() is called */
850 	cpus_read_lock();
851 	jump_label_lock();
852 	mutex_lock(&text_mutex);
853 
854 	ap = alloc_aggr_kprobe(p);
855 	if (!ap)
856 		goto out;
857 
858 	op = container_of(ap, struct optimized_kprobe, kp);
859 	if (!arch_prepared_optinsn(&op->optinsn)) {
860 		/* If failed to setup optimizing, fallback to kprobe */
861 		arch_remove_optimized_kprobe(op);
862 		kfree(op);
863 		goto out;
864 	}
865 
866 	init_aggr_kprobe(ap, p);
867 	optimize_kprobe(ap);	/* This just kicks optimizer thread */
868 
869 out:
870 	mutex_unlock(&text_mutex);
871 	jump_label_unlock();
872 	cpus_read_unlock();
873 }
874 
optimize_all_kprobes(void)875 static void optimize_all_kprobes(void)
876 {
877 	struct hlist_head *head;
878 	struct kprobe *p;
879 	unsigned int i;
880 
881 	mutex_lock(&kprobe_mutex);
882 	/* If optimization is already allowed, just return */
883 	if (kprobes_allow_optimization)
884 		goto out;
885 
886 	cpus_read_lock();
887 	kprobes_allow_optimization = true;
888 	for (i = 0; i < KPROBE_TABLE_SIZE; i++) {
889 		head = &kprobe_table[i];
890 		hlist_for_each_entry(p, head, hlist)
891 			if (!kprobe_disabled(p))
892 				optimize_kprobe(p);
893 	}
894 	cpus_read_unlock();
895 	pr_info("kprobe jump-optimization is enabled. All kprobes are optimized if possible.\n");
896 out:
897 	mutex_unlock(&kprobe_mutex);
898 }
899 
900 #ifdef CONFIG_SYSCTL
unoptimize_all_kprobes(void)901 static void unoptimize_all_kprobes(void)
902 {
903 	struct hlist_head *head;
904 	struct kprobe *p;
905 	unsigned int i;
906 
907 	mutex_lock(&kprobe_mutex);
908 	/* If optimization is already prohibited, just return */
909 	if (!kprobes_allow_optimization) {
910 		mutex_unlock(&kprobe_mutex);
911 		return;
912 	}
913 
914 	cpus_read_lock();
915 	kprobes_allow_optimization = false;
916 	for (i = 0; i < KPROBE_TABLE_SIZE; i++) {
917 		head = &kprobe_table[i];
918 		hlist_for_each_entry(p, head, hlist) {
919 			if (!kprobe_disabled(p))
920 				unoptimize_kprobe(p, false);
921 		}
922 	}
923 	cpus_read_unlock();
924 	mutex_unlock(&kprobe_mutex);
925 
926 	/* Wait for unoptimizing completion */
927 	wait_for_kprobe_optimizer();
928 	pr_info("kprobe jump-optimization is disabled. All kprobes are based on software breakpoint.\n");
929 }
930 
931 static DEFINE_MUTEX(kprobe_sysctl_mutex);
932 int sysctl_kprobes_optimization;
proc_kprobes_optimization_handler(struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)933 int proc_kprobes_optimization_handler(struct ctl_table *table, int write,
934 				      void *buffer, size_t *length,
935 				      loff_t *ppos)
936 {
937 	int ret;
938 
939 	mutex_lock(&kprobe_sysctl_mutex);
940 	sysctl_kprobes_optimization = kprobes_allow_optimization ? 1 : 0;
941 	ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
942 
943 	if (sysctl_kprobes_optimization)
944 		optimize_all_kprobes();
945 	else
946 		unoptimize_all_kprobes();
947 	mutex_unlock(&kprobe_sysctl_mutex);
948 
949 	return ret;
950 }
951 #endif /* CONFIG_SYSCTL */
952 
953 /* Put a breakpoint for a probe. Must be called with text_mutex locked */
__arm_kprobe(struct kprobe * p)954 static void __arm_kprobe(struct kprobe *p)
955 {
956 	struct kprobe *_p;
957 
958 	/* Check collision with other optimized kprobes */
959 	_p = get_optimized_kprobe((unsigned long)p->addr);
960 	if (unlikely(_p))
961 		/* Fallback to unoptimized kprobe */
962 		unoptimize_kprobe(_p, true);
963 
964 	arch_arm_kprobe(p);
965 	optimize_kprobe(p);	/* Try to optimize (add kprobe to a list) */
966 }
967 
968 /* Remove the breakpoint of a probe. Must be called with text_mutex locked */
__disarm_kprobe(struct kprobe * p,bool reopt)969 static void __disarm_kprobe(struct kprobe *p, bool reopt)
970 {
971 	struct kprobe *_p;
972 
973 	/* Try to unoptimize */
974 	unoptimize_kprobe(p, kprobes_all_disarmed);
975 
976 	if (!kprobe_queued(p)) {
977 		arch_disarm_kprobe(p);
978 		/* If another kprobe was blocked, optimize it. */
979 		_p = get_optimized_kprobe((unsigned long)p->addr);
980 		if (unlikely(_p) && reopt)
981 			optimize_kprobe(_p);
982 	}
983 	/* TODO: reoptimize others after unoptimized this probe */
984 }
985 
986 #else /* !CONFIG_OPTPROBES */
987 
988 #define optimize_kprobe(p)			do {} while (0)
989 #define unoptimize_kprobe(p, f)			do {} while (0)
990 #define kill_optimized_kprobe(p)		do {} while (0)
991 #define prepare_optimized_kprobe(p)		do {} while (0)
992 #define try_to_optimize_kprobe(p)		do {} while (0)
993 #define __arm_kprobe(p)				arch_arm_kprobe(p)
994 #define __disarm_kprobe(p, o)			arch_disarm_kprobe(p)
995 #define kprobe_disarmed(p)			kprobe_disabled(p)
996 #define wait_for_kprobe_optimizer()		do {} while (0)
997 
reuse_unused_kprobe(struct kprobe * ap)998 static int reuse_unused_kprobe(struct kprobe *ap)
999 {
1000 	/*
1001 	 * If the optimized kprobe is NOT supported, the aggr kprobe is
1002 	 * released at the same time that the last aggregated kprobe is
1003 	 * unregistered.
1004 	 * Thus there should be no chance to reuse unused kprobe.
1005 	 */
1006 	WARN_ON_ONCE(1);
1007 	return -EINVAL;
1008 }
1009 
free_aggr_kprobe(struct kprobe * p)1010 static void free_aggr_kprobe(struct kprobe *p)
1011 {
1012 	arch_remove_kprobe(p);
1013 	kfree(p);
1014 }
1015 
alloc_aggr_kprobe(struct kprobe * p)1016 static struct kprobe *alloc_aggr_kprobe(struct kprobe *p)
1017 {
1018 	return kzalloc(sizeof(struct kprobe), GFP_KERNEL);
1019 }
1020 #endif /* CONFIG_OPTPROBES */
1021 
1022 #ifdef CONFIG_KPROBES_ON_FTRACE
1023 static struct ftrace_ops kprobe_ftrace_ops __read_mostly = {
1024 	.func = kprobe_ftrace_handler,
1025 	.flags = FTRACE_OPS_FL_SAVE_REGS,
1026 };
1027 
1028 static struct ftrace_ops kprobe_ipmodify_ops __read_mostly = {
1029 	.func = kprobe_ftrace_handler,
1030 	.flags = FTRACE_OPS_FL_SAVE_REGS | FTRACE_OPS_FL_IPMODIFY,
1031 };
1032 
1033 static int kprobe_ipmodify_enabled;
1034 static int kprobe_ftrace_enabled;
1035 
1036 /* Must ensure p->addr is really on ftrace */
prepare_kprobe(struct kprobe * p)1037 static int prepare_kprobe(struct kprobe *p)
1038 {
1039 	if (!kprobe_ftrace(p))
1040 		return arch_prepare_kprobe(p);
1041 
1042 	return arch_prepare_kprobe_ftrace(p);
1043 }
1044 
1045 /* Caller must lock kprobe_mutex */
__arm_kprobe_ftrace(struct kprobe * p,struct ftrace_ops * ops,int * cnt)1046 static int __arm_kprobe_ftrace(struct kprobe *p, struct ftrace_ops *ops,
1047 			       int *cnt)
1048 {
1049 	int ret = 0;
1050 
1051 	ret = ftrace_set_filter_ip(ops, (unsigned long)p->addr, 0, 0);
1052 	if (WARN_ONCE(ret < 0, "Failed to arm kprobe-ftrace at %pS (error %d)\n", p->addr, ret))
1053 		return ret;
1054 
1055 	if (*cnt == 0) {
1056 		ret = register_ftrace_function(ops);
1057 		if (WARN(ret < 0, "Failed to register kprobe-ftrace (error %d)\n", ret))
1058 			goto err_ftrace;
1059 	}
1060 
1061 	(*cnt)++;
1062 	return ret;
1063 
1064 err_ftrace:
1065 	/*
1066 	 * At this point, sinec ops is not registered, we should be sefe from
1067 	 * registering empty filter.
1068 	 */
1069 	ftrace_set_filter_ip(ops, (unsigned long)p->addr, 1, 0);
1070 	return ret;
1071 }
1072 
arm_kprobe_ftrace(struct kprobe * p)1073 static int arm_kprobe_ftrace(struct kprobe *p)
1074 {
1075 	bool ipmodify = (p->post_handler != NULL);
1076 
1077 	return __arm_kprobe_ftrace(p,
1078 		ipmodify ? &kprobe_ipmodify_ops : &kprobe_ftrace_ops,
1079 		ipmodify ? &kprobe_ipmodify_enabled : &kprobe_ftrace_enabled);
1080 }
1081 
1082 /* Caller must lock kprobe_mutex */
__disarm_kprobe_ftrace(struct kprobe * p,struct ftrace_ops * ops,int * cnt)1083 static int __disarm_kprobe_ftrace(struct kprobe *p, struct ftrace_ops *ops,
1084 				  int *cnt)
1085 {
1086 	int ret = 0;
1087 
1088 	if (*cnt == 1) {
1089 		ret = unregister_ftrace_function(ops);
1090 		if (WARN(ret < 0, "Failed to unregister kprobe-ftrace (error %d)\n", ret))
1091 			return ret;
1092 	}
1093 
1094 	(*cnt)--;
1095 
1096 	ret = ftrace_set_filter_ip(ops, (unsigned long)p->addr, 1, 0);
1097 	WARN_ONCE(ret < 0, "Failed to disarm kprobe-ftrace at %pS (error %d)\n",
1098 		  p->addr, ret);
1099 	return ret;
1100 }
1101 
disarm_kprobe_ftrace(struct kprobe * p)1102 static int disarm_kprobe_ftrace(struct kprobe *p)
1103 {
1104 	bool ipmodify = (p->post_handler != NULL);
1105 
1106 	return __disarm_kprobe_ftrace(p,
1107 		ipmodify ? &kprobe_ipmodify_ops : &kprobe_ftrace_ops,
1108 		ipmodify ? &kprobe_ipmodify_enabled : &kprobe_ftrace_enabled);
1109 }
1110 #else	/* !CONFIG_KPROBES_ON_FTRACE */
prepare_kprobe(struct kprobe * p)1111 static inline int prepare_kprobe(struct kprobe *p)
1112 {
1113 	return arch_prepare_kprobe(p);
1114 }
1115 
arm_kprobe_ftrace(struct kprobe * p)1116 static inline int arm_kprobe_ftrace(struct kprobe *p)
1117 {
1118 	return -ENODEV;
1119 }
1120 
disarm_kprobe_ftrace(struct kprobe * p)1121 static inline int disarm_kprobe_ftrace(struct kprobe *p)
1122 {
1123 	return -ENODEV;
1124 }
1125 #endif
1126 
1127 /* Arm a kprobe with text_mutex */
arm_kprobe(struct kprobe * kp)1128 static int arm_kprobe(struct kprobe *kp)
1129 {
1130 	if (unlikely(kprobe_ftrace(kp)))
1131 		return arm_kprobe_ftrace(kp);
1132 
1133 	cpus_read_lock();
1134 	mutex_lock(&text_mutex);
1135 	__arm_kprobe(kp);
1136 	mutex_unlock(&text_mutex);
1137 	cpus_read_unlock();
1138 
1139 	return 0;
1140 }
1141 
1142 /* Disarm a kprobe with text_mutex */
disarm_kprobe(struct kprobe * kp,bool reopt)1143 static int disarm_kprobe(struct kprobe *kp, bool reopt)
1144 {
1145 	if (unlikely(kprobe_ftrace(kp)))
1146 		return disarm_kprobe_ftrace(kp);
1147 
1148 	cpus_read_lock();
1149 	mutex_lock(&text_mutex);
1150 	__disarm_kprobe(kp, reopt);
1151 	mutex_unlock(&text_mutex);
1152 	cpus_read_unlock();
1153 
1154 	return 0;
1155 }
1156 
1157 /*
1158  * Aggregate handlers for multiple kprobes support - these handlers
1159  * take care of invoking the individual kprobe handlers on p->list
1160  */
aggr_pre_handler(struct kprobe * p,struct pt_regs * regs)1161 static int aggr_pre_handler(struct kprobe *p, struct pt_regs *regs)
1162 {
1163 	struct kprobe *kp;
1164 
1165 	list_for_each_entry_rcu(kp, &p->list, list) {
1166 		if (kp->pre_handler && likely(!kprobe_disabled(kp))) {
1167 			set_kprobe_instance(kp);
1168 			if (kp->pre_handler(kp, regs))
1169 				return 1;
1170 		}
1171 		reset_kprobe_instance();
1172 	}
1173 	return 0;
1174 }
1175 NOKPROBE_SYMBOL(aggr_pre_handler);
1176 
aggr_post_handler(struct kprobe * p,struct pt_regs * regs,unsigned long flags)1177 static void aggr_post_handler(struct kprobe *p, struct pt_regs *regs,
1178 			      unsigned long flags)
1179 {
1180 	struct kprobe *kp;
1181 
1182 	list_for_each_entry_rcu(kp, &p->list, list) {
1183 		if (kp->post_handler && likely(!kprobe_disabled(kp))) {
1184 			set_kprobe_instance(kp);
1185 			kp->post_handler(kp, regs, flags);
1186 			reset_kprobe_instance();
1187 		}
1188 	}
1189 }
1190 NOKPROBE_SYMBOL(aggr_post_handler);
1191 
1192 /* Walks the list and increments nmissed count for multiprobe case */
kprobes_inc_nmissed_count(struct kprobe * p)1193 void kprobes_inc_nmissed_count(struct kprobe *p)
1194 {
1195 	struct kprobe *kp;
1196 	if (!kprobe_aggrprobe(p)) {
1197 		p->nmissed++;
1198 	} else {
1199 		list_for_each_entry_rcu(kp, &p->list, list)
1200 			kp->nmissed++;
1201 	}
1202 	return;
1203 }
1204 NOKPROBE_SYMBOL(kprobes_inc_nmissed_count);
1205 
free_rp_inst_rcu(struct rcu_head * head)1206 static void free_rp_inst_rcu(struct rcu_head *head)
1207 {
1208 	struct kretprobe_instance *ri = container_of(head, struct kretprobe_instance, rcu);
1209 
1210 	if (refcount_dec_and_test(&ri->rph->ref))
1211 		kfree(ri->rph);
1212 	kfree(ri);
1213 }
1214 NOKPROBE_SYMBOL(free_rp_inst_rcu);
1215 
recycle_rp_inst(struct kretprobe_instance * ri)1216 static void recycle_rp_inst(struct kretprobe_instance *ri)
1217 {
1218 	struct kretprobe *rp = get_kretprobe(ri);
1219 
1220 	if (likely(rp)) {
1221 		freelist_add(&ri->freelist, &rp->freelist);
1222 	} else
1223 		call_rcu(&ri->rcu, free_rp_inst_rcu);
1224 }
1225 NOKPROBE_SYMBOL(recycle_rp_inst);
1226 
1227 static struct kprobe kprobe_busy = {
1228 	.addr = (void *) get_kprobe,
1229 };
1230 
kprobe_busy_begin(void)1231 void kprobe_busy_begin(void)
1232 {
1233 	struct kprobe_ctlblk *kcb;
1234 
1235 	preempt_disable();
1236 	__this_cpu_write(current_kprobe, &kprobe_busy);
1237 	kcb = get_kprobe_ctlblk();
1238 	kcb->kprobe_status = KPROBE_HIT_ACTIVE;
1239 }
1240 
kprobe_busy_end(void)1241 void kprobe_busy_end(void)
1242 {
1243 	__this_cpu_write(current_kprobe, NULL);
1244 	preempt_enable();
1245 }
1246 
1247 /*
1248  * This function is called from finish_task_switch when task tk becomes dead,
1249  * so that we can recycle any function-return probe instances associated
1250  * with this task. These left over instances represent probed functions
1251  * that have been called but will never return.
1252  */
kprobe_flush_task(struct task_struct * tk)1253 void kprobe_flush_task(struct task_struct *tk)
1254 {
1255 	struct kretprobe_instance *ri;
1256 	struct llist_node *node;
1257 
1258 	/* Early boot, not yet initialized. */
1259 	if (unlikely(!kprobes_initialized))
1260 		return;
1261 
1262 	kprobe_busy_begin();
1263 
1264 	node = __llist_del_all(&tk->kretprobe_instances);
1265 	while (node) {
1266 		ri = container_of(node, struct kretprobe_instance, llist);
1267 		node = node->next;
1268 
1269 		recycle_rp_inst(ri);
1270 	}
1271 
1272 	kprobe_busy_end();
1273 }
1274 NOKPROBE_SYMBOL(kprobe_flush_task);
1275 
free_rp_inst(struct kretprobe * rp)1276 static inline void free_rp_inst(struct kretprobe *rp)
1277 {
1278 	struct kretprobe_instance *ri;
1279 	struct freelist_node *node;
1280 	int count = 0;
1281 
1282 	node = rp->freelist.head;
1283 	while (node) {
1284 		ri = container_of(node, struct kretprobe_instance, freelist);
1285 		node = node->next;
1286 
1287 		kfree(ri);
1288 		count++;
1289 	}
1290 
1291 	if (refcount_sub_and_test(count, &rp->rph->ref)) {
1292 		kfree(rp->rph);
1293 		rp->rph = NULL;
1294 	}
1295 }
1296 
1297 /* Add the new probe to ap->list */
add_new_kprobe(struct kprobe * ap,struct kprobe * p)1298 static int add_new_kprobe(struct kprobe *ap, struct kprobe *p)
1299 {
1300 	if (p->post_handler)
1301 		unoptimize_kprobe(ap, true);	/* Fall back to normal kprobe */
1302 
1303 	list_add_rcu(&p->list, &ap->list);
1304 	if (p->post_handler && !ap->post_handler)
1305 		ap->post_handler = aggr_post_handler;
1306 
1307 	return 0;
1308 }
1309 
1310 /*
1311  * Fill in the required fields of the "manager kprobe". Replace the
1312  * earlier kprobe in the hlist with the manager kprobe
1313  */
init_aggr_kprobe(struct kprobe * ap,struct kprobe * p)1314 static void init_aggr_kprobe(struct kprobe *ap, struct kprobe *p)
1315 {
1316 	/* Copy p's insn slot to ap */
1317 	copy_kprobe(p, ap);
1318 	flush_insn_slot(ap);
1319 	ap->addr = p->addr;
1320 	ap->flags = p->flags & ~KPROBE_FLAG_OPTIMIZED;
1321 	ap->pre_handler = aggr_pre_handler;
1322 	/* We don't care the kprobe which has gone. */
1323 	if (p->post_handler && !kprobe_gone(p))
1324 		ap->post_handler = aggr_post_handler;
1325 
1326 	INIT_LIST_HEAD(&ap->list);
1327 	INIT_HLIST_NODE(&ap->hlist);
1328 
1329 	list_add_rcu(&p->list, &ap->list);
1330 	hlist_replace_rcu(&p->hlist, &ap->hlist);
1331 }
1332 
1333 /*
1334  * This is the second or subsequent kprobe at the address - handle
1335  * the intricacies
1336  */
register_aggr_kprobe(struct kprobe * orig_p,struct kprobe * p)1337 static int register_aggr_kprobe(struct kprobe *orig_p, struct kprobe *p)
1338 {
1339 	int ret = 0;
1340 	struct kprobe *ap = orig_p;
1341 
1342 	cpus_read_lock();
1343 
1344 	/* For preparing optimization, jump_label_text_reserved() is called */
1345 	jump_label_lock();
1346 	mutex_lock(&text_mutex);
1347 
1348 	if (!kprobe_aggrprobe(orig_p)) {
1349 		/* If orig_p is not an aggr_kprobe, create new aggr_kprobe. */
1350 		ap = alloc_aggr_kprobe(orig_p);
1351 		if (!ap) {
1352 			ret = -ENOMEM;
1353 			goto out;
1354 		}
1355 		init_aggr_kprobe(ap, orig_p);
1356 	} else if (kprobe_unused(ap)) {
1357 		/* This probe is going to die. Rescue it */
1358 		ret = reuse_unused_kprobe(ap);
1359 		if (ret)
1360 			goto out;
1361 	}
1362 
1363 	if (kprobe_gone(ap)) {
1364 		/*
1365 		 * Attempting to insert new probe at the same location that
1366 		 * had a probe in the module vaddr area which already
1367 		 * freed. So, the instruction slot has already been
1368 		 * released. We need a new slot for the new probe.
1369 		 */
1370 		ret = arch_prepare_kprobe(ap);
1371 		if (ret)
1372 			/*
1373 			 * Even if fail to allocate new slot, don't need to
1374 			 * free aggr_probe. It will be used next time, or
1375 			 * freed by unregister_kprobe.
1376 			 */
1377 			goto out;
1378 
1379 		/* Prepare optimized instructions if possible. */
1380 		prepare_optimized_kprobe(ap);
1381 
1382 		/*
1383 		 * Clear gone flag to prevent allocating new slot again, and
1384 		 * set disabled flag because it is not armed yet.
1385 		 */
1386 		ap->flags = (ap->flags & ~KPROBE_FLAG_GONE)
1387 			    | KPROBE_FLAG_DISABLED;
1388 	}
1389 
1390 	/* Copy ap's insn slot to p */
1391 	copy_kprobe(ap, p);
1392 	ret = add_new_kprobe(ap, p);
1393 
1394 out:
1395 	mutex_unlock(&text_mutex);
1396 	jump_label_unlock();
1397 	cpus_read_unlock();
1398 
1399 	if (ret == 0 && kprobe_disabled(ap) && !kprobe_disabled(p)) {
1400 		ap->flags &= ~KPROBE_FLAG_DISABLED;
1401 		if (!kprobes_all_disarmed) {
1402 			/* Arm the breakpoint again. */
1403 			ret = arm_kprobe(ap);
1404 			if (ret) {
1405 				ap->flags |= KPROBE_FLAG_DISABLED;
1406 				list_del_rcu(&p->list);
1407 				synchronize_rcu();
1408 			}
1409 		}
1410 	}
1411 	return ret;
1412 }
1413 
arch_within_kprobe_blacklist(unsigned long addr)1414 bool __weak arch_within_kprobe_blacklist(unsigned long addr)
1415 {
1416 	/* The __kprobes marked functions and entry code must not be probed */
1417 	return addr >= (unsigned long)__kprobes_text_start &&
1418 	       addr < (unsigned long)__kprobes_text_end;
1419 }
1420 
__within_kprobe_blacklist(unsigned long addr)1421 static bool __within_kprobe_blacklist(unsigned long addr)
1422 {
1423 	struct kprobe_blacklist_entry *ent;
1424 
1425 	if (arch_within_kprobe_blacklist(addr))
1426 		return true;
1427 	/*
1428 	 * If there exists a kprobe_blacklist, verify and
1429 	 * fail any probe registration in the prohibited area
1430 	 */
1431 	list_for_each_entry(ent, &kprobe_blacklist, list) {
1432 		if (addr >= ent->start_addr && addr < ent->end_addr)
1433 			return true;
1434 	}
1435 	return false;
1436 }
1437 
within_kprobe_blacklist(unsigned long addr)1438 bool within_kprobe_blacklist(unsigned long addr)
1439 {
1440 	char symname[KSYM_NAME_LEN], *p;
1441 
1442 	if (__within_kprobe_blacklist(addr))
1443 		return true;
1444 
1445 	/* Check if the address is on a suffixed-symbol */
1446 	if (!lookup_symbol_name(addr, symname)) {
1447 		p = strchr(symname, '.');
1448 		if (!p)
1449 			return false;
1450 		*p = '\0';
1451 		addr = (unsigned long)kprobe_lookup_name(symname, 0);
1452 		if (addr)
1453 			return __within_kprobe_blacklist(addr);
1454 	}
1455 	return false;
1456 }
1457 
1458 /*
1459  * If we have a symbol_name argument, look it up and add the offset field
1460  * to it. This way, we can specify a relative address to a symbol.
1461  * This returns encoded errors if it fails to look up symbol or invalid
1462  * combination of parameters.
1463  */
_kprobe_addr(kprobe_opcode_t * addr,const char * symbol_name,unsigned int offset)1464 static kprobe_opcode_t *_kprobe_addr(kprobe_opcode_t *addr,
1465 			const char *symbol_name, unsigned int offset)
1466 {
1467 	if ((symbol_name && addr) || (!symbol_name && !addr))
1468 		goto invalid;
1469 
1470 	if (symbol_name) {
1471 		addr = kprobe_lookup_name(symbol_name, offset);
1472 		if (!addr)
1473 			return ERR_PTR(-ENOENT);
1474 	}
1475 
1476 	addr = (kprobe_opcode_t *)(((char *)addr) + offset);
1477 	if (addr)
1478 		return addr;
1479 
1480 invalid:
1481 	return ERR_PTR(-EINVAL);
1482 }
1483 
kprobe_addr(struct kprobe * p)1484 static kprobe_opcode_t *kprobe_addr(struct kprobe *p)
1485 {
1486 	return _kprobe_addr(p->addr, p->symbol_name, p->offset);
1487 }
1488 
1489 /* Check passed kprobe is valid and return kprobe in kprobe_table. */
__get_valid_kprobe(struct kprobe * p)1490 static struct kprobe *__get_valid_kprobe(struct kprobe *p)
1491 {
1492 	struct kprobe *ap, *list_p;
1493 
1494 	lockdep_assert_held(&kprobe_mutex);
1495 
1496 	ap = get_kprobe(p->addr);
1497 	if (unlikely(!ap))
1498 		return NULL;
1499 
1500 	if (p != ap) {
1501 		list_for_each_entry(list_p, &ap->list, list)
1502 			if (list_p == p)
1503 			/* kprobe p is a valid probe */
1504 				goto valid;
1505 		return NULL;
1506 	}
1507 valid:
1508 	return ap;
1509 }
1510 
1511 /*
1512  * Warn and return error if the kprobe is being re-registered since
1513  * there must be a software bug.
1514  */
warn_kprobe_rereg(struct kprobe * p)1515 static inline int warn_kprobe_rereg(struct kprobe *p)
1516 {
1517 	int ret = 0;
1518 
1519 	mutex_lock(&kprobe_mutex);
1520 	if (WARN_ON_ONCE(__get_valid_kprobe(p)))
1521 		ret = -EINVAL;
1522 	mutex_unlock(&kprobe_mutex);
1523 
1524 	return ret;
1525 }
1526 
arch_check_ftrace_location(struct kprobe * p)1527 int __weak arch_check_ftrace_location(struct kprobe *p)
1528 {
1529 	unsigned long ftrace_addr;
1530 
1531 	ftrace_addr = ftrace_location((unsigned long)p->addr);
1532 	if (ftrace_addr) {
1533 #ifdef CONFIG_KPROBES_ON_FTRACE
1534 		/* Given address is not on the instruction boundary */
1535 		if ((unsigned long)p->addr != ftrace_addr)
1536 			return -EILSEQ;
1537 		p->flags |= KPROBE_FLAG_FTRACE;
1538 #else	/* !CONFIG_KPROBES_ON_FTRACE */
1539 		return -EINVAL;
1540 #endif
1541 	}
1542 	return 0;
1543 }
1544 
is_cfi_preamble_symbol(unsigned long addr)1545 static bool is_cfi_preamble_symbol(unsigned long addr)
1546 {
1547 	char symbuf[KSYM_NAME_LEN];
1548 
1549 	if (lookup_symbol_name(addr, symbuf))
1550 		return false;
1551 
1552 	return str_has_prefix("__cfi_", symbuf) ||
1553 		str_has_prefix("__pfx_", symbuf);
1554 }
1555 
check_kprobe_address_safe(struct kprobe * p,struct module ** probed_mod)1556 static int check_kprobe_address_safe(struct kprobe *p,
1557 				     struct module **probed_mod)
1558 {
1559 	int ret;
1560 
1561 	ret = arch_check_ftrace_location(p);
1562 	if (ret)
1563 		return ret;
1564 	jump_label_lock();
1565 	preempt_disable();
1566 
1567 	/* Ensure it is not in reserved area nor out of text */
1568 	if (!(core_kernel_text((unsigned long) p->addr) ||
1569 	    is_module_text_address((unsigned long) p->addr)) ||
1570 	    in_gate_area_no_mm((unsigned long) p->addr) ||
1571 	    within_kprobe_blacklist((unsigned long) p->addr) ||
1572 	    jump_label_text_reserved(p->addr, p->addr) ||
1573 	    static_call_text_reserved(p->addr, p->addr) ||
1574 	    find_bug((unsigned long)p->addr) ||
1575 	    is_cfi_preamble_symbol((unsigned long)p->addr)) {
1576 		ret = -EINVAL;
1577 		goto out;
1578 	}
1579 
1580 	/* Check if are we probing a module */
1581 	*probed_mod = __module_text_address((unsigned long) p->addr);
1582 	if (*probed_mod) {
1583 		/*
1584 		 * We must hold a refcount of the probed module while updating
1585 		 * its code to prohibit unexpected unloading.
1586 		 */
1587 		if (unlikely(!try_module_get(*probed_mod))) {
1588 			ret = -ENOENT;
1589 			goto out;
1590 		}
1591 
1592 		/*
1593 		 * If the module freed .init.text, we couldn't insert
1594 		 * kprobes in there.
1595 		 */
1596 		if (within_module_init((unsigned long)p->addr, *probed_mod) &&
1597 		    (*probed_mod)->state != MODULE_STATE_COMING) {
1598 			module_put(*probed_mod);
1599 			*probed_mod = NULL;
1600 			ret = -ENOENT;
1601 		}
1602 	}
1603 out:
1604 	preempt_enable();
1605 	jump_label_unlock();
1606 
1607 	return ret;
1608 }
1609 
register_kprobe(struct kprobe * p)1610 int register_kprobe(struct kprobe *p)
1611 {
1612 	int ret;
1613 	struct kprobe *old_p;
1614 	struct module *probed_mod;
1615 	kprobe_opcode_t *addr;
1616 
1617 	/* Adjust probe address from symbol */
1618 	addr = kprobe_addr(p);
1619 	if (IS_ERR(addr))
1620 		return PTR_ERR(addr);
1621 	p->addr = addr;
1622 
1623 	ret = warn_kprobe_rereg(p);
1624 	if (ret)
1625 		return ret;
1626 
1627 	/* User can pass only KPROBE_FLAG_DISABLED to register_kprobe */
1628 	p->flags &= KPROBE_FLAG_DISABLED;
1629 	p->nmissed = 0;
1630 	INIT_LIST_HEAD(&p->list);
1631 
1632 	ret = check_kprobe_address_safe(p, &probed_mod);
1633 	if (ret)
1634 		return ret;
1635 
1636 	mutex_lock(&kprobe_mutex);
1637 
1638 	old_p = get_kprobe(p->addr);
1639 	if (old_p) {
1640 		/* Since this may unoptimize old_p, locking text_mutex. */
1641 		ret = register_aggr_kprobe(old_p, p);
1642 		goto out;
1643 	}
1644 
1645 	cpus_read_lock();
1646 	/* Prevent text modification */
1647 	mutex_lock(&text_mutex);
1648 	ret = prepare_kprobe(p);
1649 	mutex_unlock(&text_mutex);
1650 	cpus_read_unlock();
1651 	if (ret)
1652 		goto out;
1653 
1654 	INIT_HLIST_NODE(&p->hlist);
1655 	hlist_add_head_rcu(&p->hlist,
1656 		       &kprobe_table[hash_ptr(p->addr, KPROBE_HASH_BITS)]);
1657 
1658 	if (!kprobes_all_disarmed && !kprobe_disabled(p)) {
1659 		ret = arm_kprobe(p);
1660 		if (ret) {
1661 			hlist_del_rcu(&p->hlist);
1662 			synchronize_rcu();
1663 			goto out;
1664 		}
1665 	}
1666 
1667 	/* Try to optimize kprobe */
1668 	try_to_optimize_kprobe(p);
1669 out:
1670 	mutex_unlock(&kprobe_mutex);
1671 
1672 	if (probed_mod)
1673 		module_put(probed_mod);
1674 
1675 	return ret;
1676 }
1677 EXPORT_SYMBOL_GPL(register_kprobe);
1678 
1679 /* Check if all probes on the aggrprobe are disabled */
aggr_kprobe_disabled(struct kprobe * ap)1680 static int aggr_kprobe_disabled(struct kprobe *ap)
1681 {
1682 	struct kprobe *kp;
1683 
1684 	lockdep_assert_held(&kprobe_mutex);
1685 
1686 	list_for_each_entry(kp, &ap->list, list)
1687 		if (!kprobe_disabled(kp))
1688 			/*
1689 			 * There is an active probe on the list.
1690 			 * We can't disable this ap.
1691 			 */
1692 			return 0;
1693 
1694 	return 1;
1695 }
1696 
1697 /* Disable one kprobe: Make sure called under kprobe_mutex is locked */
__disable_kprobe(struct kprobe * p)1698 static struct kprobe *__disable_kprobe(struct kprobe *p)
1699 {
1700 	struct kprobe *orig_p;
1701 	int ret;
1702 
1703 	/* Get an original kprobe for return */
1704 	orig_p = __get_valid_kprobe(p);
1705 	if (unlikely(orig_p == NULL))
1706 		return ERR_PTR(-EINVAL);
1707 
1708 	if (!kprobe_disabled(p)) {
1709 		/* Disable probe if it is a child probe */
1710 		if (p != orig_p)
1711 			p->flags |= KPROBE_FLAG_DISABLED;
1712 
1713 		/* Try to disarm and disable this/parent probe */
1714 		if (p == orig_p || aggr_kprobe_disabled(orig_p)) {
1715 			/*
1716 			 * Don't be lazy here.  Even if 'kprobes_all_disarmed'
1717 			 * is false, 'orig_p' might not have been armed yet.
1718 			 * Note arm_all_kprobes() __tries__ to arm all kprobes
1719 			 * on the best effort basis.
1720 			 */
1721 			if (!kprobes_all_disarmed && !kprobe_disabled(orig_p)) {
1722 				ret = disarm_kprobe(orig_p, true);
1723 				if (ret) {
1724 					p->flags &= ~KPROBE_FLAG_DISABLED;
1725 					return ERR_PTR(ret);
1726 				}
1727 			}
1728 			orig_p->flags |= KPROBE_FLAG_DISABLED;
1729 		}
1730 	}
1731 
1732 	return orig_p;
1733 }
1734 
1735 /*
1736  * Unregister a kprobe without a scheduler synchronization.
1737  */
__unregister_kprobe_top(struct kprobe * p)1738 static int __unregister_kprobe_top(struct kprobe *p)
1739 {
1740 	struct kprobe *ap, *list_p;
1741 
1742 	/* Disable kprobe. This will disarm it if needed. */
1743 	ap = __disable_kprobe(p);
1744 	if (IS_ERR(ap))
1745 		return PTR_ERR(ap);
1746 
1747 	if (ap == p)
1748 		/*
1749 		 * This probe is an independent(and non-optimized) kprobe
1750 		 * (not an aggrprobe). Remove from the hash list.
1751 		 */
1752 		goto disarmed;
1753 
1754 	/* Following process expects this probe is an aggrprobe */
1755 	WARN_ON(!kprobe_aggrprobe(ap));
1756 
1757 	if (list_is_singular(&ap->list) && kprobe_disarmed(ap))
1758 		/*
1759 		 * !disarmed could be happen if the probe is under delayed
1760 		 * unoptimizing.
1761 		 */
1762 		goto disarmed;
1763 	else {
1764 		/* If disabling probe has special handlers, update aggrprobe */
1765 		if (p->post_handler && !kprobe_gone(p)) {
1766 			list_for_each_entry(list_p, &ap->list, list) {
1767 				if ((list_p != p) && (list_p->post_handler))
1768 					goto noclean;
1769 			}
1770 			/*
1771 			 * For the kprobe-on-ftrace case, we keep the
1772 			 * post_handler setting to identify this aggrprobe
1773 			 * armed with kprobe_ipmodify_ops.
1774 			 */
1775 			if (!kprobe_ftrace(ap))
1776 				ap->post_handler = NULL;
1777 		}
1778 noclean:
1779 		/*
1780 		 * Remove from the aggrprobe: this path will do nothing in
1781 		 * __unregister_kprobe_bottom().
1782 		 */
1783 		list_del_rcu(&p->list);
1784 		if (!kprobe_disabled(ap) && !kprobes_all_disarmed)
1785 			/*
1786 			 * Try to optimize this probe again, because post
1787 			 * handler may have been changed.
1788 			 */
1789 			optimize_kprobe(ap);
1790 	}
1791 	return 0;
1792 
1793 disarmed:
1794 	hlist_del_rcu(&ap->hlist);
1795 	return 0;
1796 }
1797 
__unregister_kprobe_bottom(struct kprobe * p)1798 static void __unregister_kprobe_bottom(struct kprobe *p)
1799 {
1800 	struct kprobe *ap;
1801 
1802 	if (list_empty(&p->list))
1803 		/* This is an independent kprobe */
1804 		arch_remove_kprobe(p);
1805 	else if (list_is_singular(&p->list)) {
1806 		/* This is the last child of an aggrprobe */
1807 		ap = list_entry(p->list.next, struct kprobe, list);
1808 		list_del(&p->list);
1809 		free_aggr_kprobe(ap);
1810 	}
1811 	/* Otherwise, do nothing. */
1812 }
1813 
register_kprobes(struct kprobe ** kps,int num)1814 int register_kprobes(struct kprobe **kps, int num)
1815 {
1816 	int i, ret = 0;
1817 
1818 	if (num <= 0)
1819 		return -EINVAL;
1820 	for (i = 0; i < num; i++) {
1821 		ret = register_kprobe(kps[i]);
1822 		if (ret < 0) {
1823 			if (i > 0)
1824 				unregister_kprobes(kps, i);
1825 			break;
1826 		}
1827 	}
1828 	return ret;
1829 }
1830 EXPORT_SYMBOL_GPL(register_kprobes);
1831 
unregister_kprobe(struct kprobe * p)1832 void unregister_kprobe(struct kprobe *p)
1833 {
1834 	unregister_kprobes(&p, 1);
1835 }
1836 EXPORT_SYMBOL_GPL(unregister_kprobe);
1837 
unregister_kprobes(struct kprobe ** kps,int num)1838 void unregister_kprobes(struct kprobe **kps, int num)
1839 {
1840 	int i;
1841 
1842 	if (num <= 0)
1843 		return;
1844 	mutex_lock(&kprobe_mutex);
1845 	for (i = 0; i < num; i++)
1846 		if (__unregister_kprobe_top(kps[i]) < 0)
1847 			kps[i]->addr = NULL;
1848 	mutex_unlock(&kprobe_mutex);
1849 
1850 	synchronize_rcu();
1851 	for (i = 0; i < num; i++)
1852 		if (kps[i]->addr)
1853 			__unregister_kprobe_bottom(kps[i]);
1854 }
1855 EXPORT_SYMBOL_GPL(unregister_kprobes);
1856 
kprobe_exceptions_notify(struct notifier_block * self,unsigned long val,void * data)1857 int __weak kprobe_exceptions_notify(struct notifier_block *self,
1858 					unsigned long val, void *data)
1859 {
1860 	return NOTIFY_DONE;
1861 }
1862 NOKPROBE_SYMBOL(kprobe_exceptions_notify);
1863 
1864 static struct notifier_block kprobe_exceptions_nb = {
1865 	.notifier_call = kprobe_exceptions_notify,
1866 	.priority = 0x7fffffff /* we need to be notified first */
1867 };
1868 
arch_deref_entry_point(void * entry)1869 unsigned long __weak arch_deref_entry_point(void *entry)
1870 {
1871 	return (unsigned long)entry;
1872 }
1873 
1874 #ifdef CONFIG_KRETPROBES
1875 
__kretprobe_trampoline_handler(struct pt_regs * regs,void * trampoline_address,void * frame_pointer)1876 unsigned long __kretprobe_trampoline_handler(struct pt_regs *regs,
1877 					     void *trampoline_address,
1878 					     void *frame_pointer)
1879 {
1880 	kprobe_opcode_t *correct_ret_addr = NULL;
1881 	struct kretprobe_instance *ri = NULL;
1882 	struct llist_node *first, *node;
1883 	struct kretprobe *rp;
1884 
1885 	/* Find all nodes for this frame. */
1886 	first = node = current->kretprobe_instances.first;
1887 	while (node) {
1888 		ri = container_of(node, struct kretprobe_instance, llist);
1889 
1890 		BUG_ON(ri->fp != frame_pointer);
1891 
1892 		if (ri->ret_addr != trampoline_address) {
1893 			correct_ret_addr = ri->ret_addr;
1894 			/*
1895 			 * This is the real return address. Any other
1896 			 * instances associated with this task are for
1897 			 * other calls deeper on the call stack
1898 			 */
1899 			goto found;
1900 		}
1901 
1902 		node = node->next;
1903 	}
1904 	pr_err("kretprobe: Return address not found, not execute handler. Maybe there is a bug in the kernel.\n");
1905 	BUG_ON(1);
1906 
1907 found:
1908 	/* Unlink all nodes for this frame. */
1909 	current->kretprobe_instances.first = node->next;
1910 	node->next = NULL;
1911 
1912 	/* Run them..  */
1913 	while (first) {
1914 		ri = container_of(first, struct kretprobe_instance, llist);
1915 		first = first->next;
1916 
1917 		rp = get_kretprobe(ri);
1918 		if (rp && rp->handler) {
1919 			struct kprobe *prev = kprobe_running();
1920 
1921 			__this_cpu_write(current_kprobe, &rp->kp);
1922 			ri->ret_addr = correct_ret_addr;
1923 			rp->handler(ri, regs);
1924 			__this_cpu_write(current_kprobe, prev);
1925 		}
1926 
1927 		recycle_rp_inst(ri);
1928 	}
1929 
1930 	return (unsigned long)correct_ret_addr;
1931 }
NOKPROBE_SYMBOL(__kretprobe_trampoline_handler)1932 NOKPROBE_SYMBOL(__kretprobe_trampoline_handler)
1933 
1934 /*
1935  * This kprobe pre_handler is registered with every kretprobe. When probe
1936  * hits it will set up the return probe.
1937  */
1938 static int pre_handler_kretprobe(struct kprobe *p, struct pt_regs *regs)
1939 {
1940 	struct kretprobe *rp = container_of(p, struct kretprobe, kp);
1941 	struct kretprobe_instance *ri;
1942 	struct freelist_node *fn;
1943 
1944 	fn = freelist_try_get(&rp->freelist);
1945 	if (!fn) {
1946 		rp->nmissed++;
1947 		return 0;
1948 	}
1949 
1950 	ri = container_of(fn, struct kretprobe_instance, freelist);
1951 
1952 	if (rp->entry_handler && rp->entry_handler(ri, regs)) {
1953 		freelist_add(&ri->freelist, &rp->freelist);
1954 		return 0;
1955 	}
1956 
1957 	arch_prepare_kretprobe(ri, regs);
1958 
1959 	__llist_add(&ri->llist, &current->kretprobe_instances);
1960 
1961 	return 0;
1962 }
1963 NOKPROBE_SYMBOL(pre_handler_kretprobe);
1964 
arch_kprobe_on_func_entry(unsigned long offset)1965 bool __weak arch_kprobe_on_func_entry(unsigned long offset)
1966 {
1967 	return !offset;
1968 }
1969 
1970 /**
1971  * kprobe_on_func_entry() -- check whether given address is function entry
1972  * @addr: Target address
1973  * @sym:  Target symbol name
1974  * @offset: The offset from the symbol or the address
1975  *
1976  * This checks whether the given @addr+@offset or @sym+@offset is on the
1977  * function entry address or not.
1978  * This returns 0 if it is the function entry, or -EINVAL if it is not.
1979  * And also it returns -ENOENT if it fails the symbol or address lookup.
1980  * Caller must pass @addr or @sym (either one must be NULL), or this
1981  * returns -EINVAL.
1982  */
kprobe_on_func_entry(kprobe_opcode_t * addr,const char * sym,unsigned long offset)1983 int kprobe_on_func_entry(kprobe_opcode_t *addr, const char *sym, unsigned long offset)
1984 {
1985 	kprobe_opcode_t *kp_addr = _kprobe_addr(addr, sym, offset);
1986 
1987 	if (IS_ERR(kp_addr))
1988 		return PTR_ERR(kp_addr);
1989 
1990 	if (!kallsyms_lookup_size_offset((unsigned long)kp_addr, NULL, &offset))
1991 		return -ENOENT;
1992 
1993 	if (!arch_kprobe_on_func_entry(offset))
1994 		return -EINVAL;
1995 
1996 	return 0;
1997 }
1998 
register_kretprobe(struct kretprobe * rp)1999 int register_kretprobe(struct kretprobe *rp)
2000 {
2001 	int ret;
2002 	struct kretprobe_instance *inst;
2003 	int i;
2004 	void *addr;
2005 
2006 	ret = kprobe_on_func_entry(rp->kp.addr, rp->kp.symbol_name, rp->kp.offset);
2007 	if (ret)
2008 		return ret;
2009 
2010 	/* If only rp->kp.addr is specified, check reregistering kprobes */
2011 	if (rp->kp.addr && warn_kprobe_rereg(&rp->kp))
2012 		return -EINVAL;
2013 
2014 	if (kretprobe_blacklist_size) {
2015 		addr = kprobe_addr(&rp->kp);
2016 		if (IS_ERR(addr))
2017 			return PTR_ERR(addr);
2018 
2019 		for (i = 0; kretprobe_blacklist[i].name != NULL; i++) {
2020 			if (kretprobe_blacklist[i].addr == addr)
2021 				return -EINVAL;
2022 		}
2023 	}
2024 
2025 	if (rp->data_size > KRETPROBE_MAX_DATA_SIZE)
2026 		return -E2BIG;
2027 
2028 	rp->kp.pre_handler = pre_handler_kretprobe;
2029 	rp->kp.post_handler = NULL;
2030 
2031 	/* Pre-allocate memory for max kretprobe instances */
2032 	if (rp->maxactive <= 0) {
2033 #ifdef CONFIG_PREEMPTION
2034 		rp->maxactive = max_t(unsigned int, 10, 2*num_possible_cpus());
2035 #else
2036 		rp->maxactive = num_possible_cpus();
2037 #endif
2038 	}
2039 	rp->freelist.head = NULL;
2040 	rp->rph = kzalloc(sizeof(struct kretprobe_holder), GFP_KERNEL);
2041 	if (!rp->rph)
2042 		return -ENOMEM;
2043 
2044 	rcu_assign_pointer(rp->rph->rp, rp);
2045 	for (i = 0; i < rp->maxactive; i++) {
2046 		inst = kzalloc(sizeof(struct kretprobe_instance) +
2047 			       rp->data_size, GFP_KERNEL);
2048 		if (inst == NULL) {
2049 			refcount_set(&rp->rph->ref, i);
2050 			free_rp_inst(rp);
2051 			return -ENOMEM;
2052 		}
2053 		inst->rph = rp->rph;
2054 		freelist_add(&inst->freelist, &rp->freelist);
2055 	}
2056 	refcount_set(&rp->rph->ref, i);
2057 
2058 	rp->nmissed = 0;
2059 	/* Establish function entry probe point */
2060 	ret = register_kprobe(&rp->kp);
2061 	if (ret != 0)
2062 		free_rp_inst(rp);
2063 	return ret;
2064 }
2065 EXPORT_SYMBOL_GPL(register_kretprobe);
2066 
register_kretprobes(struct kretprobe ** rps,int num)2067 int register_kretprobes(struct kretprobe **rps, int num)
2068 {
2069 	int ret = 0, i;
2070 
2071 	if (num <= 0)
2072 		return -EINVAL;
2073 	for (i = 0; i < num; i++) {
2074 		ret = register_kretprobe(rps[i]);
2075 		if (ret < 0) {
2076 			if (i > 0)
2077 				unregister_kretprobes(rps, i);
2078 			break;
2079 		}
2080 	}
2081 	return ret;
2082 }
2083 EXPORT_SYMBOL_GPL(register_kretprobes);
2084 
unregister_kretprobe(struct kretprobe * rp)2085 void unregister_kretprobe(struct kretprobe *rp)
2086 {
2087 	unregister_kretprobes(&rp, 1);
2088 }
2089 EXPORT_SYMBOL_GPL(unregister_kretprobe);
2090 
unregister_kretprobes(struct kretprobe ** rps,int num)2091 void unregister_kretprobes(struct kretprobe **rps, int num)
2092 {
2093 	int i;
2094 
2095 	if (num <= 0)
2096 		return;
2097 	mutex_lock(&kprobe_mutex);
2098 	for (i = 0; i < num; i++) {
2099 		if (__unregister_kprobe_top(&rps[i]->kp) < 0)
2100 			rps[i]->kp.addr = NULL;
2101 		rcu_assign_pointer(rps[i]->rph->rp, NULL);
2102 	}
2103 	mutex_unlock(&kprobe_mutex);
2104 
2105 	synchronize_rcu();
2106 	for (i = 0; i < num; i++) {
2107 		if (rps[i]->kp.addr) {
2108 			__unregister_kprobe_bottom(&rps[i]->kp);
2109 			free_rp_inst(rps[i]);
2110 		}
2111 	}
2112 }
2113 EXPORT_SYMBOL_GPL(unregister_kretprobes);
2114 
2115 #else /* CONFIG_KRETPROBES */
register_kretprobe(struct kretprobe * rp)2116 int register_kretprobe(struct kretprobe *rp)
2117 {
2118 	return -ENOSYS;
2119 }
2120 EXPORT_SYMBOL_GPL(register_kretprobe);
2121 
register_kretprobes(struct kretprobe ** rps,int num)2122 int register_kretprobes(struct kretprobe **rps, int num)
2123 {
2124 	return -ENOSYS;
2125 }
2126 EXPORT_SYMBOL_GPL(register_kretprobes);
2127 
unregister_kretprobe(struct kretprobe * rp)2128 void unregister_kretprobe(struct kretprobe *rp)
2129 {
2130 }
2131 EXPORT_SYMBOL_GPL(unregister_kretprobe);
2132 
unregister_kretprobes(struct kretprobe ** rps,int num)2133 void unregister_kretprobes(struct kretprobe **rps, int num)
2134 {
2135 }
2136 EXPORT_SYMBOL_GPL(unregister_kretprobes);
2137 
pre_handler_kretprobe(struct kprobe * p,struct pt_regs * regs)2138 static int pre_handler_kretprobe(struct kprobe *p, struct pt_regs *regs)
2139 {
2140 	return 0;
2141 }
2142 NOKPROBE_SYMBOL(pre_handler_kretprobe);
2143 
2144 #endif /* CONFIG_KRETPROBES */
2145 
2146 /* Set the kprobe gone and remove its instruction buffer. */
kill_kprobe(struct kprobe * p)2147 static void kill_kprobe(struct kprobe *p)
2148 {
2149 	struct kprobe *kp;
2150 
2151 	lockdep_assert_held(&kprobe_mutex);
2152 
2153 	p->flags |= KPROBE_FLAG_GONE;
2154 	if (kprobe_aggrprobe(p)) {
2155 		/*
2156 		 * If this is an aggr_kprobe, we have to list all the
2157 		 * chained probes and mark them GONE.
2158 		 */
2159 		list_for_each_entry(kp, &p->list, list)
2160 			kp->flags |= KPROBE_FLAG_GONE;
2161 		p->post_handler = NULL;
2162 		kill_optimized_kprobe(p);
2163 	}
2164 	/*
2165 	 * Here, we can remove insn_slot safely, because no thread calls
2166 	 * the original probed function (which will be freed soon) any more.
2167 	 */
2168 	arch_remove_kprobe(p);
2169 
2170 	/*
2171 	 * The module is going away. We should disarm the kprobe which
2172 	 * is using ftrace, because ftrace framework is still available at
2173 	 * MODULE_STATE_GOING notification.
2174 	 */
2175 	if (kprobe_ftrace(p) && !kprobe_disabled(p) && !kprobes_all_disarmed)
2176 		disarm_kprobe_ftrace(p);
2177 }
2178 
2179 /* Disable one kprobe */
disable_kprobe(struct kprobe * kp)2180 int disable_kprobe(struct kprobe *kp)
2181 {
2182 	int ret = 0;
2183 	struct kprobe *p;
2184 
2185 	mutex_lock(&kprobe_mutex);
2186 
2187 	/* Disable this kprobe */
2188 	p = __disable_kprobe(kp);
2189 	if (IS_ERR(p))
2190 		ret = PTR_ERR(p);
2191 
2192 	mutex_unlock(&kprobe_mutex);
2193 	return ret;
2194 }
2195 EXPORT_SYMBOL_GPL(disable_kprobe);
2196 
2197 /* Enable one kprobe */
enable_kprobe(struct kprobe * kp)2198 int enable_kprobe(struct kprobe *kp)
2199 {
2200 	int ret = 0;
2201 	struct kprobe *p;
2202 
2203 	mutex_lock(&kprobe_mutex);
2204 
2205 	/* Check whether specified probe is valid. */
2206 	p = __get_valid_kprobe(kp);
2207 	if (unlikely(p == NULL)) {
2208 		ret = -EINVAL;
2209 		goto out;
2210 	}
2211 
2212 	if (kprobe_gone(kp)) {
2213 		/* This kprobe has gone, we couldn't enable it. */
2214 		ret = -EINVAL;
2215 		goto out;
2216 	}
2217 
2218 	if (p != kp)
2219 		kp->flags &= ~KPROBE_FLAG_DISABLED;
2220 
2221 	if (!kprobes_all_disarmed && kprobe_disabled(p)) {
2222 		p->flags &= ~KPROBE_FLAG_DISABLED;
2223 		ret = arm_kprobe(p);
2224 		if (ret) {
2225 			p->flags |= KPROBE_FLAG_DISABLED;
2226 			if (p != kp)
2227 				kp->flags |= KPROBE_FLAG_DISABLED;
2228 		}
2229 	}
2230 out:
2231 	mutex_unlock(&kprobe_mutex);
2232 	return ret;
2233 }
2234 EXPORT_SYMBOL_GPL(enable_kprobe);
2235 
2236 /* Caller must NOT call this in usual path. This is only for critical case */
dump_kprobe(struct kprobe * kp)2237 void dump_kprobe(struct kprobe *kp)
2238 {
2239 	pr_err("Dump kprobe:\n.symbol_name = %s, .offset = %x, .addr = %pS\n",
2240 	       kp->symbol_name, kp->offset, kp->addr);
2241 }
2242 NOKPROBE_SYMBOL(dump_kprobe);
2243 
kprobe_add_ksym_blacklist(unsigned long entry)2244 int kprobe_add_ksym_blacklist(unsigned long entry)
2245 {
2246 	struct kprobe_blacklist_entry *ent;
2247 	unsigned long offset = 0, size = 0;
2248 
2249 	if (!kernel_text_address(entry) ||
2250 	    !kallsyms_lookup_size_offset(entry, &size, &offset))
2251 		return -EINVAL;
2252 
2253 	ent = kmalloc(sizeof(*ent), GFP_KERNEL);
2254 	if (!ent)
2255 		return -ENOMEM;
2256 	ent->start_addr = entry;
2257 	ent->end_addr = entry + size;
2258 	INIT_LIST_HEAD(&ent->list);
2259 	list_add_tail(&ent->list, &kprobe_blacklist);
2260 
2261 	return (int)size;
2262 }
2263 
2264 /* Add all symbols in given area into kprobe blacklist */
kprobe_add_area_blacklist(unsigned long start,unsigned long end)2265 int kprobe_add_area_blacklist(unsigned long start, unsigned long end)
2266 {
2267 	unsigned long entry;
2268 	int ret = 0;
2269 
2270 	for (entry = start; entry < end; entry += ret) {
2271 		ret = kprobe_add_ksym_blacklist(entry);
2272 		if (ret < 0)
2273 			return ret;
2274 		if (ret == 0)	/* In case of alias symbol */
2275 			ret = 1;
2276 	}
2277 	return 0;
2278 }
2279 
2280 /* Remove all symbols in given area from kprobe blacklist */
kprobe_remove_area_blacklist(unsigned long start,unsigned long end)2281 static void kprobe_remove_area_blacklist(unsigned long start, unsigned long end)
2282 {
2283 	struct kprobe_blacklist_entry *ent, *n;
2284 
2285 	list_for_each_entry_safe(ent, n, &kprobe_blacklist, list) {
2286 		if (ent->start_addr < start || ent->start_addr >= end)
2287 			continue;
2288 		list_del(&ent->list);
2289 		kfree(ent);
2290 	}
2291 }
2292 
kprobe_remove_ksym_blacklist(unsigned long entry)2293 static void kprobe_remove_ksym_blacklist(unsigned long entry)
2294 {
2295 	kprobe_remove_area_blacklist(entry, entry + 1);
2296 }
2297 
arch_kprobe_get_kallsym(unsigned int * symnum,unsigned long * value,char * type,char * sym)2298 int __weak arch_kprobe_get_kallsym(unsigned int *symnum, unsigned long *value,
2299 				   char *type, char *sym)
2300 {
2301 	return -ERANGE;
2302 }
2303 
kprobe_get_kallsym(unsigned int symnum,unsigned long * value,char * type,char * sym)2304 int kprobe_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
2305 		       char *sym)
2306 {
2307 #ifdef __ARCH_WANT_KPROBES_INSN_SLOT
2308 	if (!kprobe_cache_get_kallsym(&kprobe_insn_slots, &symnum, value, type, sym))
2309 		return 0;
2310 #ifdef CONFIG_OPTPROBES
2311 	if (!kprobe_cache_get_kallsym(&kprobe_optinsn_slots, &symnum, value, type, sym))
2312 		return 0;
2313 #endif
2314 #endif
2315 	if (!arch_kprobe_get_kallsym(&symnum, value, type, sym))
2316 		return 0;
2317 	return -ERANGE;
2318 }
2319 
arch_populate_kprobe_blacklist(void)2320 int __init __weak arch_populate_kprobe_blacklist(void)
2321 {
2322 	return 0;
2323 }
2324 
2325 /*
2326  * Lookup and populate the kprobe_blacklist.
2327  *
2328  * Unlike the kretprobe blacklist, we'll need to determine
2329  * the range of addresses that belong to the said functions,
2330  * since a kprobe need not necessarily be at the beginning
2331  * of a function.
2332  */
populate_kprobe_blacklist(unsigned long * start,unsigned long * end)2333 static int __init populate_kprobe_blacklist(unsigned long *start,
2334 					     unsigned long *end)
2335 {
2336 	unsigned long entry;
2337 	unsigned long *iter;
2338 	int ret;
2339 
2340 	for (iter = start; iter < end; iter++) {
2341 		entry = arch_deref_entry_point((void *)*iter);
2342 		ret = kprobe_add_ksym_blacklist(entry);
2343 		if (ret == -EINVAL)
2344 			continue;
2345 		if (ret < 0)
2346 			return ret;
2347 	}
2348 
2349 	/* Symbols in __kprobes_text are blacklisted */
2350 	ret = kprobe_add_area_blacklist((unsigned long)__kprobes_text_start,
2351 					(unsigned long)__kprobes_text_end);
2352 	if (ret)
2353 		return ret;
2354 
2355 	/* Symbols in noinstr section are blacklisted */
2356 	ret = kprobe_add_area_blacklist((unsigned long)__noinstr_text_start,
2357 					(unsigned long)__noinstr_text_end);
2358 
2359 	return ret ? : arch_populate_kprobe_blacklist();
2360 }
2361 
add_module_kprobe_blacklist(struct module * mod)2362 static void add_module_kprobe_blacklist(struct module *mod)
2363 {
2364 	unsigned long start, end;
2365 	int i;
2366 
2367 	if (mod->kprobe_blacklist) {
2368 		for (i = 0; i < mod->num_kprobe_blacklist; i++)
2369 			kprobe_add_ksym_blacklist(mod->kprobe_blacklist[i]);
2370 	}
2371 
2372 	start = (unsigned long)mod->kprobes_text_start;
2373 	if (start) {
2374 		end = start + mod->kprobes_text_size;
2375 		kprobe_add_area_blacklist(start, end);
2376 	}
2377 
2378 	start = (unsigned long)mod->noinstr_text_start;
2379 	if (start) {
2380 		end = start + mod->noinstr_text_size;
2381 		kprobe_add_area_blacklist(start, end);
2382 	}
2383 }
2384 
remove_module_kprobe_blacklist(struct module * mod)2385 static void remove_module_kprobe_blacklist(struct module *mod)
2386 {
2387 	unsigned long start, end;
2388 	int i;
2389 
2390 	if (mod->kprobe_blacklist) {
2391 		for (i = 0; i < mod->num_kprobe_blacklist; i++)
2392 			kprobe_remove_ksym_blacklist(mod->kprobe_blacklist[i]);
2393 	}
2394 
2395 	start = (unsigned long)mod->kprobes_text_start;
2396 	if (start) {
2397 		end = start + mod->kprobes_text_size;
2398 		kprobe_remove_area_blacklist(start, end);
2399 	}
2400 
2401 	start = (unsigned long)mod->noinstr_text_start;
2402 	if (start) {
2403 		end = start + mod->noinstr_text_size;
2404 		kprobe_remove_area_blacklist(start, end);
2405 	}
2406 }
2407 
2408 /* Module notifier call back, checking kprobes on the module */
kprobes_module_callback(struct notifier_block * nb,unsigned long val,void * data)2409 static int kprobes_module_callback(struct notifier_block *nb,
2410 				   unsigned long val, void *data)
2411 {
2412 	struct module *mod = data;
2413 	struct hlist_head *head;
2414 	struct kprobe *p;
2415 	unsigned int i;
2416 	int checkcore = (val == MODULE_STATE_GOING);
2417 
2418 	if (val == MODULE_STATE_COMING) {
2419 		mutex_lock(&kprobe_mutex);
2420 		add_module_kprobe_blacklist(mod);
2421 		mutex_unlock(&kprobe_mutex);
2422 	}
2423 	if (val != MODULE_STATE_GOING && val != MODULE_STATE_LIVE)
2424 		return NOTIFY_DONE;
2425 
2426 	/*
2427 	 * When MODULE_STATE_GOING was notified, both of module .text and
2428 	 * .init.text sections would be freed. When MODULE_STATE_LIVE was
2429 	 * notified, only .init.text section would be freed. We need to
2430 	 * disable kprobes which have been inserted in the sections.
2431 	 */
2432 	mutex_lock(&kprobe_mutex);
2433 	for (i = 0; i < KPROBE_TABLE_SIZE; i++) {
2434 		head = &kprobe_table[i];
2435 		hlist_for_each_entry(p, head, hlist)
2436 			if (within_module_init((unsigned long)p->addr, mod) ||
2437 			    (checkcore &&
2438 			     within_module_core((unsigned long)p->addr, mod))) {
2439 				/*
2440 				 * The vaddr this probe is installed will soon
2441 				 * be vfreed buy not synced to disk. Hence,
2442 				 * disarming the breakpoint isn't needed.
2443 				 *
2444 				 * Note, this will also move any optimized probes
2445 				 * that are pending to be removed from their
2446 				 * corresponding lists to the freeing_list and
2447 				 * will not be touched by the delayed
2448 				 * kprobe_optimizer work handler.
2449 				 */
2450 				kill_kprobe(p);
2451 			}
2452 	}
2453 	if (val == MODULE_STATE_GOING)
2454 		remove_module_kprobe_blacklist(mod);
2455 	mutex_unlock(&kprobe_mutex);
2456 	return NOTIFY_DONE;
2457 }
2458 
2459 static struct notifier_block kprobe_module_nb = {
2460 	.notifier_call = kprobes_module_callback,
2461 	.priority = 0
2462 };
2463 
2464 /* Markers of _kprobe_blacklist section */
2465 extern unsigned long __start_kprobe_blacklist[];
2466 extern unsigned long __stop_kprobe_blacklist[];
2467 
kprobe_free_init_mem(void)2468 void kprobe_free_init_mem(void)
2469 {
2470 	void *start = (void *)(&__init_begin);
2471 	void *end = (void *)(&__init_end);
2472 	struct hlist_head *head;
2473 	struct kprobe *p;
2474 	int i;
2475 
2476 	mutex_lock(&kprobe_mutex);
2477 
2478 	/* Kill all kprobes on initmem */
2479 	for (i = 0; i < KPROBE_TABLE_SIZE; i++) {
2480 		head = &kprobe_table[i];
2481 		hlist_for_each_entry(p, head, hlist) {
2482 			if (start <= (void *)p->addr && (void *)p->addr < end)
2483 				kill_kprobe(p);
2484 		}
2485 	}
2486 
2487 	mutex_unlock(&kprobe_mutex);
2488 }
2489 
init_kprobes(void)2490 static int __init init_kprobes(void)
2491 {
2492 	int i, err = 0;
2493 
2494 	/* FIXME allocate the probe table, currently defined statically */
2495 	/* initialize all list heads */
2496 	for (i = 0; i < KPROBE_TABLE_SIZE; i++)
2497 		INIT_HLIST_HEAD(&kprobe_table[i]);
2498 
2499 	err = populate_kprobe_blacklist(__start_kprobe_blacklist,
2500 					__stop_kprobe_blacklist);
2501 	if (err) {
2502 		pr_err("Failed to populate blacklist (error %d), kprobes not restricted, be careful using them!\n", err);
2503 	}
2504 
2505 	if (kretprobe_blacklist_size) {
2506 		/* lookup the function address from its name */
2507 		for (i = 0; kretprobe_blacklist[i].name != NULL; i++) {
2508 			kretprobe_blacklist[i].addr =
2509 				kprobe_lookup_name(kretprobe_blacklist[i].name, 0);
2510 			if (!kretprobe_blacklist[i].addr)
2511 				pr_err("Failed to lookup symbol '%s' for kretprobe blacklist. Maybe the target function is removed or renamed.\n",
2512 				       kretprobe_blacklist[i].name);
2513 		}
2514 	}
2515 
2516 	/* By default, kprobes are armed */
2517 	kprobes_all_disarmed = false;
2518 
2519 #if defined(CONFIG_OPTPROBES) && defined(__ARCH_WANT_KPROBES_INSN_SLOT)
2520 	/* Init kprobe_optinsn_slots for allocation */
2521 	kprobe_optinsn_slots.insn_size = MAX_OPTINSN_SIZE;
2522 #endif
2523 
2524 	err = arch_init_kprobes();
2525 	if (!err)
2526 		err = register_die_notifier(&kprobe_exceptions_nb);
2527 	if (!err)
2528 		err = register_module_notifier(&kprobe_module_nb);
2529 
2530 	kprobes_initialized = (err == 0);
2531 
2532 	if (!err)
2533 		init_test_probes();
2534 	return err;
2535 }
2536 early_initcall(init_kprobes);
2537 
2538 #if defined(CONFIG_OPTPROBES)
init_optprobes(void)2539 static int __init init_optprobes(void)
2540 {
2541 	/*
2542 	 * Enable kprobe optimization - this kicks the optimizer which
2543 	 * depends on synchronize_rcu_tasks() and ksoftirqd, that is
2544 	 * not spawned in early initcall. So delay the optimization.
2545 	 */
2546 	optimize_all_kprobes();
2547 
2548 	return 0;
2549 }
2550 subsys_initcall(init_optprobes);
2551 #endif
2552 
2553 #ifdef CONFIG_DEBUG_FS
report_probe(struct seq_file * pi,struct kprobe * p,const char * sym,int offset,char * modname,struct kprobe * pp)2554 static void report_probe(struct seq_file *pi, struct kprobe *p,
2555 		const char *sym, int offset, char *modname, struct kprobe *pp)
2556 {
2557 	char *kprobe_type;
2558 	void *addr = p->addr;
2559 
2560 	if (p->pre_handler == pre_handler_kretprobe)
2561 		kprobe_type = "r";
2562 	else
2563 		kprobe_type = "k";
2564 
2565 	if (!kallsyms_show_value(pi->file->f_cred))
2566 		addr = NULL;
2567 
2568 	if (sym)
2569 		seq_printf(pi, "%px  %s  %s+0x%x  %s ",
2570 			addr, kprobe_type, sym, offset,
2571 			(modname ? modname : " "));
2572 	else	/* try to use %pS */
2573 		seq_printf(pi, "%px  %s  %pS ",
2574 			addr, kprobe_type, p->addr);
2575 
2576 	if (!pp)
2577 		pp = p;
2578 	seq_printf(pi, "%s%s%s%s\n",
2579 		(kprobe_gone(p) ? "[GONE]" : ""),
2580 		((kprobe_disabled(p) && !kprobe_gone(p)) ?  "[DISABLED]" : ""),
2581 		(kprobe_optimized(pp) ? "[OPTIMIZED]" : ""),
2582 		(kprobe_ftrace(pp) ? "[FTRACE]" : ""));
2583 }
2584 
kprobe_seq_start(struct seq_file * f,loff_t * pos)2585 static void *kprobe_seq_start(struct seq_file *f, loff_t *pos)
2586 {
2587 	return (*pos < KPROBE_TABLE_SIZE) ? pos : NULL;
2588 }
2589 
kprobe_seq_next(struct seq_file * f,void * v,loff_t * pos)2590 static void *kprobe_seq_next(struct seq_file *f, void *v, loff_t *pos)
2591 {
2592 	(*pos)++;
2593 	if (*pos >= KPROBE_TABLE_SIZE)
2594 		return NULL;
2595 	return pos;
2596 }
2597 
kprobe_seq_stop(struct seq_file * f,void * v)2598 static void kprobe_seq_stop(struct seq_file *f, void *v)
2599 {
2600 	/* Nothing to do */
2601 }
2602 
show_kprobe_addr(struct seq_file * pi,void * v)2603 static int show_kprobe_addr(struct seq_file *pi, void *v)
2604 {
2605 	struct hlist_head *head;
2606 	struct kprobe *p, *kp;
2607 	const char *sym = NULL;
2608 	unsigned int i = *(loff_t *) v;
2609 	unsigned long offset = 0;
2610 	char *modname, namebuf[KSYM_NAME_LEN];
2611 
2612 	head = &kprobe_table[i];
2613 	preempt_disable();
2614 	hlist_for_each_entry_rcu(p, head, hlist) {
2615 		sym = kallsyms_lookup((unsigned long)p->addr, NULL,
2616 					&offset, &modname, namebuf);
2617 		if (kprobe_aggrprobe(p)) {
2618 			list_for_each_entry_rcu(kp, &p->list, list)
2619 				report_probe(pi, kp, sym, offset, modname, p);
2620 		} else
2621 			report_probe(pi, p, sym, offset, modname, NULL);
2622 	}
2623 	preempt_enable();
2624 	return 0;
2625 }
2626 
2627 static const struct seq_operations kprobes_sops = {
2628 	.start = kprobe_seq_start,
2629 	.next  = kprobe_seq_next,
2630 	.stop  = kprobe_seq_stop,
2631 	.show  = show_kprobe_addr
2632 };
2633 
2634 DEFINE_SEQ_ATTRIBUTE(kprobes);
2635 
2636 /* kprobes/blacklist -- shows which functions can not be probed */
kprobe_blacklist_seq_start(struct seq_file * m,loff_t * pos)2637 static void *kprobe_blacklist_seq_start(struct seq_file *m, loff_t *pos)
2638 {
2639 	mutex_lock(&kprobe_mutex);
2640 	return seq_list_start(&kprobe_blacklist, *pos);
2641 }
2642 
kprobe_blacklist_seq_next(struct seq_file * m,void * v,loff_t * pos)2643 static void *kprobe_blacklist_seq_next(struct seq_file *m, void *v, loff_t *pos)
2644 {
2645 	return seq_list_next(v, &kprobe_blacklist, pos);
2646 }
2647 
kprobe_blacklist_seq_show(struct seq_file * m,void * v)2648 static int kprobe_blacklist_seq_show(struct seq_file *m, void *v)
2649 {
2650 	struct kprobe_blacklist_entry *ent =
2651 		list_entry(v, struct kprobe_blacklist_entry, list);
2652 
2653 	/*
2654 	 * If /proc/kallsyms is not showing kernel address, we won't
2655 	 * show them here either.
2656 	 */
2657 	if (!kallsyms_show_value(m->file->f_cred))
2658 		seq_printf(m, "0x%px-0x%px\t%ps\n", NULL, NULL,
2659 			   (void *)ent->start_addr);
2660 	else
2661 		seq_printf(m, "0x%px-0x%px\t%ps\n", (void *)ent->start_addr,
2662 			   (void *)ent->end_addr, (void *)ent->start_addr);
2663 	return 0;
2664 }
2665 
kprobe_blacklist_seq_stop(struct seq_file * f,void * v)2666 static void kprobe_blacklist_seq_stop(struct seq_file *f, void *v)
2667 {
2668 	mutex_unlock(&kprobe_mutex);
2669 }
2670 
2671 static const struct seq_operations kprobe_blacklist_sops = {
2672 	.start = kprobe_blacklist_seq_start,
2673 	.next  = kprobe_blacklist_seq_next,
2674 	.stop  = kprobe_blacklist_seq_stop,
2675 	.show  = kprobe_blacklist_seq_show,
2676 };
2677 DEFINE_SEQ_ATTRIBUTE(kprobe_blacklist);
2678 
arm_all_kprobes(void)2679 static int arm_all_kprobes(void)
2680 {
2681 	struct hlist_head *head;
2682 	struct kprobe *p;
2683 	unsigned int i, total = 0, errors = 0;
2684 	int err, ret = 0;
2685 
2686 	mutex_lock(&kprobe_mutex);
2687 
2688 	/* If kprobes are armed, just return */
2689 	if (!kprobes_all_disarmed)
2690 		goto already_enabled;
2691 
2692 	/*
2693 	 * optimize_kprobe() called by arm_kprobe() checks
2694 	 * kprobes_all_disarmed, so set kprobes_all_disarmed before
2695 	 * arm_kprobe.
2696 	 */
2697 	kprobes_all_disarmed = false;
2698 	/* Arming kprobes doesn't optimize kprobe itself */
2699 	for (i = 0; i < KPROBE_TABLE_SIZE; i++) {
2700 		head = &kprobe_table[i];
2701 		/* Arm all kprobes on a best-effort basis */
2702 		hlist_for_each_entry(p, head, hlist) {
2703 			if (!kprobe_disabled(p)) {
2704 				err = arm_kprobe(p);
2705 				if (err)  {
2706 					errors++;
2707 					ret = err;
2708 				}
2709 				total++;
2710 			}
2711 		}
2712 	}
2713 
2714 	if (errors)
2715 		pr_warn("Kprobes globally enabled, but failed to enable %d out of %d probes. Please check which kprobes are kept disabled via debugfs.\n",
2716 			errors, total);
2717 	else
2718 		pr_info("Kprobes globally enabled\n");
2719 
2720 already_enabled:
2721 	mutex_unlock(&kprobe_mutex);
2722 	return ret;
2723 }
2724 
disarm_all_kprobes(void)2725 static int disarm_all_kprobes(void)
2726 {
2727 	struct hlist_head *head;
2728 	struct kprobe *p;
2729 	unsigned int i, total = 0, errors = 0;
2730 	int err, ret = 0;
2731 
2732 	mutex_lock(&kprobe_mutex);
2733 
2734 	/* If kprobes are already disarmed, just return */
2735 	if (kprobes_all_disarmed) {
2736 		mutex_unlock(&kprobe_mutex);
2737 		return 0;
2738 	}
2739 
2740 	kprobes_all_disarmed = true;
2741 
2742 	for (i = 0; i < KPROBE_TABLE_SIZE; i++) {
2743 		head = &kprobe_table[i];
2744 		/* Disarm all kprobes on a best-effort basis */
2745 		hlist_for_each_entry(p, head, hlist) {
2746 			if (!arch_trampoline_kprobe(p) && !kprobe_disabled(p)) {
2747 				err = disarm_kprobe(p, false);
2748 				if (err) {
2749 					errors++;
2750 					ret = err;
2751 				}
2752 				total++;
2753 			}
2754 		}
2755 	}
2756 
2757 	if (errors)
2758 		pr_warn("Kprobes globally disabled, but failed to disable %d out of %d probes. Please check which kprobes are kept enabled via debugfs.\n",
2759 			errors, total);
2760 	else
2761 		pr_info("Kprobes globally disabled\n");
2762 
2763 	mutex_unlock(&kprobe_mutex);
2764 
2765 	/* Wait for disarming all kprobes by optimizer */
2766 	wait_for_kprobe_optimizer();
2767 
2768 	return ret;
2769 }
2770 
2771 /*
2772  * XXX: The debugfs bool file interface doesn't allow for callbacks
2773  * when the bool state is switched. We can reuse that facility when
2774  * available
2775  */
read_enabled_file_bool(struct file * file,char __user * user_buf,size_t count,loff_t * ppos)2776 static ssize_t read_enabled_file_bool(struct file *file,
2777 	       char __user *user_buf, size_t count, loff_t *ppos)
2778 {
2779 	char buf[3];
2780 
2781 	if (!kprobes_all_disarmed)
2782 		buf[0] = '1';
2783 	else
2784 		buf[0] = '0';
2785 	buf[1] = '\n';
2786 	buf[2] = 0x00;
2787 	return simple_read_from_buffer(user_buf, count, ppos, buf, 2);
2788 }
2789 
write_enabled_file_bool(struct file * file,const char __user * user_buf,size_t count,loff_t * ppos)2790 static ssize_t write_enabled_file_bool(struct file *file,
2791 	       const char __user *user_buf, size_t count, loff_t *ppos)
2792 {
2793 	char buf[32];
2794 	size_t buf_size;
2795 	int ret = 0;
2796 
2797 	buf_size = min(count, (sizeof(buf)-1));
2798 	if (copy_from_user(buf, user_buf, buf_size))
2799 		return -EFAULT;
2800 
2801 	buf[buf_size] = '\0';
2802 	switch (buf[0]) {
2803 	case 'y':
2804 	case 'Y':
2805 	case '1':
2806 		ret = arm_all_kprobes();
2807 		break;
2808 	case 'n':
2809 	case 'N':
2810 	case '0':
2811 		ret = disarm_all_kprobes();
2812 		break;
2813 	default:
2814 		return -EINVAL;
2815 	}
2816 
2817 	if (ret)
2818 		return ret;
2819 
2820 	return count;
2821 }
2822 
2823 static const struct file_operations fops_kp = {
2824 	.read =         read_enabled_file_bool,
2825 	.write =        write_enabled_file_bool,
2826 	.llseek =	default_llseek,
2827 };
2828 
debugfs_kprobe_init(void)2829 static int __init debugfs_kprobe_init(void)
2830 {
2831 	struct dentry *dir;
2832 
2833 	dir = debugfs_create_dir("kprobes", NULL);
2834 
2835 	debugfs_create_file("list", 0400, dir, NULL, &kprobes_fops);
2836 
2837 	debugfs_create_file("enabled", 0600, dir, NULL, &fops_kp);
2838 
2839 	debugfs_create_file("blacklist", 0400, dir, NULL,
2840 			    &kprobe_blacklist_fops);
2841 
2842 	return 0;
2843 }
2844 
2845 late_initcall(debugfs_kprobe_init);
2846 #endif /* CONFIG_DEBUG_FS */
2847