xref: /linux/arch/loongarch/kernel/unwind_orc.c (revision 4cd641a79e69270a062777f64a0dd330abb9044a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 #include <linux/export.h>
3 #include <linux/module.h>
4 #include <linux/objtool.h>
5 #include <linux/sort.h>
6 #include <asm/exception.h>
7 #include <asm/orc_header.h>
8 #include <asm/orc_lookup.h>
9 #include <asm/orc_types.h>
10 #include <asm/ptrace.h>
11 #include <asm/setup.h>
12 #include <asm/stacktrace.h>
13 #include <asm/tlb.h>
14 #include <asm/unwind.h>
15 
16 ORC_HEADER;
17 
18 #define orc_warn(fmt, ...) \
19 	printk_deferred_once(KERN_WARNING "WARNING: " fmt, ##__VA_ARGS__)
20 
21 extern int __start_orc_unwind_ip[];
22 extern int __stop_orc_unwind_ip[];
23 extern struct orc_entry __start_orc_unwind[];
24 extern struct orc_entry __stop_orc_unwind[];
25 
26 static bool orc_init __ro_after_init;
27 static unsigned int lookup_num_blocks __ro_after_init;
28 
29 /* Fake frame pointer entry -- used as a fallback for generated code */
30 static struct orc_entry orc_fp_entry = {
31 	.sp_reg		= ORC_REG_FP,
32 	.sp_offset	= 16,
33 	.fp_reg		= ORC_REG_PREV_SP,
34 	.fp_offset	= -16,
35 	.ra_reg		= ORC_REG_PREV_SP,
36 	.ra_offset	= -8,
37 	.type		= ORC_TYPE_CALL
38 };
39 
40 /*
41  * If we crash with IP==0, the last successfully executed instruction
42  * was probably an indirect function call with a NULL function pointer,
43  * and we don't have unwind information for NULL.
44  * This hardcoded ORC entry for IP==0 allows us to unwind from a NULL function
45  * pointer into its parent and then continue normally from there.
46  */
47 static struct orc_entry orc_null_entry = {
48 	.sp_reg		= ORC_REG_SP,
49 	.sp_offset	= sizeof(long),
50 	.fp_reg		= ORC_REG_UNDEFINED,
51 	.type		= ORC_TYPE_CALL
52 };
53 
54 static inline unsigned long orc_ip(const int *ip)
55 {
56 	return (unsigned long)ip + *ip;
57 }
58 
59 static struct orc_entry *__orc_find(int *ip_table, struct orc_entry *u_table,
60 				    unsigned int num_entries, unsigned long ip)
61 {
62 	int *first = ip_table;
63 	int *mid = first, *found = first;
64 	int *last = ip_table + num_entries - 1;
65 
66 	if (!num_entries)
67 		return NULL;
68 
69 	/*
70 	 * Do a binary range search to find the rightmost duplicate of a given
71 	 * starting address.  Some entries are section terminators which are
72 	 * "weak" entries for ensuring there are no gaps.  They should be
73 	 * ignored when they conflict with a real entry.
74 	 */
75 	while (first <= last) {
76 		mid = first + ((last - first) / 2);
77 
78 		if (orc_ip(mid) <= ip) {
79 			found = mid;
80 			first = mid + 1;
81 		} else
82 			last = mid - 1;
83 	}
84 
85 	return u_table + (found - ip_table);
86 }
87 
88 #ifdef CONFIG_MODULES
89 static struct orc_entry *orc_module_find(unsigned long ip)
90 {
91 	struct module *mod;
92 
93 	mod = __module_address(ip);
94 	if (!mod || !mod->arch.orc_unwind || !mod->arch.orc_unwind_ip)
95 		return NULL;
96 
97 	return __orc_find(mod->arch.orc_unwind_ip, mod->arch.orc_unwind, mod->arch.num_orcs, ip);
98 }
99 #else
100 static struct orc_entry *orc_module_find(unsigned long ip)
101 {
102 	return NULL;
103 }
104 #endif
105 
106 #ifdef CONFIG_DYNAMIC_FTRACE
107 static struct orc_entry *orc_find(unsigned long ip);
108 
109 /*
110  * Ftrace dynamic trampolines do not have orc entries of their own.
111  * But they are copies of the ftrace entries that are static and
112  * defined in ftrace_*.S, which do have orc entries.
113  *
114  * If the unwinder comes across a ftrace trampoline, then find the
115  * ftrace function that was used to create it, and use that ftrace
116  * function's orc entry, as the placement of the return code in
117  * the stack will be identical.
118  */
119 static struct orc_entry *orc_ftrace_find(unsigned long ip)
120 {
121 	struct ftrace_ops *ops;
122 	unsigned long tramp_addr, offset;
123 
124 	ops = ftrace_ops_trampoline(ip);
125 	if (!ops)
126 		return NULL;
127 
128 	/* Set tramp_addr to the start of the code copied by the trampoline */
129 	if (ops->flags & FTRACE_OPS_FL_SAVE_REGS)
130 		tramp_addr = (unsigned long)ftrace_regs_caller;
131 	else
132 		tramp_addr = (unsigned long)ftrace_caller;
133 
134 	/* Now place tramp_addr to the location within the trampoline ip is at */
135 	offset = ip - ops->trampoline;
136 	tramp_addr += offset;
137 
138 	/* Prevent unlikely recursion */
139 	if (ip == tramp_addr)
140 		return NULL;
141 
142 	return orc_find(tramp_addr);
143 }
144 #else
145 static struct orc_entry *orc_ftrace_find(unsigned long ip)
146 {
147 	return NULL;
148 }
149 #endif
150 
151 static struct orc_entry *orc_find(unsigned long ip)
152 {
153 	static struct orc_entry *orc;
154 
155 	if (ip == 0)
156 		return &orc_null_entry;
157 
158 	/* For non-init vmlinux addresses, use the fast lookup table: */
159 	if (ip >= LOOKUP_START_IP && ip < LOOKUP_STOP_IP) {
160 		unsigned int idx, start, stop;
161 
162 		idx = (ip - LOOKUP_START_IP) / LOOKUP_BLOCK_SIZE;
163 
164 		if (unlikely((idx >= lookup_num_blocks-1))) {
165 			orc_warn("WARNING: bad lookup idx: idx=%u num=%u ip=%pB\n",
166 				 idx, lookup_num_blocks, (void *)ip);
167 			return NULL;
168 		}
169 
170 		start = orc_lookup[idx];
171 		stop = orc_lookup[idx + 1] + 1;
172 
173 		if (unlikely((__start_orc_unwind + start >= __stop_orc_unwind) ||
174 			     (__start_orc_unwind + stop > __stop_orc_unwind))) {
175 			orc_warn("WARNING: bad lookup value: idx=%u num=%u start=%u stop=%u ip=%pB\n",
176 				 idx, lookup_num_blocks, start, stop, (void *)ip);
177 			return NULL;
178 		}
179 
180 		return __orc_find(__start_orc_unwind_ip + start,
181 				  __start_orc_unwind + start, stop - start, ip);
182 	}
183 
184 	/* vmlinux .init slow lookup: */
185 	if (is_kernel_inittext(ip))
186 		return __orc_find(__start_orc_unwind_ip, __start_orc_unwind,
187 				  __stop_orc_unwind_ip - __start_orc_unwind_ip, ip);
188 
189 	/* Module lookup: */
190 	orc = orc_module_find(ip);
191 	if (orc)
192 		return orc;
193 
194 	return orc_ftrace_find(ip);
195 }
196 
197 #ifdef CONFIG_MODULES
198 
199 static DEFINE_MUTEX(sort_mutex);
200 static int *cur_orc_ip_table = __start_orc_unwind_ip;
201 static struct orc_entry *cur_orc_table = __start_orc_unwind;
202 
203 static void orc_sort_swap(void *_a, void *_b, int size)
204 {
205 	int delta = _b - _a;
206 	int *a = _a, *b = _b, tmp;
207 	struct orc_entry *orc_a, *orc_b;
208 
209 	/* Swap the .orc_unwind_ip entries: */
210 	tmp = *a;
211 	*a = *b + delta;
212 	*b = tmp - delta;
213 
214 	/* Swap the corresponding .orc_unwind entries: */
215 	orc_a = cur_orc_table + (a - cur_orc_ip_table);
216 	orc_b = cur_orc_table + (b - cur_orc_ip_table);
217 	swap(*orc_a, *orc_b);
218 }
219 
220 static int orc_sort_cmp(const void *_a, const void *_b)
221 {
222 	const int *a = _a, *b = _b;
223 	unsigned long a_val = orc_ip(a);
224 	unsigned long b_val = orc_ip(b);
225 	struct orc_entry *orc_a;
226 
227 	if (a_val > b_val)
228 		return 1;
229 	if (a_val < b_val)
230 		return -1;
231 
232 	/*
233 	 * The "weak" section terminator entries need to always be first
234 	 * to ensure the lookup code skips them in favor of real entries.
235 	 * These terminator entries exist to handle any gaps created by
236 	 * whitelisted .o files which didn't get objtool generation.
237 	 */
238 	orc_a = cur_orc_table + (a - cur_orc_ip_table);
239 
240 	return orc_a->type == ORC_TYPE_UNDEFINED ? -1 : 1;
241 }
242 
243 void unwind_module_init(struct module *mod, void *_orc_ip, size_t orc_ip_size,
244 			void *_orc, size_t orc_size)
245 {
246 	int *orc_ip = _orc_ip;
247 	struct orc_entry *orc = _orc;
248 	unsigned int num_entries = orc_ip_size / sizeof(int);
249 
250 	WARN_ON_ONCE(orc_ip_size % sizeof(int) != 0 ||
251 		     orc_size % sizeof(*orc) != 0 ||
252 		     num_entries != orc_size / sizeof(*orc));
253 
254 	/*
255 	 * The 'cur_orc_*' globals allow the orc_sort_swap() callback to
256 	 * associate an .orc_unwind_ip table entry with its corresponding
257 	 * .orc_unwind entry so they can both be swapped.
258 	 */
259 	mutex_lock(&sort_mutex);
260 	cur_orc_ip_table = orc_ip;
261 	cur_orc_table = orc;
262 	sort(orc_ip, num_entries, sizeof(int), orc_sort_cmp, orc_sort_swap);
263 	mutex_unlock(&sort_mutex);
264 
265 	mod->arch.orc_unwind_ip = orc_ip;
266 	mod->arch.orc_unwind = orc;
267 	mod->arch.num_orcs = num_entries;
268 }
269 #endif
270 
271 void __init unwind_init(void)
272 {
273 	int i;
274 	size_t orc_size = (void *)__stop_orc_unwind - (void *)__start_orc_unwind;
275 	size_t orc_ip_size = (void *)__stop_orc_unwind_ip - (void *)__start_orc_unwind_ip;
276 	size_t num_entries = orc_ip_size / sizeof(int);
277 	struct orc_entry *orc;
278 
279 	if (!num_entries || orc_ip_size % sizeof(int) != 0 ||
280 	    orc_size % sizeof(struct orc_entry) != 0 ||
281 	    num_entries != orc_size / sizeof(struct orc_entry)) {
282 		orc_warn("WARNING: Bad or missing .orc_unwind table.  Disabling unwinder.\n");
283 		return;
284 	}
285 
286 	/*
287 	 * Note, the orc_unwind and orc_unwind_ip tables were already
288 	 * sorted at build time via the 'sorttable' tool.
289 	 * It's ready for binary search straight away, no need to sort it.
290 	 */
291 
292 	/* Initialize the fast lookup table: */
293 	lookup_num_blocks = orc_lookup_end - orc_lookup;
294 	for (i = 0; i < lookup_num_blocks-1; i++) {
295 		orc = __orc_find(__start_orc_unwind_ip, __start_orc_unwind,
296 				 num_entries, LOOKUP_START_IP + (LOOKUP_BLOCK_SIZE * i));
297 		if (!orc) {
298 			orc_warn("WARNING: Corrupt .orc_unwind table.  Disabling unwinder.\n");
299 			return;
300 		}
301 
302 		orc_lookup[i] = orc - __start_orc_unwind;
303 	}
304 
305 	/* Initialize the ending block: */
306 	orc = __orc_find(__start_orc_unwind_ip, __start_orc_unwind, num_entries, LOOKUP_STOP_IP);
307 	if (!orc) {
308 		orc_warn("WARNING: Corrupt .orc_unwind table.  Disabling unwinder.\n");
309 		return;
310 	}
311 	orc_lookup[lookup_num_blocks-1] = orc - __start_orc_unwind;
312 
313 	orc_init = true;
314 }
315 
316 static inline bool on_stack(struct stack_info *info, unsigned long addr, size_t len)
317 {
318 	unsigned long begin = info->begin;
319 	unsigned long end   = info->end;
320 
321 	return (info->type != STACK_TYPE_UNKNOWN &&
322 		addr >= begin && addr < end && addr + len > begin && addr + len <= end);
323 }
324 
325 static bool stack_access_ok(struct unwind_state *state, unsigned long addr, size_t len)
326 {
327 	struct stack_info *info = &state->stack_info;
328 
329 	if (on_stack(info, addr, len))
330 		return true;
331 
332 	return !get_stack_info(addr, state->task, info) && on_stack(info, addr, len);
333 }
334 
335 unsigned long unwind_get_return_address(struct unwind_state *state)
336 {
337 	return __unwind_get_return_address(state);
338 }
339 EXPORT_SYMBOL_GPL(unwind_get_return_address);
340 
341 void unwind_start(struct unwind_state *state, struct task_struct *task,
342 		    struct pt_regs *regs)
343 {
344 	__unwind_start(state, task, regs);
345 	state->type = UNWINDER_ORC;
346 	if (!unwind_done(state) && !__kernel_text_address(state->pc))
347 		unwind_next_frame(state);
348 }
349 EXPORT_SYMBOL_GPL(unwind_start);
350 
351 static inline unsigned long bt_address(unsigned long ra)
352 {
353 	extern unsigned long eentry;
354 
355 	if (ra >= eentry && ra < eentry +  EXCCODE_INT_END * VECSIZE) {
356 		unsigned long func;
357 		unsigned long type = (ra - eentry) / VECSIZE;
358 		unsigned long offset = (ra - eentry) % VECSIZE;
359 
360 		switch (type) {
361 		case 0 ... EXCCODE_INT_START - 1:
362 			func = (unsigned long)exception_table[type];
363 			break;
364 		case EXCCODE_INT_START ... EXCCODE_INT_END:
365 			func = (unsigned long)handle_vint;
366 			break;
367 		default:
368 			func = (unsigned long)handle_reserved;
369 			break;
370 		}
371 
372 		ra = func + offset;
373 	}
374 
375 	if (__kernel_text_address(ra))
376 		return ra;
377 
378 	return 0;
379 }
380 
381 bool unwind_next_frame(struct unwind_state *state)
382 {
383 	unsigned long *p, pc;
384 	struct pt_regs *regs;
385 	struct orc_entry *orc;
386 	struct stack_info *info = &state->stack_info;
387 
388 	if (unwind_done(state))
389 		return false;
390 
391 	/* Don't let modules unload while we're reading their ORC data. */
392 	guard(rcu)();
393 
394 	orc = orc_find(state->pc);
395 	if (!orc) {
396 		/*
397 		 * As a fallback, try to assume this code uses a frame pointer.
398 		 * This is useful for generated code, like BPF, which ORC
399 		 * doesn't know about.  This is just a guess, so the rest of
400 		 * the unwind is no longer considered reliable.
401 		 */
402 		orc = &orc_fp_entry;
403 		state->error = true;
404 	} else {
405 		if (orc->type == ORC_TYPE_UNDEFINED)
406 			goto err;
407 
408 		if (orc->type == ORC_TYPE_END_OF_STACK)
409 			goto end;
410 	}
411 
412 	switch (orc->sp_reg) {
413 	case ORC_REG_SP:
414 		if (info->type == STACK_TYPE_IRQ && state->sp == info->end)
415 			orc->type = ORC_TYPE_REGS;
416 		else
417 			state->sp = state->sp + orc->sp_offset;
418 		break;
419 	case ORC_REG_FP:
420 		state->sp = state->fp;
421 		break;
422 	default:
423 		orc_warn("unknown SP base reg %d at %pB\n", orc->sp_reg, (void *)state->pc);
424 		goto err;
425 	}
426 
427 	switch (orc->fp_reg) {
428 	case ORC_REG_PREV_SP:
429 		p = (unsigned long *)(state->sp + orc->fp_offset);
430 		if (!stack_access_ok(state, (unsigned long)p, sizeof(unsigned long)))
431 			goto err;
432 
433 		state->fp = *p;
434 		break;
435 	case ORC_REG_UNDEFINED:
436 		/* Nothing. */
437 		break;
438 	default:
439 		orc_warn("unknown FP base reg %d at %pB\n", orc->fp_reg, (void *)state->pc);
440 		goto err;
441 	}
442 
443 	switch (orc->type) {
444 	case ORC_TYPE_CALL:
445 		if (orc->ra_reg == ORC_REG_PREV_SP) {
446 			p = (unsigned long *)(state->sp + orc->ra_offset);
447 			if (!stack_access_ok(state, (unsigned long)p, sizeof(unsigned long)))
448 				goto err;
449 
450 			pc = unwind_graph_addr(state, *p, state->sp);
451 			pc -= LOONGARCH_INSN_SIZE;
452 		} else if (orc->ra_reg == ORC_REG_UNDEFINED) {
453 			if (!state->ra || state->ra == state->pc)
454 				goto err;
455 
456 			pc = unwind_graph_addr(state, state->ra, state->sp);
457 			pc -=  LOONGARCH_INSN_SIZE;
458 			state->ra = 0;
459 		} else {
460 			orc_warn("unknown ra base reg %d at %pB\n", orc->ra_reg, (void *)state->pc);
461 			goto err;
462 		}
463 		break;
464 	case ORC_TYPE_REGS:
465 		if (info->type == STACK_TYPE_IRQ && state->sp == info->end)
466 			regs = (struct pt_regs *)info->next_sp;
467 		else
468 			regs = (struct pt_regs *)state->sp;
469 
470 		if (!stack_access_ok(state, (unsigned long)regs, sizeof(*regs)))
471 			goto err;
472 
473 		if ((info->end == (unsigned long)regs + sizeof(*regs)) &&
474 		    !regs->regs[3] && !regs->regs[1])
475 			goto end;
476 
477 		if (user_mode(regs))
478 			goto end;
479 
480 		pc = regs->csr_era;
481 		if (!__kernel_text_address(pc))
482 			goto err;
483 
484 		state->sp = regs->regs[3];
485 		state->ra = regs->regs[1];
486 		state->fp = regs->regs[22];
487 		get_stack_info(state->sp, state->task, info);
488 
489 		break;
490 	default:
491 		orc_warn("unknown .orc_unwind entry type %d at %pB\n", orc->type, (void *)state->pc);
492 		goto err;
493 	}
494 
495 	state->pc = bt_address(pc);
496 	if (!state->pc) {
497 		pr_err("cannot find unwind pc at %p\n", (void *)pc);
498 		goto err;
499 	}
500 
501 	return true;
502 
503 err:
504 	state->error = true;
505 
506 end:
507 	state->stack_info.type = STACK_TYPE_UNKNOWN;
508 	return false;
509 }
510 EXPORT_SYMBOL_GPL(unwind_next_frame);
511