xref: /linux/kernel/trace/rethook.c (revision 335bbdf01d25517ae832ac1807fd8323c1f4f3b9)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #define pr_fmt(fmt) "rethook: " fmt
4 
5 #include <linux/bug.h>
6 #include <linux/kallsyms.h>
7 #include <linux/kprobes.h>
8 #include <linux/preempt.h>
9 #include <linux/rethook.h>
10 #include <linux/slab.h>
11 
12 /* Return hook list (shadow stack by list) */
13 
14 /*
15  * This function is called from delayed_put_task_struct() when a task is
16  * dead and cleaned up to recycle any kretprobe instances associated with
17  * this task. These left over instances represent probed functions that
18  * have been called but will never return.
19  */
20 void rethook_flush_task(struct task_struct *tk)
21 {
22 	struct rethook_node *rhn;
23 	struct llist_node *node;
24 
25 	node = __llist_del_all(&tk->rethooks);
26 	while (node) {
27 		rhn = container_of(node, struct rethook_node, llist);
28 		node = node->next;
29 		preempt_disable();
30 		rethook_recycle(rhn);
31 		preempt_enable();
32 	}
33 }
34 
35 static void rethook_free_rcu(struct rcu_head *head)
36 {
37 	struct rethook *rh = container_of(head, struct rethook, rcu);
38 	objpool_fini(&rh->pool);
39 }
40 
41 /**
42  * rethook_stop() - Stop using a rethook.
43  * @rh: the struct rethook to stop.
44  *
45  * Stop using a rethook to prepare for freeing it. If you want to wait for
46  * all running rethook handler before calling rethook_free(), you need to
47  * call this first and wait RCU, and call rethook_free().
48  */
49 void rethook_stop(struct rethook *rh)
50 {
51 	WRITE_ONCE(rh->handler, NULL);
52 }
53 
54 /**
55  * rethook_free() - Free struct rethook.
56  * @rh: the struct rethook to be freed.
57  *
58  * Free the rethook. Before calling this function, user must ensure the
59  * @rh::data is cleaned if needed (or, the handler can access it after
60  * calling this function.) This function will set the @rh to be freed
61  * after all rethook_node are freed (not soon). And the caller must
62  * not touch @rh after calling this.
63  */
64 void rethook_free(struct rethook *rh)
65 {
66 	WRITE_ONCE(rh->handler, NULL);
67 
68 	call_rcu(&rh->rcu, rethook_free_rcu);
69 }
70 
71 static int rethook_init_node(void *nod, void *context)
72 {
73 	struct rethook_node *node = nod;
74 
75 	node->rethook = context;
76 	return 0;
77 }
78 
79 static int rethook_fini_pool(struct objpool_head *head, void *context)
80 {
81 	kfree(context);
82 	return 0;
83 }
84 
85 /**
86  * rethook_alloc() - Allocate struct rethook.
87  * @data: a data to pass the @handler when hooking the return.
88  * @handler: the return hook callback function, must NOT be NULL
89  * @size: node size: rethook node and additional data
90  * @num: number of rethook nodes to be preallocated
91  *
92  * Allocate and initialize a new rethook with @data and @handler.
93  * Return pointer of new rethook, or error codes for failures.
94  *
95  * Note that @handler == NULL means this rethook is going to be freed.
96  */
97 struct rethook *rethook_alloc(void *data, rethook_handler_t handler,
98 			      int size, int num)
99 {
100 	struct rethook *rh;
101 
102 	if (!handler || num <= 0 || size < sizeof(struct rethook_node))
103 		return ERR_PTR(-EINVAL);
104 
105 	rh = kzalloc(sizeof(struct rethook), GFP_KERNEL);
106 	if (!rh)
107 		return ERR_PTR(-ENOMEM);
108 
109 	rh->data = data;
110 	rh->handler = handler;
111 
112 	/* initialize the objpool for rethook nodes */
113 	if (objpool_init(&rh->pool, num, size, GFP_KERNEL, rh,
114 			 rethook_init_node, rethook_fini_pool)) {
115 		kfree(rh);
116 		return ERR_PTR(-ENOMEM);
117 	}
118 	return rh;
119 }
120 
121 static void free_rethook_node_rcu(struct rcu_head *head)
122 {
123 	struct rethook_node *node = container_of(head, struct rethook_node, rcu);
124 	struct rethook *rh = node->rethook;
125 
126 	objpool_drop(node, &rh->pool);
127 }
128 
129 /**
130  * rethook_recycle() - return the node to rethook.
131  * @node: The struct rethook_node to be returned.
132  *
133  * Return back the @node to @node::rethook. If the @node::rethook is already
134  * marked as freed, this will free the @node.
135  */
136 void rethook_recycle(struct rethook_node *node)
137 {
138 	lockdep_assert_preemption_disabled();
139 
140 	if (likely(READ_ONCE(node->rethook->handler)))
141 		objpool_push(node, &node->rethook->pool);
142 	else
143 		call_rcu(&node->rcu, free_rethook_node_rcu);
144 }
145 NOKPROBE_SYMBOL(rethook_recycle);
146 
147 /**
148  * rethook_try_get() - get an unused rethook node.
149  * @rh: The struct rethook which pools the nodes.
150  *
151  * Get an unused rethook node from @rh. If the node pool is empty, this
152  * will return NULL. Caller must disable preemption.
153  */
154 struct rethook_node *rethook_try_get(struct rethook *rh)
155 {
156 	rethook_handler_t handler = READ_ONCE(rh->handler);
157 
158 	lockdep_assert_preemption_disabled();
159 
160 	/* Check whether @rh is going to be freed. */
161 	if (unlikely(!handler))
162 		return NULL;
163 
164 	/*
165 	 * This expects the caller will set up a rethook on a function entry.
166 	 * When the function returns, the rethook will eventually be reclaimed
167 	 * or released in the rethook_recycle() with call_rcu().
168 	 * This means the caller must be run in the RCU-availabe context.
169 	 */
170 	if (unlikely(!rcu_is_watching()))
171 		return NULL;
172 
173 	return (struct rethook_node *)objpool_pop(&rh->pool);
174 }
175 NOKPROBE_SYMBOL(rethook_try_get);
176 
177 /**
178  * rethook_hook() - Hook the current function return.
179  * @node: The struct rethook node to hook the function return.
180  * @regs: The struct pt_regs for the function entry.
181  * @mcount: True if this is called from mcount(ftrace) context.
182  *
183  * Hook the current running function return. This must be called when the
184  * function entry (or at least @regs must be the registers of the function
185  * entry.) @mcount is used for identifying the context. If this is called
186  * from ftrace (mcount) callback, @mcount must be set true. If this is called
187  * from the real function entry (e.g. kprobes) @mcount must be set false.
188  * This is because the way to hook the function return depends on the context.
189  */
190 void rethook_hook(struct rethook_node *node, struct pt_regs *regs, bool mcount)
191 {
192 	arch_rethook_prepare(node, regs, mcount);
193 	__llist_add(&node->llist, &current->rethooks);
194 }
195 NOKPROBE_SYMBOL(rethook_hook);
196 
197 /* This assumes the 'tsk' is the current task or is not running. */
198 static unsigned long __rethook_find_ret_addr(struct task_struct *tsk,
199 					     struct llist_node **cur)
200 {
201 	struct rethook_node *rh = NULL;
202 	struct llist_node *node = *cur;
203 
204 	if (!node)
205 		node = tsk->rethooks.first;
206 	else
207 		node = node->next;
208 
209 	while (node) {
210 		rh = container_of(node, struct rethook_node, llist);
211 		if (rh->ret_addr != (unsigned long)arch_rethook_trampoline) {
212 			*cur = node;
213 			return rh->ret_addr;
214 		}
215 		node = node->next;
216 	}
217 	return 0;
218 }
219 NOKPROBE_SYMBOL(__rethook_find_ret_addr);
220 
221 /**
222  * rethook_find_ret_addr -- Find correct return address modified by rethook
223  * @tsk: Target task
224  * @frame: A frame pointer
225  * @cur: a storage of the loop cursor llist_node pointer for next call
226  *
227  * Find the correct return address modified by a rethook on @tsk in unsigned
228  * long type.
229  * The @tsk must be 'current' or a task which is not running. @frame is a hint
230  * to get the currect return address - which is compared with the
231  * rethook::frame field. The @cur is a loop cursor for searching the
232  * kretprobe return addresses on the @tsk. The '*@cur' should be NULL at the
233  * first call, but '@cur' itself must NOT NULL.
234  *
235  * Returns found address value or zero if not found.
236  */
237 unsigned long rethook_find_ret_addr(struct task_struct *tsk, unsigned long frame,
238 				    struct llist_node **cur)
239 {
240 	struct rethook_node *rhn = NULL;
241 	unsigned long ret;
242 
243 	if (WARN_ON_ONCE(!cur))
244 		return 0;
245 
246 	if (WARN_ON_ONCE(tsk != current && task_is_running(tsk)))
247 		return 0;
248 
249 	do {
250 		ret = __rethook_find_ret_addr(tsk, cur);
251 		if (!ret)
252 			break;
253 		rhn = container_of(*cur, struct rethook_node, llist);
254 	} while (rhn->frame != frame);
255 
256 	return ret;
257 }
258 NOKPROBE_SYMBOL(rethook_find_ret_addr);
259 
260 void __weak arch_rethook_fixup_return(struct pt_regs *regs,
261 				      unsigned long correct_ret_addr)
262 {
263 	/*
264 	 * Do nothing by default. If the architecture which uses a
265 	 * frame pointer to record real return address on the stack,
266 	 * it should fill this function to fixup the return address
267 	 * so that stacktrace works from the rethook handler.
268 	 */
269 }
270 
271 /* This function will be called from each arch-defined trampoline. */
272 unsigned long rethook_trampoline_handler(struct pt_regs *regs,
273 					 unsigned long frame)
274 {
275 	struct llist_node *first, *node = NULL;
276 	unsigned long correct_ret_addr;
277 	rethook_handler_t handler;
278 	struct rethook_node *rhn;
279 
280 	correct_ret_addr = __rethook_find_ret_addr(current, &node);
281 	if (!correct_ret_addr) {
282 		pr_err("rethook: Return address not found! Maybe there is a bug in the kernel\n");
283 		BUG_ON(1);
284 	}
285 
286 	instruction_pointer_set(regs, correct_ret_addr);
287 
288 	/*
289 	 * These loops must be protected from rethook_free_rcu() because those
290 	 * are accessing 'rhn->rethook'.
291 	 */
292 	preempt_disable_notrace();
293 
294 	/*
295 	 * Run the handler on the shadow stack. Do not unlink the list here because
296 	 * stackdump inside the handlers needs to decode it.
297 	 */
298 	first = current->rethooks.first;
299 	while (first) {
300 		rhn = container_of(first, struct rethook_node, llist);
301 		if (WARN_ON_ONCE(rhn->frame != frame))
302 			break;
303 		handler = READ_ONCE(rhn->rethook->handler);
304 		if (handler)
305 			handler(rhn, rhn->rethook->data,
306 				correct_ret_addr, regs);
307 
308 		if (first == node)
309 			break;
310 		first = first->next;
311 	}
312 
313 	/* Fixup registers for returning to correct address. */
314 	arch_rethook_fixup_return(regs, correct_ret_addr);
315 
316 	/* Unlink used shadow stack */
317 	first = current->rethooks.first;
318 	current->rethooks.first = node->next;
319 	node->next = NULL;
320 
321 	while (first) {
322 		rhn = container_of(first, struct rethook_node, llist);
323 		first = first->next;
324 		rethook_recycle(rhn);
325 	}
326 	preempt_enable_notrace();
327 
328 	return correct_ret_addr;
329 }
330 NOKPROBE_SYMBOL(rethook_trampoline_handler);
331