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