xref: /openbmc/linux/kernel/debug/kdb/kdb_support.c (revision 2d091155)
1 /*
2  * Kernel Debugger Architecture Independent Support Functions
3  *
4  * This file is subject to the terms and conditions of the GNU General Public
5  * License.  See the file "COPYING" in the main directory of this archive
6  * for more details.
7  *
8  * Copyright (c) 1999-2004 Silicon Graphics, Inc.  All Rights Reserved.
9  * Copyright (c) 2009 Wind River Systems, Inc.  All Rights Reserved.
10  * 03/02/13    added new 2.5 kallsyms <xavier.bru@bull.net>
11  */
12 
13 #include <linux/types.h>
14 #include <linux/sched.h>
15 #include <linux/mm.h>
16 #include <linux/kallsyms.h>
17 #include <linux/stddef.h>
18 #include <linux/vmalloc.h>
19 #include <linux/ptrace.h>
20 #include <linux/module.h>
21 #include <linux/highmem.h>
22 #include <linux/hardirq.h>
23 #include <linux/delay.h>
24 #include <linux/uaccess.h>
25 #include <linux/kdb.h>
26 #include <linux/slab.h>
27 #include <linux/ctype.h>
28 #include "kdb_private.h"
29 
30 /*
31  * kdbgetsymval - Return the address of the given symbol.
32  *
33  * Parameters:
34  *	symname	Character string containing symbol name
35  *      symtab  Structure to receive results
36  * Returns:
37  *	0	Symbol not found, symtab zero filled
38  *	1	Symbol mapped to module/symbol/section, data in symtab
39  */
40 int kdbgetsymval(const char *symname, kdb_symtab_t *symtab)
41 {
42 	kdb_dbg_printf(AR, "symname=%s, symtab=%px\n", symname, symtab);
43 	memset(symtab, 0, sizeof(*symtab));
44 	symtab->sym_start = kallsyms_lookup_name(symname);
45 	if (symtab->sym_start) {
46 		kdb_dbg_printf(AR, "returns 1, symtab->sym_start=0x%lx\n",
47 			       symtab->sym_start);
48 		return 1;
49 	}
50 	kdb_dbg_printf(AR, "returns 0\n");
51 	return 0;
52 }
53 EXPORT_SYMBOL(kdbgetsymval);
54 
55 /**
56  * kdbnearsym() - Return the name of the symbol with the nearest address
57  *                less than @addr.
58  * @addr: Address to check for near symbol
59  * @symtab: Structure to receive results
60  *
61  * WARNING: This function may return a pointer to a single statically
62  * allocated buffer (namebuf). kdb's unusual calling context (single
63  * threaded, all other CPUs halted) provides us sufficient locking for
64  * this to be safe. The only constraint imposed by the static buffer is
65  * that the caller must consume any previous reply prior to another call
66  * to lookup a new symbol.
67  *
68  * Note that, strictly speaking, some architectures may re-enter the kdb
69  * trap if the system turns out to be very badly damaged and this breaks
70  * the single-threaded assumption above. In these circumstances successful
71  * continuation and exit from the inner trap is unlikely to work and any
72  * user attempting this receives a prominent warning before being allowed
73  * to progress. In these circumstances we remain memory safe because
74  * namebuf[KSYM_NAME_LEN-1] will never change from '\0' although we do
75  * tolerate the possibility of garbled symbol display from the outer kdb
76  * trap.
77  *
78  * Return:
79  * * 0 - No sections contain this address, symtab zero filled
80  * * 1 - Address mapped to module/symbol/section, data in symtab
81  */
82 int kdbnearsym(unsigned long addr, kdb_symtab_t *symtab)
83 {
84 	int ret = 0;
85 	unsigned long symbolsize = 0;
86 	unsigned long offset = 0;
87 	static char namebuf[KSYM_NAME_LEN];
88 
89 	kdb_dbg_printf(AR, "addr=0x%lx, symtab=%px\n", addr, symtab);
90 	memset(symtab, 0, sizeof(*symtab));
91 
92 	if (addr < 4096)
93 		goto out;
94 
95 	symtab->sym_name = kallsyms_lookup(addr, &symbolsize , &offset,
96 				(char **)(&symtab->mod_name), namebuf);
97 	if (offset > 8*1024*1024) {
98 		symtab->sym_name = NULL;
99 		addr = offset = symbolsize = 0;
100 	}
101 	symtab->sym_start = addr - offset;
102 	symtab->sym_end = symtab->sym_start + symbolsize;
103 	ret = symtab->sym_name != NULL && *(symtab->sym_name) != '\0';
104 
105 	if (symtab->mod_name == NULL)
106 		symtab->mod_name = "kernel";
107 	kdb_dbg_printf(AR, "returns %d symtab->sym_start=0x%lx, symtab->mod_name=%px, symtab->sym_name=%px (%s)\n",
108 		       ret, symtab->sym_start, symtab->mod_name, symtab->sym_name, symtab->sym_name);
109 out:
110 	return ret;
111 }
112 
113 static char ks_namebuf[KSYM_NAME_LEN+1], ks_namebuf_prev[KSYM_NAME_LEN+1];
114 
115 /*
116  * kallsyms_symbol_complete
117  *
118  * Parameters:
119  *	prefix_name	prefix of a symbol name to lookup
120  *	max_len		maximum length that can be returned
121  * Returns:
122  *	Number of symbols which match the given prefix.
123  * Notes:
124  *	prefix_name is changed to contain the longest unique prefix that
125  *	starts with this prefix (tab completion).
126  */
127 int kallsyms_symbol_complete(char *prefix_name, int max_len)
128 {
129 	loff_t pos = 0;
130 	int prefix_len = strlen(prefix_name), prev_len = 0;
131 	int i, number = 0;
132 	const char *name;
133 
134 	while ((name = kdb_walk_kallsyms(&pos))) {
135 		if (strncmp(name, prefix_name, prefix_len) == 0) {
136 			strscpy(ks_namebuf, name, sizeof(ks_namebuf));
137 			/* Work out the longest name that matches the prefix */
138 			if (++number == 1) {
139 				prev_len = min_t(int, max_len-1,
140 						 strlen(ks_namebuf));
141 				memcpy(ks_namebuf_prev, ks_namebuf, prev_len);
142 				ks_namebuf_prev[prev_len] = '\0';
143 				continue;
144 			}
145 			for (i = 0; i < prev_len; i++) {
146 				if (ks_namebuf[i] != ks_namebuf_prev[i]) {
147 					prev_len = i;
148 					ks_namebuf_prev[i] = '\0';
149 					break;
150 				}
151 			}
152 		}
153 	}
154 	if (prev_len > prefix_len)
155 		memcpy(prefix_name, ks_namebuf_prev, prev_len+1);
156 	return number;
157 }
158 
159 /*
160  * kallsyms_symbol_next
161  *
162  * Parameters:
163  *	prefix_name	prefix of a symbol name to lookup
164  *	flag	0 means search from the head, 1 means continue search.
165  *	buf_size	maximum length that can be written to prefix_name
166  *			buffer
167  * Returns:
168  *	1 if a symbol matches the given prefix.
169  *	0 if no string found
170  */
171 int kallsyms_symbol_next(char *prefix_name, int flag, int buf_size)
172 {
173 	int prefix_len = strlen(prefix_name);
174 	static loff_t pos;
175 	const char *name;
176 
177 	if (!flag)
178 		pos = 0;
179 
180 	while ((name = kdb_walk_kallsyms(&pos))) {
181 		if (!strncmp(name, prefix_name, prefix_len))
182 			return strscpy(prefix_name, name, buf_size);
183 	}
184 	return 0;
185 }
186 
187 /*
188  * kdb_symbol_print - Standard method for printing a symbol name and offset.
189  * Inputs:
190  *	addr	Address to be printed.
191  *	symtab	Address of symbol data, if NULL this routine does its
192  *		own lookup.
193  *	punc	Punctuation for string, bit field.
194  * Remarks:
195  *	The string and its punctuation is only printed if the address
196  *	is inside the kernel, except that the value is always printed
197  *	when requested.
198  */
199 void kdb_symbol_print(unsigned long addr, const kdb_symtab_t *symtab_p,
200 		      unsigned int punc)
201 {
202 	kdb_symtab_t symtab, *symtab_p2;
203 	if (symtab_p) {
204 		symtab_p2 = (kdb_symtab_t *)symtab_p;
205 	} else {
206 		symtab_p2 = &symtab;
207 		kdbnearsym(addr, symtab_p2);
208 	}
209 	if (!(symtab_p2->sym_name || (punc & KDB_SP_VALUE)))
210 		return;
211 	if (punc & KDB_SP_SPACEB)
212 		kdb_printf(" ");
213 	if (punc & KDB_SP_VALUE)
214 		kdb_printf(kdb_machreg_fmt0, addr);
215 	if (symtab_p2->sym_name) {
216 		if (punc & KDB_SP_VALUE)
217 			kdb_printf(" ");
218 		if (punc & KDB_SP_PAREN)
219 			kdb_printf("(");
220 		if (strcmp(symtab_p2->mod_name, "kernel"))
221 			kdb_printf("[%s]", symtab_p2->mod_name);
222 		kdb_printf("%s", symtab_p2->sym_name);
223 		if (addr != symtab_p2->sym_start)
224 			kdb_printf("+0x%lx", addr - symtab_p2->sym_start);
225 		if (punc & KDB_SP_SYMSIZE)
226 			kdb_printf("/0x%lx",
227 				   symtab_p2->sym_end - symtab_p2->sym_start);
228 		if (punc & KDB_SP_PAREN)
229 			kdb_printf(")");
230 	}
231 	if (punc & KDB_SP_SPACEA)
232 		kdb_printf(" ");
233 	if (punc & KDB_SP_NEWLINE)
234 		kdb_printf("\n");
235 }
236 
237 /*
238  * kdb_strdup - kdb equivalent of strdup, for disasm code.
239  * Inputs:
240  *	str	The string to duplicate.
241  *	type	Flags to kmalloc for the new string.
242  * Returns:
243  *	Address of the new string, NULL if storage could not be allocated.
244  * Remarks:
245  *	This is not in lib/string.c because it uses kmalloc which is not
246  *	available when string.o is used in boot loaders.
247  */
248 char *kdb_strdup(const char *str, gfp_t type)
249 {
250 	int n = strlen(str)+1;
251 	char *s = kmalloc(n, type);
252 	if (!s)
253 		return NULL;
254 	return strcpy(s, str);
255 }
256 
257 /*
258  * kdb_getarea_size - Read an area of data.  The kdb equivalent of
259  *	copy_from_user, with kdb messages for invalid addresses.
260  * Inputs:
261  *	res	Pointer to the area to receive the result.
262  *	addr	Address of the area to copy.
263  *	size	Size of the area.
264  * Returns:
265  *	0 for success, < 0 for error.
266  */
267 int kdb_getarea_size(void *res, unsigned long addr, size_t size)
268 {
269 	int ret = copy_from_kernel_nofault((char *)res, (char *)addr, size);
270 	if (ret) {
271 		if (!KDB_STATE(SUPPRESS)) {
272 			kdb_func_printf("Bad address 0x%lx\n", addr);
273 			KDB_STATE_SET(SUPPRESS);
274 		}
275 		ret = KDB_BADADDR;
276 	} else {
277 		KDB_STATE_CLEAR(SUPPRESS);
278 	}
279 	return ret;
280 }
281 
282 /*
283  * kdb_putarea_size - Write an area of data.  The kdb equivalent of
284  *	copy_to_user, with kdb messages for invalid addresses.
285  * Inputs:
286  *	addr	Address of the area to write to.
287  *	res	Pointer to the area holding the data.
288  *	size	Size of the area.
289  * Returns:
290  *	0 for success, < 0 for error.
291  */
292 int kdb_putarea_size(unsigned long addr, void *res, size_t size)
293 {
294 	int ret = copy_to_kernel_nofault((char *)addr, (char *)res, size);
295 	if (ret) {
296 		if (!KDB_STATE(SUPPRESS)) {
297 			kdb_func_printf("Bad address 0x%lx\n", addr);
298 			KDB_STATE_SET(SUPPRESS);
299 		}
300 		ret = KDB_BADADDR;
301 	} else {
302 		KDB_STATE_CLEAR(SUPPRESS);
303 	}
304 	return ret;
305 }
306 
307 /*
308  * kdb_getphys - Read data from a physical address. Validate the
309  * 	address is in range, use kmap_atomic() to get data
310  * 	similar to kdb_getarea() - but for phys addresses
311  * Inputs:
312  * 	res	Pointer to the word to receive the result
313  * 	addr	Physical address of the area to copy
314  * 	size	Size of the area
315  * Returns:
316  *	0 for success, < 0 for error.
317  */
318 static int kdb_getphys(void *res, unsigned long addr, size_t size)
319 {
320 	unsigned long pfn;
321 	void *vaddr;
322 	struct page *page;
323 
324 	pfn = (addr >> PAGE_SHIFT);
325 	if (!pfn_valid(pfn))
326 		return 1;
327 	page = pfn_to_page(pfn);
328 	vaddr = kmap_atomic(page);
329 	memcpy(res, vaddr + (addr & (PAGE_SIZE - 1)), size);
330 	kunmap_atomic(vaddr);
331 
332 	return 0;
333 }
334 
335 /*
336  * kdb_getphysword
337  * Inputs:
338  *	word	Pointer to the word to receive the result.
339  *	addr	Address of the area to copy.
340  *	size	Size of the area.
341  * Returns:
342  *	0 for success, < 0 for error.
343  */
344 int kdb_getphysword(unsigned long *word, unsigned long addr, size_t size)
345 {
346 	int diag;
347 	__u8  w1;
348 	__u16 w2;
349 	__u32 w4;
350 	__u64 w8;
351 	*word = 0;	/* Default value if addr or size is invalid */
352 
353 	switch (size) {
354 	case 1:
355 		diag = kdb_getphys(&w1, addr, sizeof(w1));
356 		if (!diag)
357 			*word = w1;
358 		break;
359 	case 2:
360 		diag = kdb_getphys(&w2, addr, sizeof(w2));
361 		if (!diag)
362 			*word = w2;
363 		break;
364 	case 4:
365 		diag = kdb_getphys(&w4, addr, sizeof(w4));
366 		if (!diag)
367 			*word = w4;
368 		break;
369 	case 8:
370 		if (size <= sizeof(*word)) {
371 			diag = kdb_getphys(&w8, addr, sizeof(w8));
372 			if (!diag)
373 				*word = w8;
374 			break;
375 		}
376 		fallthrough;
377 	default:
378 		diag = KDB_BADWIDTH;
379 		kdb_func_printf("bad width %zu\n", size);
380 	}
381 	return diag;
382 }
383 
384 /*
385  * kdb_getword - Read a binary value.  Unlike kdb_getarea, this treats
386  *	data as numbers.
387  * Inputs:
388  *	word	Pointer to the word to receive the result.
389  *	addr	Address of the area to copy.
390  *	size	Size of the area.
391  * Returns:
392  *	0 for success, < 0 for error.
393  */
394 int kdb_getword(unsigned long *word, unsigned long addr, size_t size)
395 {
396 	int diag;
397 	__u8  w1;
398 	__u16 w2;
399 	__u32 w4;
400 	__u64 w8;
401 	*word = 0;	/* Default value if addr or size is invalid */
402 	switch (size) {
403 	case 1:
404 		diag = kdb_getarea(w1, addr);
405 		if (!diag)
406 			*word = w1;
407 		break;
408 	case 2:
409 		diag = kdb_getarea(w2, addr);
410 		if (!diag)
411 			*word = w2;
412 		break;
413 	case 4:
414 		diag = kdb_getarea(w4, addr);
415 		if (!diag)
416 			*word = w4;
417 		break;
418 	case 8:
419 		if (size <= sizeof(*word)) {
420 			diag = kdb_getarea(w8, addr);
421 			if (!diag)
422 				*word = w8;
423 			break;
424 		}
425 		fallthrough;
426 	default:
427 		diag = KDB_BADWIDTH;
428 		kdb_func_printf("bad width %zu\n", size);
429 	}
430 	return diag;
431 }
432 
433 /*
434  * kdb_putword - Write a binary value.  Unlike kdb_putarea, this
435  *	treats data as numbers.
436  * Inputs:
437  *	addr	Address of the area to write to..
438  *	word	The value to set.
439  *	size	Size of the area.
440  * Returns:
441  *	0 for success, < 0 for error.
442  */
443 int kdb_putword(unsigned long addr, unsigned long word, size_t size)
444 {
445 	int diag;
446 	__u8  w1;
447 	__u16 w2;
448 	__u32 w4;
449 	__u64 w8;
450 	switch (size) {
451 	case 1:
452 		w1 = word;
453 		diag = kdb_putarea(addr, w1);
454 		break;
455 	case 2:
456 		w2 = word;
457 		diag = kdb_putarea(addr, w2);
458 		break;
459 	case 4:
460 		w4 = word;
461 		diag = kdb_putarea(addr, w4);
462 		break;
463 	case 8:
464 		if (size <= sizeof(word)) {
465 			w8 = word;
466 			diag = kdb_putarea(addr, w8);
467 			break;
468 		}
469 		fallthrough;
470 	default:
471 		diag = KDB_BADWIDTH;
472 		kdb_func_printf("bad width %zu\n", size);
473 	}
474 	return diag;
475 }
476 
477 
478 
479 /*
480  * kdb_task_state_char - Return the character that represents the task state.
481  * Inputs:
482  *	p	struct task for the process
483  * Returns:
484  *	One character to represent the task state.
485  */
486 char kdb_task_state_char (const struct task_struct *p)
487 {
488 	unsigned long tmp;
489 	char state;
490 	int cpu;
491 
492 	if (!p ||
493 	    copy_from_kernel_nofault(&tmp, (char *)p, sizeof(unsigned long)))
494 		return 'E';
495 
496 	state = task_state_to_char((struct task_struct *) p);
497 
498 	if (is_idle_task(p)) {
499 		/* Idle task.  Is it really idle, apart from the kdb
500 		 * interrupt? */
501 		cpu = kdb_process_cpu(p);
502 		if (!kdb_task_has_cpu(p) || kgdb_info[cpu].irq_depth == 1) {
503 			if (cpu != kdb_initial_cpu)
504 				state = '-';	/* idle task */
505 		}
506 	} else if (!p->mm && strchr("IMS", state)) {
507 		state = tolower(state);		/* sleeping system daemon */
508 	}
509 	return state;
510 }
511 
512 /*
513  * kdb_task_state - Return true if a process has the desired state
514  *	given by the mask.
515  * Inputs:
516  *	p	struct task for the process
517  *	mask	set of characters used to select processes; both NULL
518  *	        and the empty string mean adopt a default filter, which
519  *	        is to suppress sleeping system daemons and the idle tasks
520  * Returns:
521  *	True if the process matches at least one criteria defined by the mask.
522  */
523 bool kdb_task_state(const struct task_struct *p, const char *mask)
524 {
525 	char state = kdb_task_state_char(p);
526 
527 	/* If there is no mask, then we will filter code that runs when the
528 	 * scheduler is idling and any system daemons that are currently
529 	 * sleeping.
530 	 */
531 	if (!mask || mask[0] == '\0')
532 		return !strchr("-ims", state);
533 
534 	/* A is a special case that matches all states */
535 	if (strchr(mask, 'A'))
536 		return true;
537 
538 	return strchr(mask, state);
539 }
540 
541 /* Maintain a small stack of kdb_flags to allow recursion without disturbing
542  * the global kdb state.
543  */
544 
545 static int kdb_flags_stack[4], kdb_flags_index;
546 
547 void kdb_save_flags(void)
548 {
549 	BUG_ON(kdb_flags_index >= ARRAY_SIZE(kdb_flags_stack));
550 	kdb_flags_stack[kdb_flags_index++] = kdb_flags;
551 }
552 
553 void kdb_restore_flags(void)
554 {
555 	BUG_ON(kdb_flags_index <= 0);
556 	kdb_flags = kdb_flags_stack[--kdb_flags_index];
557 }
558