Home | History | Annotate | Line # | Download | only in kern
kern_ksyms.c revision 1.57
      1 /*	$NetBSD: kern_ksyms.c,v 1.57 2010/03/13 16:27:06 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2008 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software developed for The NetBSD Foundation
      8  * by Andrew Doran.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 2001, 2003 Anders Magnusson (ragge (at) ludd.luth.se).
     34  * All rights reserved.
     35  *
     36  * Redistribution and use in source and binary forms, with or without
     37  * modification, are permitted provided that the following conditions
     38  * are met:
     39  * 1. Redistributions of source code must retain the above copyright
     40  *    notice, this list of conditions and the following disclaimer.
     41  * 2. Redistributions in binary form must reproduce the above copyright
     42  *    notice, this list of conditions and the following disclaimer in the
     43  *    documentation and/or other materials provided with the distribution.
     44  * 3. The name of the author may not be used to endorse or promote products
     45  *    derived from this software without specific prior written permission
     46  *
     47  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     48  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     49  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     50  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     51  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     52  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     53  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     54  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     55  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     56  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     57  */
     58 
     59 /*
     60  * Code to deal with in-kernel symbol table management + /dev/ksyms.
     61  *
     62  * For each loaded module the symbol table info is kept track of by a
     63  * struct, placed in a circular list. The first entry is the kernel
     64  * symbol table.
     65  */
     66 
     67 /*
     68  * TODO:
     69  *
     70  *	Add support for mmap, poll.
     71  */
     72 
     73 #include <sys/cdefs.h>
     74 __KERNEL_RCSID(0, "$NetBSD: kern_ksyms.c,v 1.57 2010/03/13 16:27:06 christos Exp $");
     75 
     76 #if defined(_KERNEL) && defined(_KERNEL_OPT)
     77 #include "opt_ddb.h"
     78 #include "opt_ddbparam.h"	/* for SYMTAB_SPACE */
     79 #include "opt_dtrace.h"
     80 #endif
     81 
     82 #define _KSYMS_PRIVATE
     83 
     84 #include <sys/param.h>
     85 #include <sys/queue.h>
     86 #include <sys/exec.h>
     87 #include <sys/systm.h>
     88 #include <sys/conf.h>
     89 #include <sys/kmem.h>
     90 #include <sys/proc.h>
     91 #include <sys/atomic.h>
     92 #include <sys/ksyms.h>
     93 
     94 #include <uvm/uvm_extern.h>
     95 
     96 #ifdef DDB
     97 #include <ddb/db_output.h>
     98 #endif
     99 
    100 #include "ksyms.h"
    101 
    102 #define KSYMS_MAX_ID	65536
    103 #ifdef KDTRACE_HOOKS
    104 static uint32_t ksyms_nmap[KSYMS_MAX_ID];	/* sorted symbol table map */
    105 #else
    106 static uint32_t *ksyms_nmap = NULL;
    107 #endif
    108 
    109 static int ksyms_maxlen;
    110 static bool ksyms_isopen;
    111 static bool ksyms_initted;
    112 static struct ksyms_hdr ksyms_hdr;
    113 static kmutex_t ksyms_lock;
    114 
    115 void ksymsattach(int);
    116 static void ksyms_hdr_init(void *);
    117 static void ksyms_sizes_calc(void);
    118 
    119 #ifdef KSYMS_DEBUG
    120 #define	FOLLOW_CALLS		1
    121 #define	FOLLOW_MORE_CALLS	2
    122 #define	FOLLOW_DEVKSYMS		4
    123 static int ksyms_debug;
    124 #endif
    125 
    126 #ifdef SYMTAB_SPACE
    127 #define		SYMTAB_FILLER	"|This is the symbol table!"
    128 
    129 char		db_symtab[SYMTAB_SPACE] = SYMTAB_FILLER;
    130 int		db_symtabsize = SYMTAB_SPACE;
    131 #endif
    132 
    133 int ksyms_symsz;
    134 int ksyms_strsz;
    135 int ksyms_ctfsz;
    136 TAILQ_HEAD(, ksyms_symtab) ksyms_symtabs =
    137     TAILQ_HEAD_INITIALIZER(ksyms_symtabs);
    138 static struct ksyms_symtab kernel_symtab;
    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 	return 1;
    154 }
    155 
    156 /*
    157  * Finds a certain symbol name in a certain symbol table.
    158  */
    159 static Elf_Sym *
    160 findsym(const char *name, struct ksyms_symtab *table, int type)
    161 {
    162 	Elf_Sym *sym, *maxsym;
    163 	int low, mid, high, nglob;
    164 	char *str, *cmp;
    165 
    166 	sym = table->sd_symstart;
    167 	str = table->sd_strstart - table->sd_usroffset;
    168 	nglob = table->sd_nglob;
    169 	low = 0;
    170 	high = nglob;
    171 
    172 	/*
    173 	 * Start with a binary search of all global symbols in this table.
    174 	 * Global symbols must have unique names.
    175 	 */
    176 	while (low < high) {
    177 		mid = (low + high) >> 1;
    178 		cmp = sym[mid].st_name + str;
    179 		if (cmp[0] < name[0] || strcmp(cmp, name) < 0) {
    180 			low = mid + 1;
    181 		} else {
    182 			high = mid;
    183 		}
    184 	}
    185 	KASSERT(low == high);
    186 	if (__predict_true(low < nglob &&
    187 	    strcmp(sym[low].st_name + str, name) == 0)) {
    188 		KASSERT(ELF_ST_BIND(sym[low].st_info) == STB_GLOBAL);
    189 		return &sym[low];
    190 	}
    191 
    192 	/*
    193 	 * Perform a linear search of local symbols (rare).  Many local
    194 	 * symbols with the same name can exist so are not included in
    195 	 * the binary search.
    196 	 */
    197 	if (type != KSYMS_EXTERN) {
    198 		maxsym = sym + table->sd_symsize / sizeof(Elf_Sym);
    199 		for (sym += nglob; sym < maxsym; sym++) {
    200 			if (strcmp(name, sym->st_name + str) == 0) {
    201 				return sym;
    202 			}
    203 		}
    204 	}
    205 	return NULL;
    206 }
    207 
    208 /*
    209  * The "attach" is in reality done in ksyms_init().
    210  */
    211 void
    212 ksymsattach(int arg)
    213 {
    214 
    215 }
    216 
    217 void
    218 ksyms_init(void)
    219 {
    220 
    221 #ifdef SYMTAB_SPACE
    222 	if (!ksyms_initted &&
    223 	    strncmp(db_symtab, SYMTAB_FILLER, sizeof(SYMTAB_FILLER))) {
    224 		ksyms_addsyms_elf(db_symtabsize, db_symtab,
    225 		    db_symtab + db_symtabsize);
    226 	}
    227 #endif
    228 
    229 	mutex_init(&ksyms_lock, MUTEX_DEFAULT, IPL_NONE);
    230 }
    231 
    232 /*
    233  * Add a symbol table.
    234  * This is intended for use when the symbol table and its corresponding
    235  * string table are easily available.  If they are embedded in an ELF
    236  * image, use addsymtab_elf() instead.
    237  *
    238  * name - Symbol's table name.
    239  * symstart, symsize - Address and size of the symbol table.
    240  * strstart, strsize - Address and size of the string table.
    241  * tab - Symbol table to be updated with this information.
    242  * newstart - Address to which the symbol table has to be copied during
    243  *            shrinking.  If NULL, it is not moved.
    244  */
    245 static const char *addsymtab_strstart;
    246 
    247 static int
    248 addsymtab_compar(const void *a, const void *b)
    249 {
    250 	const Elf_Sym *sa, *sb;
    251 
    252 	sa = a;
    253 	sb = b;
    254 
    255 	/*
    256 	 * Split the symbol table into two, with globals at the start
    257 	 * and locals at the end.
    258 	 */
    259 	if (ELF_ST_BIND(sa->st_info) != ELF_ST_BIND(sb->st_info)) {
    260 		if (ELF_ST_BIND(sa->st_info) == STB_GLOBAL) {
    261 			return -1;
    262 		}
    263 		if (ELF_ST_BIND(sb->st_info) == STB_GLOBAL) {
    264 			return 1;
    265 		}
    266 	}
    267 
    268 	/* Within each band, sort by name. */
    269 	return strcmp(sa->st_name + addsymtab_strstart,
    270 	    sb->st_name + addsymtab_strstart);
    271 }
    272 
    273 static void
    274 addsymtab(const char *name, void *symstart, size_t symsize,
    275 	  void *strstart, size_t strsize, struct ksyms_symtab *tab,
    276 	  void *newstart, void *ctfstart, size_t ctfsize, uint32_t *nmap)
    277 {
    278 	Elf_Sym *sym, *nsym, ts;
    279 	int i, j, n, nglob;
    280 	char *str;
    281 	int nsyms = symsize / sizeof(Elf_Sym);
    282 
    283 	/* sanity check for pre-malloc map table used during startup */
    284 	if ((nmap == ksyms_nmap) && (nsyms >= KSYMS_MAX_ID)) {
    285 	    printf("kern_ksyms: ERROR %d > %d, increase KSYMS_MAX_ID\n",
    286 		    nsyms, KSYMS_MAX_ID);
    287 
    288 	    /* truncate for now */
    289 	    nsyms = KSYMS_MAX_ID-1;
    290 	}
    291 
    292 	tab->sd_symstart = symstart;
    293 	tab->sd_symsize = symsize;
    294 	tab->sd_strstart = strstart;
    295 	tab->sd_strsize = strsize;
    296 	tab->sd_name = name;
    297 	tab->sd_minsym = UINTPTR_MAX;
    298 	tab->sd_maxsym = 0;
    299 	tab->sd_usroffset = 0;
    300 	tab->sd_gone = false;
    301 	tab->sd_ctfstart = ctfstart;
    302 	tab->sd_ctfsize = ctfsize;
    303 	tab->sd_nmap = nmap;
    304 	tab->sd_nmapsize = nsyms;
    305 #ifdef KSYMS_DEBUG
    306 	printf("newstart %p sym %p ksyms_symsz %d str %p strsz %d send %p\n",
    307 	    newstart, symstart, symsize, strstart, strsize,
    308 	    tab->sd_strstart + tab->sd_strsize);
    309 #endif
    310 
    311 	if (nmap) {
    312 		memset(nmap, 0, nsyms * sizeof(uint32_t));
    313 	}
    314 
    315 	/* Pack symbol table by removing all file name references. */
    316 	sym = tab->sd_symstart;
    317 	nsym = (Elf_Sym *)newstart;
    318 	str = tab->sd_strstart;
    319 	nglob = 0;
    320 	for (i = n = 0; i < nsyms; i++) {
    321 
    322 	    	/* This breaks CTF mapping, so don't do it when
    323 		 * DTrace is enabled
    324 		 */
    325 #ifndef KDTRACE_HOOKS
    326 		/*
    327 		 * Remove useless symbols.
    328 		 * Should actually remove all typeless symbols.
    329 		 */
    330 		if (sym[i].st_name == 0)
    331 			continue; /* Skip nameless entries */
    332 		if (sym[i].st_shndx == SHN_UNDEF)
    333 			continue; /* Skip external references */
    334 		if (ELF_ST_TYPE(sym[i].st_info) == STT_FILE)
    335 			continue; /* Skip filenames */
    336 		if (ELF_ST_TYPE(sym[i].st_info) == STT_NOTYPE &&
    337 		    sym[i].st_value == 0 &&
    338 		    strcmp(str + sym[i].st_name, "*ABS*") == 0)
    339 			continue; /* XXX */
    340 		if (ELF_ST_TYPE(sym[i].st_info) == STT_NOTYPE &&
    341 		    strcmp(str + sym[i].st_name, "gcc2_compiled.") == 0)
    342 			continue; /* XXX */
    343 #endif
    344 
    345 		/* Save symbol. Set it as an absolute offset */
    346 		nsym[n] = sym[i];
    347 
    348 		if (nmap != NULL) {
    349 			/* Save the size, replace it with the symbol id so
    350 			 * the mapping can be done after the cleanup and sort.
    351 			 */
    352 			nmap[i] = nsym[n].st_size;
    353 			nsym[n].st_size = i+1;	/* zero is reserved */
    354 		}
    355 
    356 		nsym[n].st_shndx = SHBSS;
    357 		j = strlen(nsym[n].st_name + str) + 1;
    358 		if (j > ksyms_maxlen)
    359 			ksyms_maxlen = j;
    360 		nglob += (ELF_ST_BIND(nsym[n].st_info) == STB_GLOBAL);
    361 
    362 		/* Compute min and max symbols. */
    363 		if (nsym[n].st_value < tab->sd_minsym) {
    364 		    	tab->sd_minsym = nsym[n].st_value;
    365 		}
    366 		if (nsym[n].st_value > tab->sd_maxsym) {
    367 		    	tab->sd_maxsym = nsym[n].st_value;
    368 		}
    369 		n++;
    370 	}
    371 
    372 	/* Fill the rest of the record, and sort the symbols. */
    373 	tab->sd_symstart = nsym;
    374 	tab->sd_symsize = n * sizeof(Elf_Sym);
    375 	tab->sd_nglob = nglob;
    376 	addsymtab_strstart = str;
    377 	if (kheapsort(nsym, n, sizeof(Elf_Sym), addsymtab_compar, &ts) != 0)
    378 		panic("addsymtab");
    379 
    380 	/*
    381 	 * Build the mapping from original symbol id to new symbol table.
    382 	 * Deleted symbols will have a zero map, indices will be one based
    383 	 * instead of zero based.
    384 	 * Resulting map is sd_nmap[original_index] = new_index + 1
    385 	 */
    386 	if (nmap != NULL) {
    387 		int new;
    388 		for (new=0; new<n; new++) {
    389 			uint32_t orig = nsym[new].st_size - 1;
    390 			uint32_t size = nmap[orig];
    391 
    392 			nmap[orig] = new + 1;
    393 
    394 			/* restore the size */
    395 			nsym[new].st_size = size;
    396 		}
    397 	}
    398 
    399 	/* ksymsread() is unlocked, so membar. */
    400 	membar_producer();
    401 	TAILQ_INSERT_TAIL(&ksyms_symtabs, tab, sd_queue);
    402 	ksyms_sizes_calc();
    403 	ksyms_initted = true;
    404 }
    405 
    406 /*
    407  * Setup the kernel symbol table stuff.
    408  */
    409 void
    410 ksyms_addsyms_elf(int symsize, void *start, void *end)
    411 {
    412 	int i, j;
    413 	Elf_Shdr *shdr;
    414 	char *symstart = NULL, *strstart = NULL;
    415 	size_t strsize = 0;
    416 	Elf_Ehdr *ehdr;
    417 	char *ctfstart = NULL;
    418 	size_t ctfsize = 0;
    419 	char *shstr = NULL;
    420 
    421 	if (symsize <= 0) {
    422 		printf("[ Kernel symbol table missing! ]\n");
    423 		return;
    424 	}
    425 
    426 	/* Sanity check */
    427 	if (ALIGNED_POINTER(start, long) == 0) {
    428 		printf("[ Kernel symbol table has bad start address %p ]\n",
    429 		    start);
    430 		return;
    431 	}
    432 
    433 	ehdr = (Elf_Ehdr *)start;
    434 
    435 	/* check if this is a valid ELF header */
    436 	/* No reason to verify arch type, the kernel is actually running! */
    437 	if (memcmp(ehdr->e_ident, ELFMAG, SELFMAG) ||
    438 	    ehdr->e_ident[EI_CLASS] != ELFCLASS ||
    439 	    ehdr->e_version > 1) {
    440 		printf("[ Kernel symbol table invalid! ]\n");
    441 		return; /* nothing to do */
    442 	}
    443 
    444 	/* Loaded header will be scratched in addsymtab */
    445 	ksyms_hdr_init(start);
    446 
    447 	/* Find the symbol table and the corresponding string table. */
    448 	shdr = (Elf_Shdr *)((uint8_t *)start + ehdr->e_shoff);
    449 	for (i = 1; i < ehdr->e_shnum; i++) {
    450 		if (shdr[i].sh_type != SHT_SYMTAB)
    451 			continue;
    452 		if (shdr[i].sh_offset == 0)
    453 			continue;
    454 		symstart = (uint8_t *)start + shdr[i].sh_offset;
    455 		symsize = shdr[i].sh_size;
    456 		j = shdr[i].sh_link;
    457 		if (shdr[j].sh_offset == 0)
    458 			continue; /* Can this happen? */
    459 		strstart = (uint8_t *)start + shdr[j].sh_offset;
    460 		strsize = shdr[j].sh_size;
    461 		break;
    462 	}
    463 
    464 	/* Find the CTF section */
    465 	shdr = (Elf_Shdr *)((uint8_t *)start + ehdr->e_shoff);
    466 	if (ehdr->e_shstrndx != 0) {
    467 		shstr = (uint8_t*)start + shdr[ehdr->e_shstrndx].sh_offset;
    468 		for (i = 1; i < ehdr->e_shnum; i++) {
    469 			if (shdr[i].sh_type != SHT_PROGBITS)
    470 				continue;
    471 			if (strncmp(".SUNW_ctf", &shstr[shdr[i].sh_name] ,10) != 0)
    472 				continue;
    473 			ctfstart = (uint8_t *)start + shdr[i].sh_offset;
    474 			ctfsize = shdr[i].sh_size;
    475 			ksyms_ctfsz = ctfsize;
    476 #ifdef DEBUG
    477 			aprint_normal("Found CTF at %p, size 0x%zx\n",
    478 			    ctfstart, ctfsize);
    479 #endif
    480 			break;
    481 		}
    482 	}
    483 
    484 	if (!ksyms_verify(symstart, strstart))
    485 		return;
    486 
    487 	addsymtab("netbsd", symstart, symsize, strstart, strsize,
    488 	    &kernel_symtab, start, ctfstart, ctfsize, ksyms_nmap);
    489 
    490 #ifdef DEBUG
    491 	aprint_normal("Loaded initial symtab at %p, strtab at %p, # entries %ld\n",
    492 	    kernel_symtab.sd_symstart, kernel_symtab.sd_strstart,
    493 	    (long)kernel_symtab.sd_symsize/sizeof(Elf_Sym));
    494 #endif
    495 }
    496 
    497 /*
    498  * Setup the kernel symbol table stuff.
    499  * Use this when the address of the symbol and string tables are known;
    500  * otherwise use ksyms_init with an ELF image.
    501  * We need to pass a minimal ELF header which will later be completed by
    502  * ksyms_hdr_init and handed off to userland through /dev/ksyms.  We use
    503  * a void *rather than a pointer to avoid exposing the Elf_Ehdr type.
    504  */
    505 void
    506 ksyms_addsyms_explicit(void *ehdr, void *symstart, size_t symsize,
    507 		    void *strstart, size_t strsize)
    508 {
    509 
    510 	if (!ksyms_verify(symstart, strstart))
    511 		return;
    512 
    513 	ksyms_hdr_init(ehdr);
    514 	addsymtab("netbsd", symstart, symsize, strstart, strsize,
    515 	    &kernel_symtab, symstart, NULL, 0, ksyms_nmap);
    516 }
    517 
    518 /*
    519  * Get the value associated with a symbol.
    520  * "mod" is the module name, or null if any module.
    521  * "sym" is the symbol name.
    522  * "val" is a pointer to the corresponding value, if call succeeded.
    523  * Returns 0 if success or ENOENT if no such entry.
    524  *
    525  * Call with ksyms_lock, unless known that the symbol table can't change.
    526  */
    527 int
    528 ksyms_getval_unlocked(const char *mod, const char *sym, unsigned long *val,
    529 		      int type)
    530 {
    531 	struct ksyms_symtab *st;
    532 	Elf_Sym *es;
    533 
    534 #ifdef KSYMS_DEBUG
    535 	if (ksyms_debug & FOLLOW_CALLS)
    536 		printf("ksyms_getval_unlocked: mod %s sym %s valp %p\n",
    537 		    mod, sym, val);
    538 #endif
    539 
    540 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    541 		if (__predict_false(st->sd_gone))
    542 			continue;
    543 		if (mod != NULL && strcmp(st->sd_name, mod))
    544 			continue;
    545 		if ((es = findsym(sym, st, type)) != NULL) {
    546 			*val = es->st_value;
    547 			return 0;
    548 		}
    549 	}
    550 	return ENOENT;
    551 }
    552 
    553 int
    554 ksyms_getval(const char *mod, const char *sym, unsigned long *val, int type)
    555 {
    556 	int rc;
    557 
    558 	if (!ksyms_initted)
    559 		return ENOENT;
    560 
    561 	mutex_enter(&ksyms_lock);
    562 	rc = ksyms_getval_unlocked(mod, sym, val, type);
    563 	mutex_exit(&ksyms_lock);
    564 	return rc;
    565 }
    566 
    567 struct ksyms_symtab *
    568 ksyms_get_mod(const char *mod)
    569 {
    570 	struct ksyms_symtab *st;
    571 
    572 	mutex_enter(&ksyms_lock);
    573 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    574 		if (__predict_false(st->sd_gone))
    575 			continue;
    576 		if (mod != NULL && strcmp(st->sd_name, mod))
    577 			continue;
    578 		break;
    579 	}
    580 	mutex_exit(&ksyms_lock);
    581 
    582 	return st;
    583 }
    584 
    585 
    586 /*
    587  * ksyms_mod_foreach()
    588  *
    589  * Iterate over the symbol table of the specified module, calling the callback
    590  * handler for each symbol. Stop iterating if the handler return is non-zero.
    591  *
    592  */
    593 
    594 int
    595 ksyms_mod_foreach(const char *mod, ksyms_callback_t callback, void *opaque)
    596 {
    597 	struct ksyms_symtab *st;
    598 	Elf_Sym *sym, *maxsym;
    599 	char *str;
    600 	int symindx;
    601 
    602 	if (!ksyms_initted)
    603 		return ENOENT;
    604 
    605 	mutex_enter(&ksyms_lock);
    606 
    607 	/* find the module */
    608 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    609 		if (__predict_false(st->sd_gone))
    610 			continue;
    611 		if (mod != NULL && strcmp(st->sd_name, mod))
    612 			continue;
    613 
    614 		sym = st->sd_symstart;
    615 		str = st->sd_strstart - st->sd_usroffset;
    616 
    617 		/* now iterate through the symbols */
    618 		maxsym = sym + st->sd_symsize / sizeof(Elf_Sym);
    619 		for (symindx=0; sym < maxsym; sym++,symindx++) {
    620 			if (callback(str + sym->st_name, symindx,
    621 				    (void *)sym->st_value,
    622 				    sym->st_size,
    623 				    sym->st_info,
    624 				    opaque) != 0) {
    625 				break;
    626 			}
    627 		}
    628 	}
    629 	mutex_exit(&ksyms_lock);
    630 
    631 	return 0;
    632 }
    633 
    634 /*
    635  * Get "mod" and "symbol" associated with an address.
    636  * Returns 0 if success or ENOENT if no such entry.
    637  *
    638  * Call with ksyms_lock, unless known that the symbol table can't change.
    639  */
    640 int
    641 ksyms_getname(const char **mod, const char **sym, vaddr_t v, int f)
    642 {
    643 	struct ksyms_symtab *st;
    644 	Elf_Sym *les, *es = NULL;
    645 	vaddr_t laddr = 0;
    646 	const char *lmod = NULL;
    647 	char *stable = NULL;
    648 	int type, i, sz;
    649 
    650 	if (!ksyms_initted)
    651 		return ENOENT;
    652 
    653 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    654 		if (st->sd_gone)
    655 			continue;
    656 		if (v < st->sd_minsym || v > st->sd_maxsym)
    657 			continue;
    658 		sz = st->sd_symsize/sizeof(Elf_Sym);
    659 		for (i = 0; i < sz; i++) {
    660 			les = st->sd_symstart + i;
    661 			type = ELF_ST_TYPE(les->st_info);
    662 
    663 			if ((f & KSYMS_PROC) && (type != STT_FUNC))
    664 				continue;
    665 
    666 			if (type == STT_NOTYPE)
    667 				continue;
    668 
    669 			if (((f & KSYMS_ANY) == 0) &&
    670 			    (type != STT_FUNC) && (type != STT_OBJECT))
    671 				continue;
    672 
    673 			if ((les->st_value <= v) && (les->st_value > laddr)) {
    674 				laddr = les->st_value;
    675 				es = les;
    676 				lmod = st->sd_name;
    677 				stable = st->sd_strstart - st->sd_usroffset;
    678 			}
    679 		}
    680 	}
    681 	if (es == NULL)
    682 		return ENOENT;
    683 	if ((f & KSYMS_EXACT) && (v != es->st_value))
    684 		return ENOENT;
    685 	if (mod)
    686 		*mod = lmod;
    687 	if (sym)
    688 		*sym = stable + es->st_name;
    689 	return 0;
    690 }
    691 
    692 /*
    693  * Add a symbol table from a loadable module.
    694  */
    695 void
    696 ksyms_modload(const char *name, void *symstart, vsize_t symsize,
    697 	      char *strstart, vsize_t strsize)
    698 {
    699 	struct ksyms_symtab *st;
    700 
    701 	st = kmem_zalloc(sizeof(*st), KM_SLEEP);
    702 	mutex_enter(&ksyms_lock);
    703 	addsymtab(name, symstart, symsize, strstart, strsize, st, symstart,
    704 		NULL, 0, NULL);
    705 	mutex_exit(&ksyms_lock);
    706 }
    707 
    708 /*
    709  * Remove a symbol table from a loadable module.
    710  */
    711 void
    712 ksyms_modunload(const char *name)
    713 {
    714 	struct ksyms_symtab *st;
    715 
    716 	mutex_enter(&ksyms_lock);
    717 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    718 		if (st->sd_gone)
    719 			continue;
    720 		if (strcmp(name, st->sd_name) != 0)
    721 			continue;
    722 		st->sd_gone = true;
    723 		if (!ksyms_isopen) {
    724 			TAILQ_REMOVE(&ksyms_symtabs, st, sd_queue);
    725 			ksyms_sizes_calc();
    726 			kmem_free(st, sizeof(*st));
    727 		}
    728 		break;
    729 	}
    730 	mutex_exit(&ksyms_lock);
    731 	KASSERT(st != NULL);
    732 }
    733 
    734 #ifdef DDB
    735 /*
    736  * Keep sifting stuff here, to avoid export of ksyms internals.
    737  *
    738  * Systems is expected to be quiescent, so no locking done.
    739  */
    740 int
    741 ksyms_sift(char *mod, char *sym, int mode)
    742 {
    743 	struct ksyms_symtab *st;
    744 	char *sb;
    745 	int i, sz;
    746 
    747 	if (!ksyms_initted)
    748 		return ENOENT;
    749 
    750 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    751 		if (st->sd_gone)
    752 			continue;
    753 		if (mod && strcmp(mod, st->sd_name))
    754 			continue;
    755 		sb = st->sd_strstart - st->sd_usroffset;
    756 
    757 		sz = st->sd_symsize/sizeof(Elf_Sym);
    758 		for (i = 0; i < sz; i++) {
    759 			Elf_Sym *les = st->sd_symstart + i;
    760 			char c;
    761 
    762 			if (strstr(sb + les->st_name, sym) == NULL)
    763 				continue;
    764 
    765 			if (mode == 'F') {
    766 				switch (ELF_ST_TYPE(les->st_info)) {
    767 				case STT_OBJECT:
    768 					c = '+';
    769 					break;
    770 				case STT_FUNC:
    771 					c = '*';
    772 					break;
    773 				case STT_SECTION:
    774 					c = '&';
    775 					break;
    776 				case STT_FILE:
    777 					c = '/';
    778 					break;
    779 				default:
    780 					c = ' ';
    781 					break;
    782 				}
    783 				db_printf("%s%c ", sb + les->st_name, c);
    784 			} else
    785 				db_printf("%s ", sb + les->st_name);
    786 		}
    787 	}
    788 	return ENOENT;
    789 }
    790 #endif /* DDB */
    791 
    792 /*
    793  * In case we exposing the symbol table to the userland using the pseudo-
    794  * device /dev/ksyms, it is easier to provide all the tables as one.
    795  * However, it means we have to change all the st_name fields for the
    796  * symbols so they match the ELF image that the userland will read
    797  * through the device.
    798  *
    799  * The actual (correct) value of st_name is preserved through a global
    800  * offset stored in the symbol table structure.
    801  *
    802  * Call with ksyms_lock held.
    803  */
    804 static void
    805 ksyms_sizes_calc(void)
    806 {
    807         struct ksyms_symtab *st;
    808 	int i, delta;
    809 
    810         ksyms_symsz = ksyms_strsz = 0;
    811         TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    812 		delta = ksyms_strsz - st->sd_usroffset;
    813 		if (delta != 0) {
    814 			for (i = 0; i < st->sd_symsize/sizeof(Elf_Sym); i++)
    815 				st->sd_symstart[i].st_name += delta;
    816 			st->sd_usroffset = ksyms_strsz;
    817 		}
    818                 ksyms_symsz += st->sd_symsize;
    819                 ksyms_strsz += st->sd_strsize;
    820         }
    821 }
    822 
    823 static void
    824 ksyms_hdr_init(void *hdraddr)
    825 {
    826 
    827 	/* Copy the loaded elf exec header */
    828 	memcpy(&ksyms_hdr.kh_ehdr, hdraddr, sizeof(Elf_Ehdr));
    829 
    830 	/* Set correct program/section header sizes, offsets and numbers */
    831 	ksyms_hdr.kh_ehdr.e_phoff = offsetof(struct ksyms_hdr, kh_phdr[0]);
    832 	ksyms_hdr.kh_ehdr.e_phentsize = sizeof(Elf_Phdr);
    833 	ksyms_hdr.kh_ehdr.e_phnum = NPRGHDR;
    834 	ksyms_hdr.kh_ehdr.e_shoff = offsetof(struct ksyms_hdr, kh_shdr[0]);
    835 	ksyms_hdr.kh_ehdr.e_shentsize = sizeof(Elf_Shdr);
    836 	ksyms_hdr.kh_ehdr.e_shnum = NSECHDR;
    837 	ksyms_hdr.kh_ehdr.e_shstrndx = SHSTRTAB;
    838 
    839 	/* Text/data - fake */
    840 	ksyms_hdr.kh_phdr[0].p_type = PT_LOAD;
    841 	ksyms_hdr.kh_phdr[0].p_memsz = (unsigned long)-1L;
    842 	ksyms_hdr.kh_phdr[0].p_flags = PF_R | PF_X | PF_W;
    843 
    844 	/* First section is null */
    845 
    846 	/* Second section header; ".symtab" */
    847 	ksyms_hdr.kh_shdr[SYMTAB].sh_name = 1; /* Section 3 offset */
    848 	ksyms_hdr.kh_shdr[SYMTAB].sh_type = SHT_SYMTAB;
    849 	ksyms_hdr.kh_shdr[SYMTAB].sh_offset = sizeof(struct ksyms_hdr);
    850 /*	ksyms_hdr.kh_shdr[SYMTAB].sh_size = filled in at open */
    851 	ksyms_hdr.kh_shdr[SYMTAB].sh_link = 2; /* Corresponding strtab */
    852 	ksyms_hdr.kh_shdr[SYMTAB].sh_addralign = sizeof(long);
    853 	ksyms_hdr.kh_shdr[SYMTAB].sh_entsize = sizeof(Elf_Sym);
    854 
    855 	/* Third section header; ".strtab" */
    856 	ksyms_hdr.kh_shdr[STRTAB].sh_name = 9; /* Section 3 offset */
    857 	ksyms_hdr.kh_shdr[STRTAB].sh_type = SHT_STRTAB;
    858 /*	ksyms_hdr.kh_shdr[STRTAB].sh_offset = filled in at open */
    859 /*	ksyms_hdr.kh_shdr[STRTAB].sh_size = filled in at open */
    860 	ksyms_hdr.kh_shdr[STRTAB].sh_addralign = sizeof(char);
    861 
    862 	/* Fourth section, ".shstrtab" */
    863 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_name = 17; /* This section name offset */
    864 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_type = SHT_STRTAB;
    865 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_offset =
    866 	    offsetof(struct ksyms_hdr, kh_strtab);
    867 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_size = SHSTRSIZ;
    868 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_addralign = sizeof(char);
    869 
    870 	/* Fifth section, ".bss". All symbols reside here. */
    871 	ksyms_hdr.kh_shdr[SHBSS].sh_name = 27; /* This section name offset */
    872 	ksyms_hdr.kh_shdr[SHBSS].sh_type = SHT_NOBITS;
    873 	ksyms_hdr.kh_shdr[SHBSS].sh_offset = 0;
    874 	ksyms_hdr.kh_shdr[SHBSS].sh_size = (unsigned long)-1L;
    875 	ksyms_hdr.kh_shdr[SHBSS].sh_addralign = PAGE_SIZE;
    876 	ksyms_hdr.kh_shdr[SHBSS].sh_flags = SHF_ALLOC | SHF_EXECINSTR;
    877 
    878 	/* Sixth section header; ".SUNW_ctf" */
    879 	ksyms_hdr.kh_shdr[SHCTF].sh_name = 32; /* Section 6 offset */
    880 	ksyms_hdr.kh_shdr[SHCTF].sh_type = SHT_PROGBITS;
    881 /*	ksyms_hdr.kh_shdr[SHCTF].sh_offset = filled in at open */
    882 /*	ksyms_hdr.kh_shdr[SHCTF].sh_size = filled in at open */
    883 	ksyms_hdr.kh_shdr[SHCTF].sh_link = SYMTAB; /* Corresponding symtab */
    884 	ksyms_hdr.kh_shdr[SHCTF].sh_addralign = sizeof(char);
    885 
    886 	/* Set section names */
    887 	strlcpy(&ksyms_hdr.kh_strtab[1], ".symtab",
    888 	    sizeof(ksyms_hdr.kh_strtab) - 1);
    889 	strlcpy(&ksyms_hdr.kh_strtab[9], ".strtab",
    890 	    sizeof(ksyms_hdr.kh_strtab) - 9);
    891 	strlcpy(&ksyms_hdr.kh_strtab[17], ".shstrtab",
    892 	    sizeof(ksyms_hdr.kh_strtab) - 17);
    893 	strlcpy(&ksyms_hdr.kh_strtab[27], ".bss",
    894 	    sizeof(ksyms_hdr.kh_strtab) - 27);
    895 	strlcpy(&ksyms_hdr.kh_strtab[32], ".SUNW_ctf",
    896 	    sizeof(ksyms_hdr.kh_strtab) - 32);
    897 }
    898 
    899 static int
    900 ksymsopen(dev_t dev, int oflags, int devtype, struct lwp *l)
    901 {
    902 
    903 	if (minor(dev) != 0 || !ksyms_initted)
    904 		return ENXIO;
    905 
    906 	/*
    907 	 * Create a "snapshot" of the kernel symbol table.  Setting
    908 	 * ksyms_isopen will prevent symbol tables from being freed.
    909 	 */
    910 	mutex_enter(&ksyms_lock);
    911 	ksyms_hdr.kh_shdr[SYMTAB].sh_size = ksyms_symsz;
    912 	ksyms_hdr.kh_shdr[SYMTAB].sh_info = ksyms_symsz / sizeof(Elf_Sym);
    913 	ksyms_hdr.kh_shdr[STRTAB].sh_offset = ksyms_symsz +
    914 	    ksyms_hdr.kh_shdr[SYMTAB].sh_offset;
    915 	ksyms_hdr.kh_shdr[STRTAB].sh_size = ksyms_strsz;
    916 	ksyms_hdr.kh_shdr[SHCTF].sh_offset = ksyms_strsz +
    917 	    ksyms_hdr.kh_shdr[STRTAB].sh_offset;
    918 	ksyms_hdr.kh_shdr[SHCTF].sh_size = ksyms_ctfsz;
    919 	ksyms_isopen = true;
    920 	mutex_exit(&ksyms_lock);
    921 
    922 	return 0;
    923 }
    924 
    925 static int
    926 ksymsclose(dev_t dev, int oflags, int devtype, struct lwp *l)
    927 {
    928 	struct ksyms_symtab *st, *next;
    929 	bool resize;
    930 
    931 	/* Discard refernces to symbol tables. */
    932 	mutex_enter(&ksyms_lock);
    933 	ksyms_isopen = false;
    934 	resize = false;
    935 	for (st = TAILQ_FIRST(&ksyms_symtabs); st != NULL; st = next) {
    936 		next = TAILQ_NEXT(st, sd_queue);
    937 		if (st->sd_gone) {
    938 			TAILQ_REMOVE(&ksyms_symtabs, st, sd_queue);
    939 			kmem_free(st, sizeof(*st));
    940 			resize = true;
    941 		}
    942 	}
    943 	if (resize)
    944 		ksyms_sizes_calc();
    945 	mutex_exit(&ksyms_lock);
    946 
    947 	return 0;
    948 }
    949 
    950 static int
    951 ksymsread(dev_t dev, struct uio *uio, int ioflag)
    952 {
    953 	struct ksyms_symtab *st, *cst;
    954 	size_t filepos, inpos, off;
    955 	int error;
    956 
    957 	/*
    958 	 * First: Copy out the ELF header.   XXX Lose if ksymsopen()
    959 	 * occurs during read of the header.
    960 	 */
    961 	off = uio->uio_offset;
    962 	if (off < sizeof(struct ksyms_hdr)) {
    963 		error = uiomove((char *)&ksyms_hdr + off,
    964 		    sizeof(struct ksyms_hdr) - off, uio);
    965 		if (error != 0)
    966 			return error;
    967 	}
    968 
    969 	/*
    970 	 * Copy out the symbol table.
    971 	 */
    972 	filepos = sizeof(struct ksyms_hdr);
    973 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    974 		if (uio->uio_resid == 0)
    975 			return 0;
    976 		if (uio->uio_offset <= st->sd_symsize + filepos) {
    977 			inpos = uio->uio_offset - filepos;
    978 			error = uiomove((char *)st->sd_symstart + inpos,
    979 			   st->sd_symsize - inpos, uio);
    980 			if (error != 0)
    981 				return error;
    982 		}
    983 		filepos += st->sd_symsize;
    984 	}
    985 
    986 	/*
    987 	 * Copy out the string table
    988 	 */
    989 	KASSERT(filepos == sizeof(struct ksyms_hdr) +
    990 	    ksyms_hdr.kh_shdr[SYMTAB].sh_size);
    991 	TAILQ_FOREACH(st, &ksyms_symtabs, 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 			error = uiomove((char *)st->sd_strstart + inpos,
    997 			   st->sd_strsize - inpos, uio);
    998 			if (error != 0)
    999 				return error;
   1000 		}
   1001 		filepos += st->sd_strsize;
   1002 	}
   1003 
   1004 	/*
   1005 	 * Copy out the CTF table.
   1006 	 */
   1007 	cst = TAILQ_FIRST(&ksyms_symtabs);
   1008 	if (cst->sd_ctfstart != NULL) {
   1009 		if (uio->uio_resid == 0)
   1010 			return 0;
   1011 		if (uio->uio_offset <= cst->sd_ctfsize + filepos) {
   1012 			inpos = uio->uio_offset - filepos;
   1013 			error = uiomove((char *)cst->sd_ctfstart + inpos,
   1014 			   cst->sd_ctfsize - inpos, uio);
   1015 			if (error != 0)
   1016 				return error;
   1017 		}
   1018 		filepos += cst->sd_ctfsize;
   1019 	}
   1020 
   1021 
   1022 	return 0;
   1023 }
   1024 
   1025 static int
   1026 ksymswrite(dev_t dev, struct uio *uio, int ioflag)
   1027 {
   1028 
   1029 	return EROFS;
   1030 }
   1031 
   1032 static int
   1033 ksymsioctl(dev_t dev, u_long cmd, void *data, int fflag, struct lwp *l)
   1034 {
   1035 	struct ksyms_gsymbol *kg = (struct ksyms_gsymbol *)data;
   1036 	struct ksyms_symtab *st;
   1037 	Elf_Sym *sym = NULL, copy;
   1038 	unsigned long val;
   1039 	int error = 0;
   1040 	char *str = NULL;
   1041 	int len;
   1042 
   1043 	/* Read ksyms_maxlen only once while not holding the lock. */
   1044 	len = ksyms_maxlen;
   1045 
   1046 	if (cmd == KIOCGVALUE || cmd == KIOCGSYMBOL) {
   1047 		str = kmem_alloc(len, KM_SLEEP);
   1048 		if ((error = copyinstr(kg->kg_name, str, len, NULL)) != 0) {
   1049 			kmem_free(str, len);
   1050 			return error;
   1051 		}
   1052 	}
   1053 
   1054 	switch (cmd) {
   1055 	case KIOCGVALUE:
   1056 		/*
   1057 		 * Use the in-kernel symbol lookup code for fast
   1058 		 * retreival of a value.
   1059 		 */
   1060 		error = ksyms_getval(NULL, str, &val, KSYMS_EXTERN);
   1061 		if (error == 0)
   1062 			error = copyout(&val, kg->kg_value, sizeof(long));
   1063 		kmem_free(str, len);
   1064 		break;
   1065 
   1066 	case KIOCGSYMBOL:
   1067 		/*
   1068 		 * Use the in-kernel symbol lookup code for fast
   1069 		 * retreival of a symbol.
   1070 		 */
   1071 		mutex_enter(&ksyms_lock);
   1072 		TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
   1073 			if (st->sd_gone)
   1074 				continue;
   1075 			if ((sym = findsym(str, st, KSYMS_ANY)) == NULL)
   1076 				continue;
   1077 #ifdef notdef
   1078 			/* Skip if bad binding */
   1079 			if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL) {
   1080 				sym = NULL;
   1081 				continue;
   1082 			}
   1083 #endif
   1084 			break;
   1085 		}
   1086 		if (sym != NULL) {
   1087 			memcpy(&copy, sym, sizeof(copy));
   1088 			mutex_exit(&ksyms_lock);
   1089 			error = copyout(&copy, kg->kg_sym, sizeof(Elf_Sym));
   1090 		} else {
   1091 			mutex_exit(&ksyms_lock);
   1092 			error = ENOENT;
   1093 		}
   1094 		kmem_free(str, len);
   1095 		break;
   1096 
   1097 	case KIOCGSIZE:
   1098 		/*
   1099 		 * Get total size of symbol table.
   1100 		 */
   1101 		mutex_enter(&ksyms_lock);
   1102 		*(int *)data = ksyms_strsz + ksyms_symsz +
   1103 		    sizeof(struct ksyms_hdr);
   1104 		mutex_exit(&ksyms_lock);
   1105 		break;
   1106 
   1107 	default:
   1108 		error = ENOTTY;
   1109 		break;
   1110 	}
   1111 
   1112 	return error;
   1113 }
   1114 
   1115 const struct cdevsw ksyms_cdevsw = {
   1116 	ksymsopen, ksymsclose, ksymsread, ksymswrite, ksymsioctl,
   1117 	nullstop, notty, nopoll, nommap, nullkqfilter, D_OTHER | D_MPSAFE
   1118 };
   1119