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