xref: /freebsd-14.2/sys/arm/arm/unwind.c (revision f9984cda)
1 /*
2  * Copyright 2013-2014 Andrew Turner.
3  * Copyright 2013-2014 Ian Lepore.
4  * Copyright 2013-2014 Rui Paulo.
5  * Copyright 2013 Eitan Adler.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are
10  * met:
11  *
12  *  1. Redistributions of source code must retain the above copyright
13  *     notice, this list of conditions and the following disclaimer.
14  *  2. Redistributions in binary form must reproduce the above copyright
15  *     notice, this list of conditions and the following disclaimer in the
16  *     documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE
22  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
25  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
26  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
27  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
28  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 #include <sys/param.h>
33 #include <sys/kernel.h>
34 #include <sys/linker.h>
35 #include <sys/malloc.h>
36 #include <sys/proc.h>
37 #include <sys/queue.h>
38 #include <sys/systm.h>
39 
40 #include <machine/machdep.h>
41 #include <machine/stack.h>
42 
43 #include "linker_if.h"
44 
45 /*
46  * Definitions for the instruction interpreter.
47  *
48  * The ARM EABI specifies how to perform the frame unwinding in the
49  * Exception Handling ABI for the ARM Architecture document. To perform
50  * the unwind we need to know the initial frame pointer, stack pointer,
51  * link register and program counter. We then find the entry within the
52  * index table that points to the function the program counter is within.
53  * This gives us either a list of three instructions to process, a 31-bit
54  * relative offset to a table of instructions, or a value telling us
55  * we can't unwind any further.
56  *
57  * When we have the instructions to process we need to decode them
58  * following table 4 in section 9.3. This describes a collection of bit
59  * patterns to encode that steps to take to update the stack pointer and
60  * link register to the correct values at the start of the function.
61  */
62 
63 /* A special case when we are unable to unwind past this function */
64 #define	EXIDX_CANTUNWIND	1
65 
66 /*
67  * Entry types.
68  * These are the only entry types that have been seen in the kernel.
69  */
70 #define	ENTRY_MASK	0xff000000
71 #define	ENTRY_ARM_SU16	0x80000000
72 #define	ENTRY_ARM_LU16	0x81000000
73 
74 /* Instruction masks. */
75 #define	INSN_VSP_MASK		0xc0
76 #define	INSN_VSP_SIZE_MASK	0x3f
77 #define	INSN_STD_MASK		0xf0
78 #define	INSN_STD_DATA_MASK	0x0f
79 #define	INSN_POP_TYPE_MASK	0x08
80 #define	INSN_POP_COUNT_MASK	0x07
81 #define	INSN_VSP_LARGE_INC_MASK	0xff
82 
83 /* Instruction definitions */
84 #define	INSN_VSP_INC		0x00
85 #define	INSN_VSP_DEC		0x40
86 #define	INSN_POP_MASKED		0x80
87 #define	INSN_VSP_REG		0x90
88 #define	INSN_POP_COUNT		0xa0
89 #define	INSN_FINISH		0xb0
90 #define	INSN_POP_REGS		0xb1
91 #define	INSN_VSP_LARGE_INC	0xb2
92 
93 /* An item in the exception index table */
94 struct unwind_idx {
95 	uint32_t offset;
96 	uint32_t insn;
97 };
98 
99 /*
100  * Local cache of unwind info for loaded modules.
101  *
102  * To unwind the stack through the code in a loaded module, we need to access
103  * the module's exidx unwind data.  To locate that data, one must search the
104  * elf section headers for the SHT_ARM_EXIDX section.  Those headers are
105  * available at the time the module is being loaded, but are discarded by time
106  * the load process has completed.  Code in kern/link_elf.c locates the data we
107  * need and stores it into the linker_file structure before calling the arm
108  * machdep routine for handling loaded modules (in arm/elf_machdep.c).  That
109  * function calls into this code to pass along the unwind info, which we save
110  * into one of these module_info structures.
111  *
112  * Because we have to help stack(9) gather stack info at any time, including in
113  * contexts where sleeping is not allowed, we cannot use linker_file_foreach()
114  * to walk the kernel's list of linker_file structs, because doing so requires
115  * acquiring an exclusive sx_lock.  So instead, we keep a local list of these
116  * structures, one for each loaded module (and one for the kernel itself that we
117  * synthesize at init time).  New entries are added to the end of this list as
118  * needed, but entries are never deleted from the list.  Instead, they are
119  * cleared out in-place to mark them as unused.  That means the code doing stack
120  * unwinding can always safely walk the list without locking, because the
121  * structure of the list never changes in a way that would cause the walker to
122  * follow a bad link.
123  *
124  * A cleared-out entry on the list has module start=UINTPTR_MAX and end=0, so
125  * start <= addr < end cannot be true for any value of addr being searched for.
126  * We also don't have to worry about races where we look up the unwind info just
127  * before a module is unloaded and try to access it concurrently with or just
128  * after the unloading happens in another thread, because that means the path of
129  * execution leads through a now-unloaded module, and that's already well into
130  * undefined-behavior territory.
131  *
132  * List entries marked as unused get reused when new modules are loaded.  We
133  * don't worry about holding a few unused bytes of memory in the list after
134  * unloading a module.
135  */
136 struct module_info {
137 	uintptr_t	module_start;   /* Start of loaded module */
138 	uintptr_t	module_end;     /* End of loaded module */
139 	uintptr_t	exidx_start;    /* Start of unwind data */
140 	uintptr_t	exidx_end;      /* End of unwind data */
141 	STAILQ_ENTRY(module_info)
142 			link;           /* Link to next entry */
143 };
144 static STAILQ_HEAD(, module_info) module_list;
145 
146 /*
147  * Hide ugly casting in somewhat-less-ugly macros.
148  *  CADDR - cast a pointer or number to caddr_t.
149  *  UADDR - cast a pointer or number to uintptr_t.
150  */
151 #define	CADDR(addr)	((caddr_t)(void*)(uintptr_t)(addr))
152 #define	UADDR(addr)	((uintptr_t)(addr))
153 
154 /*
155  * Clear the info in an existing module_info entry on the list.  The
156  * module_start/end addresses are set to values that cannot match any real
157  * memory address.  The entry remains on the list, but will be ignored until it
158  * is populated with new data.
159  */
160 static void
clear_module_info(struct module_info * info)161 clear_module_info(struct module_info *info)
162 {
163 	info->module_start = UINTPTR_MAX;
164 	info->module_end   = 0;
165 }
166 
167 /*
168  * Populate an existing module_info entry (which is already on the list) with
169  * the info for a new module.
170  */
171 static void
populate_module_info(struct module_info * info,linker_file_t lf)172 populate_module_info(struct module_info *info, linker_file_t lf)
173 {
174 
175 	/*
176 	 * Careful!  The module_start and module_end fields must not be set
177 	 * until all other data in the structure is valid.
178 	 */
179 	info->exidx_start  = UADDR(lf->exidx_addr);
180 	info->exidx_end    = UADDR(lf->exidx_addr) + lf->exidx_size;
181 	info->module_start = UADDR(lf->address);
182 	info->module_end   = UADDR(lf->address) + lf->size;
183 }
184 
185 /*
186  * Create a new empty module_info entry and add it to the tail of the list.
187  */
188 static struct module_info *
create_module_info(void)189 create_module_info(void)
190 {
191 	struct module_info *info;
192 
193 	info = malloc(sizeof(*info), M_CACHE, M_WAITOK | M_ZERO);
194 	clear_module_info(info);
195 	STAILQ_INSERT_TAIL(&module_list, info, link);
196 	return (info);
197 }
198 
199 /*
200  * Search for a module_info entry on the list whose address range contains the
201  * given address.  If the search address is zero (no module will be loaded at
202  * zero), then we're looking for an empty item to reuse, which is indicated by
203  * module_start being set to UINTPTR_MAX in the entry.
204  */
205 static struct module_info *
find_module_info(uintptr_t addr)206 find_module_info(uintptr_t addr)
207 {
208 	struct module_info *info;
209 
210 	STAILQ_FOREACH(info, &module_list, link) {
211 		if ((addr >= info->module_start && addr < info->module_end) ||
212 		    (addr == 0 && info->module_start == UINTPTR_MAX))
213 			return (info);
214 	}
215 	return (NULL);
216 }
217 
218 /*
219  * Handle the loading of a new module by populating a module_info for it.  This
220  * is called for both preloaded and dynamically loaded modules.
221  */
222 void
unwind_module_loaded(struct linker_file * lf)223 unwind_module_loaded(struct linker_file *lf)
224 {
225 	struct module_info *info;
226 
227 	/*
228 	 * A module that contains only data may have no unwind info; don't
229 	 * create any module info for it.
230 	 */
231 	if (lf->exidx_size == 0)
232 		return;
233 
234 	/*
235 	 * Find an unused entry in the existing list to reuse.  If we don't find
236 	 * one, create a new one and link it into the list.  This is the only
237 	 * place the module_list is modified.  Adding a new entry to the list
238 	 * will not perturb any other threads currently walking the list.  This
239 	 * function is invoked while kern_linker is still holding its lock
240 	 * to prevent its module list from being modified, so we don't have to
241 	 * worry about racing other threads doing an insert concurrently.
242 	 */
243 	if ((info = find_module_info(0)) == NULL) {
244 		info = create_module_info();
245 	}
246 	populate_module_info(info, lf);
247 }
248 
249 /* Handle the unloading of a module. */
250 void
unwind_module_unloaded(struct linker_file * lf)251 unwind_module_unloaded(struct linker_file *lf)
252 {
253 	struct module_info *info;
254 
255 	/*
256 	 * A module that contains only data may have no unwind info and there
257 	 * won't be a list entry for it.
258 	 */
259 	if (lf->exidx_size == 0)
260 		return;
261 
262 	/*
263 	 * When a module is unloaded, we clear the info out of its entry in the
264 	 * module list, making that entry available for later reuse.
265 	 */
266 	if ((info = find_module_info(UADDR(lf->address))) == NULL) {
267 		printf("arm unwind: module '%s' not on list at unload time\n",
268 		    lf->filename);
269 		return;
270 	}
271 	clear_module_info(info);
272 }
273 
274 /*
275  * Initialization must run fairly early, as soon as malloc(9) is available, and
276  * definitely before witness, which uses stack(9).  We synthesize a module_info
277  * entry for the kernel, because unwind_module_loaded() doesn't get called for
278  * it.  Also, it is unlike other modules in that the elf metadata for locating
279  * the unwind tables might be stripped, so instead we have to use the
280  * _exidx_start/end symbols created by ldscript.arm.
281  */
282 static int
module_info_init(void * arg __unused)283 module_info_init(void *arg __unused)
284 {
285 	struct linker_file thekernel;
286 
287 	STAILQ_INIT(&module_list);
288 
289 	thekernel.filename   = "kernel";
290 	thekernel.address    = CADDR(&_start);
291 	thekernel.size       = UADDR(&_end) - UADDR(&_start);
292 	thekernel.exidx_addr = CADDR(&_exidx_start);
293 	thekernel.exidx_size = UADDR(&_exidx_end) - UADDR(&_exidx_start);
294 	populate_module_info(create_module_info(), &thekernel);
295 
296 	return (0);
297 }
298 SYSINIT(unwind_init, SI_SUB_KMEM, SI_ORDER_ANY, module_info_init, NULL);
299 
300 /* Expand a 31-bit signed value to a 32-bit signed value */
301 static __inline int32_t
expand_prel31(uint32_t prel31)302 expand_prel31(uint32_t prel31)
303 {
304 
305 	return ((int32_t)(prel31 & 0x7fffffffu) << 1) / 2;
306 }
307 
308 /*
309  * Perform a binary search of the index table to find the function
310  * with the largest address that doesn't exceed addr.
311  */
312 static struct unwind_idx *
find_index(uint32_t addr)313 find_index(uint32_t addr)
314 {
315 	struct module_info *info;
316 	unsigned int min, mid, max;
317 	struct unwind_idx *start;
318 	struct unwind_idx *item;
319 	int32_t prel31_addr;
320 	uint32_t func_addr;
321 
322 	info = find_module_info(addr);
323 	if (info == NULL)
324 		return NULL;
325 
326 	min = 0;
327 	max = (info->exidx_end - info->exidx_start) / sizeof(struct unwind_idx);
328 	start = (struct unwind_idx *)CADDR(info->exidx_start);
329 
330 	while (min != max) {
331 		mid = min + (max - min + 1) / 2;
332 
333 		item = &start[mid];
334 
335 		prel31_addr = expand_prel31(item->offset);
336 		func_addr = (uint32_t)&item->offset + prel31_addr;
337 
338 		if (func_addr <= addr) {
339 			min = mid;
340 		} else {
341 			max = mid - 1;
342 		}
343 	}
344 
345 	return &start[min];
346 }
347 
348 /* Reads the next byte from the instruction list */
349 static uint8_t
unwind_exec_read_byte(struct unwind_state * state)350 unwind_exec_read_byte(struct unwind_state *state)
351 {
352 	uint8_t insn;
353 
354 	/* Read the unwind instruction */
355 	insn = (*state->insn) >> (state->byte * 8);
356 
357 	/* Update the location of the next instruction */
358 	if (state->byte == 0) {
359 		state->byte = 3;
360 		state->insn++;
361 		state->entries--;
362 	} else
363 		state->byte--;
364 
365 	return insn;
366 }
367 
368 /* Executes the next instruction on the list */
369 static int
unwind_exec_insn(struct unwind_state * state)370 unwind_exec_insn(struct unwind_state *state)
371 {
372 	struct thread *td = curthread;
373 	unsigned int insn;
374 	uint32_t *vsp = (uint32_t *)state->registers[SP];
375 	int update_vsp = 0;
376 
377 	/* This should never happen */
378 	if (state->entries == 0)
379 		return 1;
380 
381 	/* Read the next instruction */
382 	insn = unwind_exec_read_byte(state);
383 
384 	if ((insn & INSN_VSP_MASK) == INSN_VSP_INC) {
385 		state->registers[SP] += ((insn & INSN_VSP_SIZE_MASK) << 2) + 4;
386 
387 	} else if ((insn & INSN_VSP_MASK) == INSN_VSP_DEC) {
388 		state->registers[SP] -= ((insn & INSN_VSP_SIZE_MASK) << 2) + 4;
389 
390 	} else if ((insn & INSN_STD_MASK) == INSN_POP_MASKED) {
391 		unsigned int mask, reg;
392 
393 		/* Load the mask */
394 		mask = unwind_exec_read_byte(state);
395 		mask |= (insn & INSN_STD_DATA_MASK) << 8;
396 
397 		/* We have a refuse to unwind instruction */
398 		if (mask == 0)
399 			return 1;
400 
401 		if (!__is_aligned(vsp, sizeof(register_t)))
402 			return 1;
403 
404 		/* Update SP */
405 		update_vsp = 1;
406 
407 		/* Load the registers */
408 		for (reg = 4; mask && reg < 16; mask >>= 1, reg++) {
409 			if (mask & 1) {
410 				if (!kstack_contains(td, (uintptr_t)vsp,
411 				    sizeof(*vsp)))
412 					return 1;
413 
414 				state->registers[reg] = *vsp++;
415 				state->update_mask |= 1 << reg;
416 
417 				/* If we have updated SP kep its value */
418 				if (reg == SP)
419 					update_vsp = 0;
420 			}
421 		}
422 
423 	} else if ((insn & INSN_STD_MASK) == INSN_VSP_REG &&
424 	    ((insn & INSN_STD_DATA_MASK) != 13) &&
425 	    ((insn & INSN_STD_DATA_MASK) != 15)) {
426 		/* sp = register */
427 		state->registers[SP] =
428 		    state->registers[insn & INSN_STD_DATA_MASK];
429 
430 	} else if ((insn & INSN_STD_MASK) == INSN_POP_COUNT) {
431 		unsigned int count, reg;
432 
433 		/* Read how many registers to load */
434 		count = insn & INSN_POP_COUNT_MASK;
435 
436 		if (!__is_aligned(vsp, sizeof(register_t)))
437 			return 1;
438 
439 		/* Update sp */
440 		update_vsp = 1;
441 
442 		/* Pop the registers */
443 		if (!kstack_contains(td, (uintptr_t)vsp,
444 		    sizeof(*vsp) * (4 + count)))
445 			return 1;
446 		for (reg = 4; reg <= 4 + count; reg++) {
447 			state->registers[reg] = *vsp++;
448 			state->update_mask |= 1 << reg;
449 		}
450 
451 		/* Check if we are in the pop r14 version */
452 		if ((insn & INSN_POP_TYPE_MASK) != 0) {
453 			if (!kstack_contains(td, (uintptr_t)vsp, sizeof(*vsp)))
454 				return 1;
455 			state->registers[14] = *vsp++;
456 		}
457 
458 	} else if (insn == INSN_FINISH) {
459 		/* Stop processing */
460 		state->entries = 0;
461 
462 	} else if (insn == INSN_POP_REGS) {
463 		unsigned int mask, reg;
464 
465 		mask = unwind_exec_read_byte(state);
466 		if (mask == 0 || (mask & 0xf0) != 0)
467 			return 1;
468 
469 		if (!__is_aligned(vsp, sizeof(register_t)))
470 			return 1;
471 
472 		/* Update SP */
473 		update_vsp = 1;
474 
475 		/* Load the registers */
476 		for (reg = 0; mask && reg < 4; mask >>= 1, reg++) {
477 			if (mask & 1) {
478 				if (!kstack_contains(td, (uintptr_t)vsp,
479 				    sizeof(*vsp)))
480 					return 1;
481 				state->registers[reg] = *vsp++;
482 				state->update_mask |= 1 << reg;
483 			}
484 		}
485 
486 	} else if ((insn & INSN_VSP_LARGE_INC_MASK) == INSN_VSP_LARGE_INC) {
487 		unsigned int uleb128;
488 
489 		/* Read the increment value */
490 		uleb128 = unwind_exec_read_byte(state);
491 
492 		state->registers[SP] += 0x204 + (uleb128 << 2);
493 
494 	} else {
495 		/* We hit a new instruction that needs to be implemented */
496 #if 0
497 		db_printf("Unhandled instruction %.2x\n", insn);
498 #endif
499 		return 1;
500 	}
501 
502 	if (update_vsp) {
503 		state->registers[SP] = (uint32_t)vsp;
504 	}
505 
506 #if 0
507 	db_printf("fp = %08x, sp = %08x, lr = %08x, pc = %08x\n",
508 	    state->registers[FP], state->registers[SP], state->registers[LR],
509 	    state->registers[PC]);
510 #endif
511 
512 	return 0;
513 }
514 
515 /* Performs the unwind of a function */
516 static int
unwind_tab(struct unwind_state * state)517 unwind_tab(struct unwind_state *state)
518 {
519 	uint32_t entry;
520 
521 	/* Set PC to a known value */
522 	state->registers[PC] = 0;
523 
524 	/* Read the personality */
525 	entry = *state->insn & ENTRY_MASK;
526 
527 	if (entry == ENTRY_ARM_SU16) {
528 		state->byte = 2;
529 		state->entries = 1;
530 	} else if (entry == ENTRY_ARM_LU16) {
531 		state->byte = 1;
532 		state->entries = ((*state->insn >> 16) & 0xFF) + 1;
533 	} else {
534 #if 0
535 		db_printf("Unknown entry: %x\n", entry);
536 #endif
537 		return 1;
538 	}
539 
540 	while (state->entries > 0) {
541 		if (unwind_exec_insn(state) != 0)
542 			return 1;
543 	}
544 
545 	/*
546 	 * The program counter was not updated, load it from the link register.
547 	 */
548 	if (state->registers[PC] == 0) {
549 		state->registers[PC] = state->registers[LR];
550 
551 		/*
552 		 * If the program counter changed, flag it in the update mask.
553 		 */
554 		if (state->start_pc != state->registers[PC])
555 			state->update_mask |= 1 << PC;
556 	}
557 
558 	return 0;
559 }
560 
561 /*
562  * Unwind a single stack frame.
563  * Return 0 on success or 1 if the stack cannot be unwound any further.
564  *
565  * XXX The can_lock argument is no longer germane; a sweep of callers should be
566  * made to remove it after this new code has proven itself for a while.
567  */
568 int
unwind_stack_one(struct unwind_state * state,int can_lock __unused)569 unwind_stack_one(struct unwind_state *state, int can_lock __unused)
570 {
571 	struct unwind_idx *index;
572 
573 	/* Reset the mask of updated registers */
574 	state->update_mask = 0;
575 
576 	/* The pc value is correct and will be overwritten, save it */
577 	state->start_pc = state->registers[PC];
578 
579 	/* Find the item to run */
580 	index = find_index(state->start_pc);
581 	if (index == NULL || index->insn == EXIDX_CANTUNWIND)
582 		return 1;
583 
584 	if (index->insn & (1U << 31)) {
585 		/* The data is within the instruction */
586 		state->insn = &index->insn;
587 	} else {
588 		/* A prel31 offset to the unwind table */
589 		state->insn = (uint32_t *)
590 		    ((uintptr_t)&index->insn +
591 		     expand_prel31(index->insn));
592 	}
593 
594 	/* Run the unwind function, return its finished/not-finished status. */
595 	return (unwind_tab(state));
596 }
597