xref: /netbsd-src/sys/kern/kern_ksyms.c (revision cac8e449158efc7261bebc8657cbb0125a2cfdde)
1 /*
2  * Copyright (c) 2001, 2003 Anders Magnusson (ragge@ludd.luth.se).
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 /*
29  * Code to deal with in-kernel symbol table management + /dev/ksyms.
30  *
31  * For each loaded module the symbol table info is kept track of by a
32  * struct, placed in a circular list. The first entry is the kernel
33  * symbol table.
34  */
35 
36 /*
37  * TODO:
38  *	Change the ugly way of adding new symbols (comes with linker)
39  *	Add kernel locking stuff.
40  *	(Ev) add support for poll.
41  *	(Ev) fix support for mmap.
42  *
43  *	Export ksyms internal logic for use in post-mortem debuggers?
44  *	  Need to move struct symtab to ksyms.h for that.
45  */
46 
47 #include <sys/cdefs.h>
48 __KERNEL_RCSID(0, "$NetBSD: kern_ksyms.c,v 1.36 2008/07/22 21:18:35 christos Exp $");
49 
50 #ifdef _KERNEL
51 #include "opt_ddb.h"
52 #include "opt_ddbparam.h"	/* for SYMTAB_SPACE */
53 #endif
54 
55 #include <sys/param.h>
56 #include <sys/errno.h>
57 #include <sys/queue.h>
58 #include <sys/exec.h>
59 #include <sys/systm.h>
60 #include <sys/conf.h>
61 #include <sys/device.h>
62 #include <sys/malloc.h>
63 #include <sys/proc.h>
64 
65 #include <machine/elf_machdep.h> /* XXX */
66 #define ELFSIZE ARCH_ELFSIZE
67 
68 #include <sys/exec_elf.h>
69 #include <sys/ksyms.h>
70 
71 #include <lib/libkern/libkern.h>
72 
73 #ifdef DDB
74 #include <ddb/db_output.h>
75 #endif
76 
77 #include "ksyms.h"
78 
79 static int ksymsinited = 0;
80 
81 #if NKSYMS
82 static void ksyms_hdr_init(void *hdraddr);
83 static void ksyms_sizes_calc(void);
84 static int ksyms_isopen;
85 static int ksyms_maxlen;
86 #endif
87 
88 #ifdef KSYMS_DEBUG
89 #define	FOLLOW_CALLS		1
90 #define	FOLLOW_MORE_CALLS	2
91 #define	FOLLOW_DEVKSYMS		4
92 static int ksyms_debug;
93 #endif
94 
95 #ifdef SYMTAB_SPACE
96 #define		SYMTAB_FILLER	"|This is the symbol table!"
97 
98 char		db_symtab[SYMTAB_SPACE] = SYMTAB_FILLER;
99 int		db_symtabsize = SYMTAB_SPACE;
100 #endif
101 
102 /*
103  * Store the different symbol tables in a double-linked list.
104  */
105 struct symtab {
106 	CIRCLEQ_ENTRY(symtab) sd_queue;
107 	const char *sd_name;	/* Name of this table */
108 	Elf_Sym *sd_symstart;	/* Address of symbol table */
109 	Elf_Sym *sd_minsym;	/* symbol with minimum value */
110 	Elf_Sym *sd_maxsym;	/* symbol with maximum value */
111 	char *sd_strstart;	/* Address of corresponding string table */
112 	int *sd_symnmoff;	/* Used when calculating the name offset */
113 	int sd_usroffset;	/* Real address for userspace */
114 	int sd_symsize;		/* Size in bytes of symbol table */
115 	int sd_strsize;		/* Size of string table */
116 };
117 
118 static CIRCLEQ_HEAD(, symtab) symtab_queue =
119     CIRCLEQ_HEAD_INITIALIZER(symtab_queue);
120 
121 static struct symtab kernel_symtab;
122 
123 #define	USE_PTREE
124 #ifdef USE_PTREE
125 /*
126  * Patricia-tree-based lookup structure for the in-kernel global symbols.
127  * Based on a design by Mikael Sundstrom, msm@sm.luth.se.
128  */
129 struct ptree {
130 	int16_t bitno;
131 	int16_t lr[2];
132 } *symb;
133 static int16_t baseidx;
134 static int treex = 1;
135 
136 #define	P_BIT(key, bit) ((key[bit >> 3] >> (bit & 7)) & 1)
137 #define	STRING(idx) (kernel_symtab.sd_symstart[idx].st_name + \
138 			kernel_symtab.sd_strstart)
139 
140 static int
141 ksyms_verify(void *symstart, void *strstart)
142 {
143 #if defined(DIAGNOSTIC) || defined(DEBUG)
144 	if (symstart == NULL)
145 		printf("ksyms: Symbol table not found\n");
146 	if (strstart == NULL)
147 		printf("ksyms: String table not found\n");
148 	if (symstart == NULL || strstart == NULL)
149 		printf("ksyms: Perhaps the kernel is stripped?\n");
150 #endif
151 	if (symstart == NULL || strstart == NULL)
152 		return 0;
153 	KASSERT(symstart <= strstart);
154 	return 1;
155 }
156 
157 /*
158  * Walk down the tree until a terminal node is found.
159  */
160 static int
161 symbol_traverse(const char *key)
162 {
163 	int16_t nb, rbit = baseidx;
164 
165 	while (rbit > 0) {
166 		nb = symb[rbit].bitno;
167 		rbit = symb[rbit].lr[P_BIT(key, nb)];
168 	}
169 	return -rbit;
170 }
171 
172 static int
173 ptree_add(char *key, int val)
174 {
175 	int idx;
176 	int nix, cix, bit, rbit, sb, lastrbit, svbit = 0, ix;
177 	char *m, *k;
178 
179 	if (baseidx == 0) {
180 		baseidx = -val;
181 		return 0; /* First element */
182 	}
183 
184 	/* Get string to match against */
185 	idx = symbol_traverse(key);
186 
187 	/* Find first mismatching bit */
188 	m = STRING(idx);
189 	k = key;
190 	if (strcmp(m, k) == 0)
191 		return 1;
192 
193 	for (cix = 0; *m && *k && *m == *k; m++, k++, cix += 8)
194 		;
195 	ix = ffs((int)*m ^ (int)*k) - 1;
196 	cix += ix;
197 
198 	/* Create new node */
199 	nix = treex++;
200 	bit = P_BIT(key, cix);
201 	symb[nix].bitno = cix;
202 	symb[nix].lr[bit] = -val;
203 
204 	/* Find where to insert node */
205 	rbit = baseidx;
206 	lastrbit = 0;
207 	for (;;) {
208 		if (rbit < 0)
209 			break;
210 		sb = symb[rbit].bitno;
211 		if (sb > cix)
212 			break;
213 		if (sb == cix)
214 			printf("symb[rbit].bitno == cix!!!\n");
215 		lastrbit = rbit;
216 		svbit = P_BIT(key, sb);
217 		rbit = symb[rbit].lr[svbit];
218 	}
219 
220 	/* Do the actual insertion */
221 	if (lastrbit == 0) {
222 		/* first element */
223 		symb[nix].lr[!bit] = baseidx;
224 		baseidx = nix;
225 	} else {
226 		symb[nix].lr[!bit] = rbit;
227 		symb[lastrbit].lr[svbit] = nix;
228 	}
229 	return 0;
230 }
231 
232 static int
233 ptree_find(const char *key)
234 {
235 	int idx;
236 
237 	if (baseidx == 0)
238 		return 0;
239 	idx = symbol_traverse(key);
240 
241 	if (strcmp(key, STRING(idx)) == 0)
242 		return idx;
243 	return 0;
244 }
245 
246 static void
247 ptree_gen(char *off, struct symtab *tab)
248 {
249 	Elf_Sym *sym;
250 	int i, nsym;
251 
252 	if (off != NULL)
253 		symb = (struct ptree *)ALIGN(off);
254 	else
255 		symb = malloc((tab->sd_symsize/sizeof(Elf_Sym)) *
256 		    sizeof(struct ptree), M_DEVBUF, M_WAITOK);
257 	symb--; /* sym index won't be 0 */
258 
259 	sym = tab->sd_symstart;
260 	if ((nsym = tab->sd_symsize/sizeof(Elf_Sym)) > INT16_MAX) {
261 		printf("Too many symbols for tree, skipping %d symbols\n",
262 		    nsym-INT16_MAX);
263 		nsym = INT16_MAX;
264 	}
265 	for (i = 1; i < nsym; i++) {
266 		if (ELF_ST_BIND(sym[i].st_info) != STB_GLOBAL)
267 			continue;
268 		ptree_add(tab->sd_strstart+sym[i].st_name, i);
269 		if (tab->sd_minsym == NULL
270 		    || sym[i].st_value < tab->sd_minsym->st_value)
271 			tab->sd_minsym = &sym[i];
272 		if (tab->sd_maxsym == NULL
273 		    || sym[i].st_value > tab->sd_maxsym->st_value)
274 			tab->sd_maxsym = &sym[i];
275 	}
276 }
277 #endif /* USE_PTREE */
278 
279 /*
280  * Finds a certain symbol name in a certain symbol table.
281  */
282 static Elf_Sym *
283 findsym(const char *name, struct symtab *table)
284 {
285 	Elf_Sym *start = table->sd_symstart;
286 	int i, sz = table->sd_symsize/sizeof(Elf_Sym);
287 	char *np;
288 	char *realstart = table->sd_strstart - table->sd_usroffset;
289 
290 #ifdef USE_PTREE
291 	if (table == &kernel_symtab && (i = ptree_find(name)) != 0)
292 		return &start[i];
293 #endif
294 
295 	for (i = 0; i < sz; i++) {
296 		np = realstart + start[i].st_name;
297 		if (name[0] == np[0] && name[1] == np[1] &&
298 		    strcmp(name, np) == 0)
299 			return &start[i];
300 	}
301 	return NULL;
302 }
303 
304 /*
305  * The "attach" is in reality done in ksyms_init().
306  */
307 void ksymsattach(int);
308 void
309 ksymsattach(int arg)
310 {
311 
312 #ifdef USE_PTREE
313 	if (baseidx == 0)
314 		ptree_gen(0, &kernel_symtab);
315 #endif
316 
317 }
318 
319 /*
320  * Add a symbol table.
321  * This is intended for use when the symbol table and its corresponding
322  * string table are easily available.  If they are embedded in an ELF
323  * image, use addsymtab_elf() instead.
324  *
325  * name - Symbol's table name.
326  * symstart, symsize - Address and size of the symbol table.
327  * strstart, strsize - Address and size of the string table.
328  * tab - Symbol table to be updated with this information.
329  * newstart - Address to which the symbol table has to be copied during
330  *            shrinking.  If NULL, it is not moved.
331  */
332 static void
333 addsymtab(const char *name,
334     void *symstart, size_t symsize,
335     void *strstart, size_t strsize,
336     struct symtab *tab,
337     void *newstart)
338 {
339 	void *send;
340 	Elf_Sym *sym, *nsym;
341 	int i, n, g;
342 	char *str;
343 
344 	if (newstart == NULL)
345 		newstart = symstart;
346 	KASSERT(newstart <= symstart && symstart <= strstart);
347 
348 	tab->sd_symstart = (Elf_Sym *)symstart;
349 	tab->sd_symsize = symsize;
350 	tab->sd_strstart = strstart;
351 	tab->sd_strsize = strsize;
352 	tab->sd_name = name;
353 	send = tab->sd_strstart + tab->sd_strsize;
354 
355 #ifdef KSYMS_DEBUG
356 	printf("newstart %p sym %p symsz %d str %p strsz %d send %p\n",
357 	    newstart, symstart, symsize, strstart, strsize, send);
358 #endif
359 
360 	/*
361 	 * Pack symbol table by removing all file name references
362 	 * and overwrite the elf header.
363 	 */
364 	sym = tab->sd_symstart;
365 	nsym = (Elf_Sym *)newstart;
366 	str = tab->sd_strstart;
367 	for (g = i = n = 0; i < tab->sd_symsize/sizeof(Elf_Sym); i++) {
368 		if (i == 0) {
369 			nsym[n++] = sym[i];
370 			continue;
371 		}
372 		/*
373 		 * Remove useless symbols.
374 		 * Should actually remove all typeless symbols.
375 		 */
376 		if (sym[i].st_name == 0)
377 			continue; /* Skip nameless entries */
378 		if (sym[i].st_shndx == SHN_UNDEF)
379 			continue; /* Skip external references */
380 		if (ELF_ST_TYPE(sym[i].st_info) == STT_FILE)
381 			continue; /* Skip filenames */
382 		if (ELF_ST_TYPE(sym[i].st_info) == STT_NOTYPE &&
383 		    sym[i].st_value == 0 &&
384 		    strcmp(str + sym[i].st_name, "*ABS*") == 0)
385 			continue; /* XXX */
386 		if (ELF_ST_TYPE(sym[i].st_info) == STT_NOTYPE &&
387 		    strcmp(str + sym[i].st_name, "gcc2_compiled.") == 0)
388 			continue; /* XXX */
389 
390 #ifndef DDB
391 		/* Only need global symbols */
392 		if (ELF_ST_BIND(sym[i].st_info) != STB_GLOBAL)
393 			continue;
394 #endif
395 
396 		/* Save symbol. Set it as an absolute offset */
397 		nsym[n] = sym[i];
398 		nsym[n].st_shndx = SHN_ABS;
399 		if (ELF_ST_BIND(nsym[n].st_info) == STB_GLOBAL)
400 			g++;
401 #if NKSYMS
402 		{
403 			int j;
404 			j = strlen(nsym[n].st_name + tab->sd_strstart) + 1;
405 			if (j > ksyms_maxlen)
406 				ksyms_maxlen = j;
407 		}
408 #endif
409 		n++;
410 
411 	}
412 	tab->sd_symstart = nsym;
413 	tab->sd_symsize = n * sizeof(Elf_Sym);
414 
415 #ifdef notyet
416 	/*
417 	 * Remove left-over strings.
418 	 */
419 	sym = tab->sd_symstart;
420 	str = (void *)tab->sd_symstart + tab->sd_symsize;
421 	str[0] = 0;
422 	n = 1;
423 	for (i = 1; i < tab->sd_symsize/sizeof(Elf_Sym); i++) {
424 		strcpy(str + n, tab->sd_strstart + sym[i].st_name);
425 		sym[i].st_name = n;
426 		n += strlen(str+n) + 1;
427 	}
428 	tab->sd_strstart = str;
429 	tab->sd_strsize = n;
430 
431 #ifdef KSYMS_DEBUG
432 	printf("str %p strsz %d send %p\n", str, n, send);
433 #endif
434 #endif
435 
436 	CIRCLEQ_INSERT_HEAD(&symtab_queue, tab, sd_queue);
437 
438 #ifdef notyet
439 #ifdef USE_PTREE
440 	/* Try to use the freed space, if possible */
441 	if (send - str - n > g * sizeof(struct ptree))
442 		ptree_gen(str + n, tab);
443 #endif
444 #endif
445 }
446 
447 /*
448  * Add a symbol table named name.
449  * This is intended for use when the kernel loader enters the table.
450  */
451 static void
452 addsymtab_elf(const char *name, Elf_Ehdr *ehdr, struct symtab *tab)
453 {
454 	int i, j;
455 	char *start = (char *)ehdr;
456 	Elf_Shdr *shdr;
457 	char *symstart = NULL, *strstart = NULL;
458 	size_t symsize = 0, strsize = 0;
459 
460 	/* Find the symbol table and the corresponding string table. */
461 	shdr = (Elf_Shdr *)(start + ehdr->e_shoff);
462 	for (i = 1; i < ehdr->e_shnum; i++) {
463 		if (shdr[i].sh_type != SHT_SYMTAB)
464 			continue;
465 		if (shdr[i].sh_offset == 0)
466 			continue;
467 		symstart = start + shdr[i].sh_offset;
468 		symsize = shdr[i].sh_size;
469 		j = shdr[i].sh_link;
470 		if (shdr[j].sh_offset == 0)
471 			continue; /* Can this happen? */
472 		strstart = start + shdr[j].sh_offset;
473 		strsize = shdr[j].sh_size;
474 		break;
475 	}
476 
477 	if (!ksyms_verify(symstart, strstart))
478 		return;
479 
480 	addsymtab(name, symstart, symsize, strstart, strsize, tab, start);
481 }
482 
483 /*
484  * Setup the kernel symbol table stuff.
485  */
486 void
487 ksyms_init(int symsize, void *start, void *end)
488 {
489 	Elf_Ehdr *ehdr;
490 
491 #ifdef SYMTAB_SPACE
492 	if (symsize <= 0 &&
493 	    strncmp(db_symtab, SYMTAB_FILLER, sizeof(SYMTAB_FILLER))) {
494 		symsize = db_symtabsize;
495 		start = db_symtab;
496 		end = db_symtab + db_symtabsize;
497 	}
498 #endif
499 	if (symsize <= 0) {
500 		printf("[ Kernel symbol table missing! ]\n");
501 		return;
502 	}
503 
504 	/* Sanity check */
505 	if (ALIGNED_POINTER(start, long) == 0) {
506 		printf("[ Kernel symbol table has bad start address %p ]\n",
507 		    start);
508 		return;
509 	}
510 
511 	ehdr = (Elf_Ehdr *)start;
512 
513 	/* check if this is a valid ELF header */
514 	/* No reason to verify arch type, the kernel is actually running! */
515 	if (memcmp(ehdr->e_ident, ELFMAG, SELFMAG) ||
516 	    ehdr->e_ident[EI_CLASS] != ELFCLASS ||
517 	    ehdr->e_version > 1) {
518 #ifdef notyet /* DDB */
519 		if (ddb_init(symsize, start, end))
520 			return; /* old-style symbol table */
521 #endif
522 		printf("[ Kernel symbol table invalid! ]\n");
523 		return; /* nothing to do */
524 	}
525 
526 #if NKSYMS
527 	/* Loaded header will be scratched in addsymtab */
528 	ksyms_hdr_init(start);
529 #endif
530 
531 	addsymtab_elf("netbsd", ehdr, &kernel_symtab);
532 
533 #if NKSYMS
534 	ksyms_sizes_calc();
535 #endif
536 
537 	ksymsinited = 1;
538 
539 #ifdef DEBUG
540 	printf("Loaded initial symtab at %p, strtab at %p, # entries %ld\n",
541 	    kernel_symtab.sd_symstart, kernel_symtab.sd_strstart,
542 	    (long)kernel_symtab.sd_symsize/sizeof(Elf_Sym));
543 #endif
544 }
545 
546 /*
547  * Setup the kernel symbol table stuff.
548  * Use this when the address of the symbol and string tables are known;
549  * otherwise use ksyms_init with an ELF image.
550  * We need to pass a minimal ELF header which will later be completed by
551  * ksyms_hdr_init and handed off to userland through /dev/ksyms.  We use
552  * a void *rather than a pointer to avoid exposing the Elf_Ehdr type.
553  */
554 void
555 ksyms_init_explicit(void *ehdr, void *symstart, size_t symsize,
556     void *strstart, size_t strsize)
557 {
558 
559 	if (!ksyms_verify(symstart, strstart))
560 		return;
561 
562 #if NKSYMS
563 	ksyms_hdr_init(ehdr);
564 #endif
565 
566 	addsymtab("netbsd", symstart, symsize, strstart, strsize,
567 	    &kernel_symtab, NULL);
568 
569 #if NKSYMS
570 	ksyms_sizes_calc();
571 #endif
572 
573 	ksymsinited = 1;
574 }
575 
576 /*
577  * Get the value associated with a symbol.
578  * "mod" is the module name, or null if any module.
579  * "sym" is the symbol name.
580  * "val" is a pointer to the corresponding value, if call succeeded.
581  * Returns 0 if success or ENOENT if no such entry.
582  */
583 int
584 ksyms_getval(const char *mod, const char *sym, unsigned long *val, int type)
585 {
586 	struct symtab *st;
587 	Elf_Sym *es;
588 
589 	if (ksymsinited == 0)
590 		return ENOENT;
591 
592 #ifdef KSYMS_DEBUG
593 	if (ksyms_debug & FOLLOW_CALLS)
594 		printf("ksyms_getval: mod %s sym %s valp %p\n", mod, sym, val);
595 #endif
596 
597 	CIRCLEQ_FOREACH(st, &symtab_queue, sd_queue) {
598 		if (mod && strcmp(st->sd_name, mod))
599 			continue;
600 		if ((es = findsym(sym, st)) == NULL)
601 			continue;
602 		if (es->st_shndx == SHN_UNDEF)
603 			continue;
604 
605 		/* Skip if bad binding */
606 		if (type == KSYMS_EXTERN &&
607 		    ELF_ST_BIND(es->st_info) != STB_GLOBAL)
608 			continue;
609 
610 		if (val)
611 			*val = es->st_value;
612 		return 0;
613 	}
614 	return ENOENT;
615 }
616 
617 /*
618  * Get "mod" and "symbol" associated with an address.
619  * Returns 0 if success or ENOENT if no such entry.
620  */
621 int
622 ksyms_getname(const char **mod, const char **sym, vaddr_t v, int f)
623 {
624 	struct symtab *st;
625 	Elf_Sym *les, *es = NULL;
626 	vaddr_t laddr = 0;
627 	const char *lmod = NULL;
628 	char *stable = NULL;
629 	int type, i, sz;
630 
631 	if (ksymsinited == 0)
632 		return ENOENT;
633 
634 	CIRCLEQ_FOREACH(st, &symtab_queue, sd_queue) {
635 		if (st->sd_minsym != NULL && v < st->sd_minsym->st_value)
636 			continue;
637 		if (st->sd_maxsym != NULL && v > st->sd_maxsym->st_value)
638 			continue;
639 		sz = st->sd_symsize/sizeof(Elf_Sym);
640 		for (i = 0; i < sz; i++) {
641 			les = st->sd_symstart + i;
642 			type = ELF_ST_TYPE(les->st_info);
643 
644 			if ((f & KSYMS_PROC) && (type != STT_FUNC))
645 				continue;
646 
647 			if (type == STT_NOTYPE)
648 				continue;
649 
650 			if (((f & KSYMS_ANY) == 0) &&
651 			    (type != STT_FUNC) && (type != STT_OBJECT))
652 				continue;
653 
654 			if ((les->st_value <= v) && (les->st_value > laddr)) {
655 				laddr = les->st_value;
656 				es = les;
657 				lmod = st->sd_name;
658 				stable = st->sd_strstart - st->sd_usroffset;
659 			}
660 		}
661 	}
662 	if (es == NULL)
663 		return ENOENT;
664 	if ((f & KSYMS_EXACT) && (v != es->st_value))
665 		return ENOENT;
666 	if (mod)
667 		*mod = lmod;
668 	if (sym)
669 		*sym = stable + es->st_name;
670 	return 0;
671 }
672 
673 #if NKSYMS
674 static int symsz, strsz;
675 
676 /*
677  * In case we exposing the symbol table to the userland using the pseudo-
678  * device /dev/ksyms, it is easier to provide all the tables as one.
679  * However, it means we have to change all the st_name fields for the
680  * symbols so they match the ELF image that the userland will read
681  * through the device.
682  *
683  * The actual (correct) value of st_name is preserved through a global
684  * offset stored in the symbol table structure.
685  */
686 
687 static void
688 ksyms_sizes_calc(void)
689 {
690         struct symtab *st;
691 	int i;
692 
693         symsz = strsz = 0;
694         CIRCLEQ_FOREACH(st, &symtab_queue, sd_queue) {
695 		if (st != &kernel_symtab) {
696 			for (i = 0; i < st->sd_symsize/sizeof(Elf_Sym); i++)
697 				st->sd_symstart[i].st_name =
698 				    strsz + st->sd_symnmoff[i];
699 			st->sd_usroffset = strsz;
700 		}
701                 symsz += st->sd_symsize;
702                 strsz += st->sd_strsize;
703         }
704 }
705 #endif /* NKSYMS */
706 
707 /*
708  * Temporary work structure for dynamic loaded symbol tables.
709  * Will go away when in-kernel linker is in place.
710  */
711 
712 struct syminfo {
713 	size_t cursyms;
714 	size_t curnamep;
715 	size_t maxsyms;
716 	size_t maxnamep;
717 	Elf_Sym *syms;
718 	int *symnmoff;
719 	char *symnames;
720 };
721 
722 
723 /*
724  * Add a symbol to the temporary save area for symbols.
725  * This routine will go away when the in-kernel linker is in place.
726  */
727 static void
728 addsym(struct syminfo *info, const Elf_Sym *sym, const char *name,
729        const char *mod)
730 {
731 	int len, mlen;
732 
733 #ifdef KSYMS_DEBUG
734 	if (ksyms_debug & FOLLOW_MORE_CALLS)
735 		printf("addsym: name %s val %lx\n", name, (long)sym->st_value);
736 #endif
737 	len = strlen(name) + 1;
738 	if (mod)
739 		mlen = 1 + strlen(mod);
740 	else
741 		mlen = 0;
742 	if (info->cursyms == info->maxsyms ||
743 	    (len + mlen + info->curnamep) > info->maxnamep) {
744 		printf("addsym: too many symbols, skipping '%s'\n", name);
745 		return;
746 	}
747 	strlcpy(&info->symnames[info->curnamep], name,
748 	    info->maxnamep - info->curnamep);
749 	if (mlen) {
750 		info->symnames[info->curnamep + len - 1] = '.';
751 		strlcpy(&info->symnames[info->curnamep + len], mod,
752 		    info->maxnamep - (info->curnamep + len));
753 		len += mlen;
754 	}
755 	info->syms[info->cursyms] = *sym;
756 	info->syms[info->cursyms].st_name = info->curnamep;
757 	info->symnmoff[info->cursyms] = info->curnamep;
758 	info->curnamep += len;
759 #if NKSYMS
760 	if (len > ksyms_maxlen)
761 		ksyms_maxlen = len;
762 #endif
763 	info->cursyms++;
764 }
765 /*
766  * Adds a symbol table.
767  * "name" is the module name, "start" and "size" is where the symbol table
768  * is located, and "type" is in which binary format the symbol table is.
769  * New memory for keeping the symbol table is allocated in this function.
770  * Returns 0 if success and EEXIST if the module name is in use.
771  */
772 static int
773 specialsym(const char *symname)
774 {
775 	return	!strcmp(symname, "_bss_start") ||
776 		!strcmp(symname, "__bss_start") ||
777 		!strcmp(symname, "_bss_end__") ||
778 		!strcmp(symname, "__bss_end__") ||
779 		!strcmp(symname, "_edata") ||
780 		!strcmp(symname, "_end") ||
781 		!strcmp(symname, "__end") ||
782 		!strcmp(symname, "__end__") ||
783 		!strncmp(symname, "__start_link_set_", 17) ||
784 		!strncmp(symname, "__stop_link_set_", 16);
785 }
786 
787 int
788 ksyms_addsymtab(const char *mod, void *symstart, vsize_t symsize,
789     char *strstart, vsize_t strsize)
790 {
791 	Elf_Sym *sym = symstart;
792 	struct symtab *st;
793 	unsigned long rval;
794 	int i;
795 	char *name;
796 	struct syminfo info;
797 
798 #ifdef KSYMS_DEBUG
799 	if (ksyms_debug & FOLLOW_CALLS)
800 		printf("ksyms_addsymtab: mod %s symsize %lx strsize %lx\n",
801 		    mod, symsize, strsize);
802 #endif
803 
804 #if NKSYMS
805 	/*
806 	 * Do not try to add a symbol table while someone is reading
807 	 * from /dev/ksyms.
808 	 */
809 	while (ksyms_isopen != 0)
810 		tsleep(&ksyms_isopen, PWAIT, "ksyms", 0);
811 #endif
812 
813 	/* Check if this symtab already loaded */
814 	CIRCLEQ_FOREACH(st, &symtab_queue, sd_queue) {
815 		if (strcmp(mod, st->sd_name) == 0)
816 			return EEXIST;
817 	}
818 
819 	/*
820 	 * XXX - Only add a symbol if it do not exist already.
821 	 * This is because of a flaw in the current LKM implementation,
822 	 * these loops will be removed once the in-kernel linker is in place.
823 	 */
824 	memset(&info, 0, sizeof(info));
825 	for (i = 0; i < symsize/sizeof(Elf_Sym); i++) {
826 		char * const symname = strstart + sym[i].st_name;
827 		if (sym[i].st_name == 0)
828 			continue; /* Just ignore */
829 
830 		/* check validity of the symbol */
831 		/* XXX - save local symbols if DDB */
832 		if (ELF_ST_BIND(sym[i].st_info) != STB_GLOBAL)
833 			continue;
834 
835 		/* Check if the symbol exists */
836 		if (ksyms_getval(NULL, symname, &rval, KSYMS_EXTERN) == 0) {
837 			/* Check (and complain) about differing values */
838 			if (sym[i].st_value != rval &&
839 			    sym[i].st_shndx != SHN_UNDEF) {
840 				if (specialsym(symname)) {
841 					info.maxsyms++;
842 					info.maxnamep += strlen(symname) + 1 +
843 					    strlen(mod) + 1;
844 				} else {
845 					printf("%s: symbol '%s' redeclared with"
846 					    " different value (%lx != %lx)\n",
847 					    mod, symname,
848 					    rval, (long)sym[i].st_value);
849 				}
850 			}
851 		} else {
852 			/*
853 			 * Count this symbol
854 			 */
855 			info.maxsyms++;
856 			info.maxnamep += strlen(symname) + 1;
857 		}
858 	}
859 
860 	/*
861 	 * Now that we know the sizes, malloc the structures.
862 	 */
863 	info.syms = malloc(sizeof(Elf_Sym)*info.maxsyms, M_DEVBUF, M_WAITOK);
864 	info.symnames = malloc(info.maxnamep, M_DEVBUF, M_WAITOK);
865 	info.symnmoff = malloc(sizeof(int)*info.maxsyms, M_DEVBUF, M_WAITOK);
866 
867 	/*
868 	 * Now that we have the symbols, actually fill in the structures.
869 	 */
870 	for (i = 0; i < symsize/sizeof(Elf_Sym); i++) {
871 		char * const symname = strstart + sym[i].st_name;
872 		if (sym[i].st_name == 0)
873 			continue; /* Just ignore */
874 
875 		/* check validity of the symbol */
876 		/* XXX - save local symbols if DDB */
877 		if (ELF_ST_BIND(sym[i].st_info) != STB_GLOBAL)
878 			continue;
879 
880 		/* Check if the symbol exists */
881 		if (ksyms_getval(NULL, symname, &rval, KSYMS_EXTERN) == 0) {
882 			if ((sym[i].st_value != rval) && specialsym(symname)) {
883 				addsym(&info, &sym[i], symname, mod);
884 			}
885 		} else
886 			/* Ok, save this symbol */
887 			addsym(&info, &sym[i], symname, NULL);
888 	}
889 
890 	st = malloc(sizeof(struct symtab), M_DEVBUF, M_WAITOK);
891 	i = strlen(mod) + 1;
892 	name = malloc(i, M_DEVBUF, M_WAITOK);
893 	strlcpy(name, mod, i);
894 	st->sd_name = name;
895 	st->sd_symnmoff = info.symnmoff;
896 	st->sd_symstart = info.syms;
897 	st->sd_symsize = sizeof(Elf_Sym)*info.maxsyms;
898 	st->sd_strstart = info.symnames;
899 	st->sd_strsize = info.maxnamep;
900 
901 	/* Make them absolute references */
902 	sym = st->sd_symstart;
903 	for (i = 0; i < st->sd_symsize/sizeof(Elf_Sym); i++)
904 		sym[i].st_shndx = SHN_ABS;
905 
906 	CIRCLEQ_INSERT_TAIL(&symtab_queue, st, sd_queue);
907 #if NKSYMS
908 	ksyms_sizes_calc();
909 #endif
910 	return 0;
911 }
912 
913 /*
914  * Remove a symbol table specified by name.
915  * Returns 0 if success, EBUSY if device open and ENOENT if no such name.
916  */
917 int
918 ksyms_delsymtab(const char *mod)
919 {
920 	struct symtab *st;
921 	int found = 0;
922 
923 #if NKSYMS
924 	/*
925 	 * Do not try to delete a symbol table while someone is reading
926 	 * from /dev/ksyms.
927 	 */
928 	while (ksyms_isopen != 0)
929 		tsleep(&ksyms_isopen, PWAIT, "ksyms", 0);
930 #endif
931 
932 	CIRCLEQ_FOREACH(st, &symtab_queue, sd_queue) {
933 		if (strcmp(mod, st->sd_name) == 0) {
934 			found = 1;
935 			break;
936 		}
937 	}
938 	if (found == 0)
939 		return ENOENT;
940 	CIRCLEQ_REMOVE(&symtab_queue, st, sd_queue);
941 	free(st->sd_symstart, M_DEVBUF);
942 	free(st->sd_strstart, M_DEVBUF);
943 	free(st->sd_symnmoff, M_DEVBUF);
944 	/* XXXUNCONST LINTED - const castaway */
945 	free(__UNCONST(st->sd_name), M_DEVBUF);
946 	free(st, M_DEVBUF);
947 #if NKSYMS
948 	ksyms_sizes_calc();
949 #endif
950 	return 0;
951 }
952 
953 int
954 ksyms_rensymtab(const char *old, const char *new)
955 {
956 	struct symtab *st, *oldst = NULL;
957 	char *newstr;
958 
959 	CIRCLEQ_FOREACH(st, &symtab_queue, sd_queue) {
960 		if (strcmp(old, st->sd_name) == 0)
961 			oldst = st;
962 		if (strcmp(new, st->sd_name) == 0)
963 			return (EEXIST);
964 	}
965 	if (oldst == NULL)
966 		return (ENOENT);
967 
968 	newstr = malloc(strlen(new)+1, M_DEVBUF, M_WAITOK);
969 	if (!newstr)
970 		return (ENOMEM);
971 	strcpy(newstr, new);
972 	/*XXXUNCONST*/
973 	free(__UNCONST(oldst->sd_name), M_DEVBUF);
974 	oldst->sd_name = newstr;
975 
976 	return (0);
977 }
978 
979 #ifdef DDB
980 /*
981  * Keep sifting stuff here, to avoid export of ksyms internals.
982  */
983 int
984 ksyms_sift(char *mod, char *sym, int mode)
985 {
986 	struct symtab *st;
987 	char *sb;
988 	int i, sz;
989 
990 	if (ksymsinited == 0)
991 		return ENOENT;
992 
993 	CIRCLEQ_FOREACH(st, &symtab_queue, sd_queue) {
994 		if (mod && strcmp(mod, st->sd_name))
995 			continue;
996 		sb = st->sd_strstart;
997 
998 		sz = st->sd_symsize/sizeof(Elf_Sym);
999 		for (i = 0; i < sz; i++) {
1000 			Elf_Sym *les = st->sd_symstart + i;
1001 			char c;
1002 
1003 			if (strstr(sb + les->st_name - st->sd_usroffset, sym)
1004 			    == NULL)
1005 				continue;
1006 
1007 			if (mode == 'F') {
1008 				switch (ELF_ST_TYPE(les->st_info)) {
1009 				case STT_OBJECT:
1010 					c = '+';
1011 					break;
1012 				case STT_FUNC:
1013 					c = '*';
1014 					break;
1015 				case STT_SECTION:
1016 					c = '&';
1017 					break;
1018 				case STT_FILE:
1019 					c = '/';
1020 					break;
1021 				default:
1022 					c = ' ';
1023 					break;
1024 				}
1025 				db_printf("%s%c ", sb + les->st_name -
1026 				    st->sd_usroffset, c);
1027 			} else
1028 				db_printf("%s ", sb + les->st_name -
1029 				    st->sd_usroffset);
1030 		}
1031 	}
1032 	return ENOENT;
1033 }
1034 #endif /* DDB */
1035 
1036 #if NKSYMS
1037 /*
1038  * Static allocated ELF header.
1039  * Basic info is filled in at attach, sizes at open.
1040  */
1041 #define	SYMTAB		1
1042 #define	STRTAB		2
1043 #define	SHSTRTAB	3
1044 #define NSECHDR		4
1045 
1046 #define	NPRGHDR		2
1047 #define	SHSTRSIZ	28
1048 
1049 static struct ksyms_hdr {
1050 	Elf_Ehdr	kh_ehdr;
1051 	Elf_Phdr	kh_phdr[NPRGHDR];
1052 	Elf_Shdr	kh_shdr[NSECHDR];
1053 	char 		kh_strtab[SHSTRSIZ];
1054 } ksyms_hdr;
1055 
1056 
1057 static void
1058 ksyms_hdr_init(void *hdraddr)
1059 {
1060 
1061 	/* Copy the loaded elf exec header */
1062 	memcpy(&ksyms_hdr.kh_ehdr, hdraddr, sizeof(Elf_Ehdr));
1063 
1064 	/* Set correct program/section header sizes, offsets and numbers */
1065 	ksyms_hdr.kh_ehdr.e_phoff = offsetof(struct ksyms_hdr, kh_phdr[0]);
1066 	ksyms_hdr.kh_ehdr.e_phentsize = sizeof(Elf_Phdr);
1067 	ksyms_hdr.kh_ehdr.e_phnum = NPRGHDR;
1068 	ksyms_hdr.kh_ehdr.e_shoff = offsetof(struct ksyms_hdr, kh_shdr[0]);
1069 	ksyms_hdr.kh_ehdr.e_shentsize = sizeof(Elf_Shdr);
1070 	ksyms_hdr.kh_ehdr.e_shnum = NSECHDR;
1071 	ksyms_hdr.kh_ehdr.e_shstrndx = NSECHDR - 1; /* Last section */
1072 
1073 	/*
1074 	 * Keep program headers zeroed (unused).
1075 	 * The section headers are hand-crafted.
1076 	 * First section is section zero.
1077 	 */
1078 
1079 	/* Second section header; ".symtab" */
1080 	ksyms_hdr.kh_shdr[SYMTAB].sh_name = 1; /* Section 3 offset */
1081 	ksyms_hdr.kh_shdr[SYMTAB].sh_type = SHT_SYMTAB;
1082 	ksyms_hdr.kh_shdr[SYMTAB].sh_offset = sizeof(struct ksyms_hdr);
1083 /*	ksyms_hdr.kh_shdr[SYMTAB].sh_size = filled in at open */
1084 	ksyms_hdr.kh_shdr[SYMTAB].sh_link = 2; /* Corresponding strtab */
1085 	ksyms_hdr.kh_shdr[SYMTAB].sh_info = 0; /* XXX */
1086 	ksyms_hdr.kh_shdr[SYMTAB].sh_addralign = sizeof(long);
1087 	ksyms_hdr.kh_shdr[SYMTAB].sh_entsize = sizeof(Elf_Sym);
1088 
1089 	/* Third section header; ".strtab" */
1090 	ksyms_hdr.kh_shdr[STRTAB].sh_name = 9; /* Section 3 offset */
1091 	ksyms_hdr.kh_shdr[STRTAB].sh_type = SHT_STRTAB;
1092 /*	ksyms_hdr.kh_shdr[STRTAB].sh_offset = filled in at open */
1093 /*	ksyms_hdr.kh_shdr[STRTAB].sh_size = filled in at open */
1094 /*	ksyms_hdr.kh_shdr[STRTAB].sh_link = kept zero */
1095 	ksyms_hdr.kh_shdr[STRTAB].sh_info = 0;
1096 	ksyms_hdr.kh_shdr[STRTAB].sh_addralign = sizeof(char);
1097 	ksyms_hdr.kh_shdr[STRTAB].sh_entsize = 0;
1098 
1099 	/* Fourth section, ".shstrtab" */
1100 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_name = 17; /* This section name offset */
1101 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_type = SHT_STRTAB;
1102 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_offset =
1103 	    offsetof(struct ksyms_hdr, kh_strtab);
1104 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_size = SHSTRSIZ;
1105 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_addralign = sizeof(char);
1106 
1107 	/* Set section names */
1108 	strlcpy(&ksyms_hdr.kh_strtab[1], ".symtab",
1109 	    sizeof(ksyms_hdr.kh_strtab) - 1);
1110 	strlcpy(&ksyms_hdr.kh_strtab[9], ".strtab",
1111 	    sizeof(ksyms_hdr.kh_strtab) - 9);
1112 	strlcpy(&ksyms_hdr.kh_strtab[17], ".shstrtab",
1113 	    sizeof(ksyms_hdr.kh_strtab) - 17);
1114 };
1115 
1116 static int
1117 ksymsopen(dev_t dev, int oflags, int devtype, struct lwp *l)
1118 {
1119 
1120 	if (minor(dev))
1121 		return ENXIO;
1122 	if (ksymsinited == 0)
1123 		return ENXIO;
1124 
1125 	ksyms_hdr.kh_shdr[SYMTAB].sh_size = symsz;
1126 	ksyms_hdr.kh_shdr[STRTAB].sh_offset = symsz +
1127 	    ksyms_hdr.kh_shdr[SYMTAB].sh_offset;
1128 	ksyms_hdr.kh_shdr[STRTAB].sh_size = strsz;
1129 	ksyms_isopen = 1;
1130 
1131 #ifdef KSYMS_DEBUG
1132 	if (ksyms_debug & FOLLOW_DEVKSYMS)
1133 		printf("ksymsopen: symsz 0x%x strsz 0x%x\n", symsz, strsz);
1134 #endif
1135 
1136 	return 0;
1137 }
1138 
1139 static int
1140 ksymsclose(dev_t dev, int oflags, int devtype, struct lwp *l)
1141 {
1142 
1143 #ifdef KSYMS_DEBUG
1144 	if (ksyms_debug & FOLLOW_DEVKSYMS)
1145 		printf("ksymsclose\n");
1146 #endif
1147 
1148 	ksyms_isopen = 0;
1149 	wakeup(&ksyms_isopen);
1150 	return 0;
1151 }
1152 
1153 #define	HDRSIZ	sizeof(struct ksyms_hdr)
1154 
1155 static int
1156 ksymsread(dev_t dev, struct uio *uio, int ioflag)
1157 {
1158 	struct symtab *st;
1159 	size_t filepos, inpos, off;
1160 
1161 #ifdef KSYMS_DEBUG
1162 	if (ksyms_debug & FOLLOW_DEVKSYMS)
1163 		printf("ksymsread: offset 0x%llx resid 0x%zx\n",
1164 		    (long long)uio->uio_offset, uio->uio_resid);
1165 #endif
1166 
1167 	off = uio->uio_offset;
1168 	if (off >= (strsz + symsz + HDRSIZ))
1169 		return 0; /* End of symtab */
1170 	/*
1171 	 * First: Copy out the ELF header.
1172 	 */
1173 	if (off < HDRSIZ)
1174 		uiomove((char *)&ksyms_hdr + off, HDRSIZ - off, uio);
1175 
1176 	/*
1177 	 * Copy out the symbol table.
1178 	 */
1179 	filepos = HDRSIZ;
1180 	CIRCLEQ_FOREACH(st, &symtab_queue, sd_queue) {
1181 		if (uio->uio_resid == 0)
1182 			return 0;
1183 		if (uio->uio_offset <= st->sd_symsize + filepos) {
1184 			inpos = uio->uio_offset - filepos;
1185 			uiomove((char *)st->sd_symstart + inpos,
1186 			   st->sd_symsize - inpos, uio);
1187 		}
1188 		filepos += st->sd_symsize;
1189 	}
1190 
1191 	if (filepos != HDRSIZ + symsz)
1192 		panic("ksymsread: unsunc");
1193 
1194 	/*
1195 	 * Copy out the string table
1196 	 */
1197 	CIRCLEQ_FOREACH(st, &symtab_queue, sd_queue) {
1198 		if (uio->uio_resid == 0)
1199 			return 0;
1200 		if (uio->uio_offset <= st->sd_strsize + filepos) {
1201 			inpos = uio->uio_offset - filepos;
1202 			uiomove((char *)st->sd_strstart + inpos,
1203 			   st->sd_strsize - inpos, uio);
1204 		}
1205 		filepos += st->sd_strsize;
1206 	}
1207 	return 0;
1208 }
1209 
1210 static int
1211 ksymswrite(dev_t dev, struct uio *uio, int ioflag)
1212 {
1213 
1214 	return EROFS;
1215 }
1216 
1217 static int
1218 ksymsioctl(dev_t dev, u_long cmd, void *data, int fflag, struct lwp *l)
1219 {
1220 	struct ksyms_gsymbol *kg = (struct ksyms_gsymbol *)data;
1221 	struct symtab *st;
1222 	Elf_Sym *sym = NULL;
1223 	unsigned long val;
1224 	int error = 0;
1225 	char *str = NULL;
1226 
1227 	if (cmd == KIOCGVALUE || cmd == KIOCGSYMBOL)
1228 		str = malloc(ksyms_maxlen, M_DEVBUF, M_WAITOK);
1229 
1230 	switch (cmd) {
1231 	case KIOCGVALUE:
1232 		/*
1233 		 * Use the in-kernel symbol lookup code for fast
1234 		 * retreival of a value.
1235 		 */
1236 		if ((error = copyinstr(kg->kg_name, str, ksyms_maxlen, NULL)))
1237 			break;
1238 		if ((error = ksyms_getval(NULL, str, &val, KSYMS_EXTERN)))
1239 			break;
1240 		error = copyout(&val, kg->kg_value, sizeof(long));
1241 		break;
1242 
1243 	case KIOCGSYMBOL:
1244 		/*
1245 		 * Use the in-kernel symbol lookup code for fast
1246 		 * retreival of a symbol.
1247 		 */
1248 		if ((error = copyinstr(kg->kg_name, str, ksyms_maxlen, NULL)))
1249 			break;
1250 		CIRCLEQ_FOREACH(st, &symtab_queue, sd_queue) {
1251 			if ((sym = findsym(str, st)) == NULL) /* from userland */
1252 				continue;
1253 
1254 #ifdef notdef
1255 			/* Skip if bad binding */
1256 			if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL) {
1257 				sym = NULL;
1258 				continue;
1259 			}
1260 #endif
1261 			break;
1262 		}
1263 		/*
1264 		 * XXX which value of sym->st_name should be returned?  The real
1265 		 * one, or the one that matches what reading /dev/ksyms get?
1266 		 *
1267 		 * Currently, we're returning the /dev/ksyms one.
1268 		 */
1269 		if (sym != NULL)
1270 			error = copyout(sym, kg->kg_sym, sizeof(Elf_Sym));
1271 		else
1272 			error = ENOENT;
1273 		break;
1274 
1275 	case KIOCGSIZE:
1276 		/*
1277 		 * Get total size of symbol table.
1278 		 */
1279 		*(int *)data = strsz + symsz + HDRSIZ;
1280 		break;
1281 
1282 	default:
1283 		error = ENOTTY;
1284 		break;
1285 	}
1286 
1287 	if (cmd == KIOCGVALUE || cmd == KIOCGSYMBOL)
1288 		free(str, M_DEVBUF);
1289 
1290 	return error;
1291 }
1292 
1293 const struct cdevsw ksyms_cdevsw = {
1294 	ksymsopen, ksymsclose, ksymsread, ksymswrite, ksymsioctl,
1295 	    nullstop, notty, nopoll, nommap, nullkqfilter, DV_DULL
1296 };
1297 #endif /* NKSYMS */
1298