Home | History | Annotate | Line # | Download | only in kern
kern_ksyms.c revision 1.102
      1 /*	$NetBSD: kern_ksyms.c,v 1.102 2021/09/07 16:56:25 riastradh 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  *	Constify tables.
     72  *	Constify db_symtab and move it to .rodata.
     73  */
     74 
     75 #include <sys/cdefs.h>
     76 __KERNEL_RCSID(0, "$NetBSD: kern_ksyms.c,v 1.102 2021/09/07 16:56:25 riastradh Exp $");
     77 
     78 #if defined(_KERNEL) && defined(_KERNEL_OPT)
     79 #include "opt_copy_symtab.h"
     80 #include "opt_ddb.h"
     81 #include "opt_dtrace.h"
     82 #endif
     83 
     84 #define _KSYMS_PRIVATE
     85 
     86 #include <sys/param.h>
     87 #include <sys/queue.h>
     88 #include <sys/exec.h>
     89 #include <sys/systm.h>
     90 #include <sys/conf.h>
     91 #include <sys/kmem.h>
     92 #include <sys/proc.h>
     93 #include <sys/atomic.h>
     94 #include <sys/ksyms.h>
     95 #include <sys/kernel.h>
     96 #include <sys/intr.h>
     97 
     98 #ifdef DDB
     99 #include <ddb/db_output.h>
    100 #endif
    101 
    102 #include "ksyms.h"
    103 #if NKSYMS > 0
    104 #include "ioconf.h"
    105 #endif
    106 
    107 #define KSYMS_MAX_ID	98304
    108 #ifdef KDTRACE_HOOKS
    109 static uint32_t ksyms_nmap[KSYMS_MAX_ID];	/* sorted symbol table map */
    110 #else
    111 static uint32_t *ksyms_nmap = NULL;
    112 #endif
    113 
    114 static int ksyms_maxlen;
    115 static uint64_t ksyms_opencnt;
    116 static struct ksyms_symtab *ksyms_last_snapshot;
    117 static bool ksyms_initted;
    118 static bool ksyms_loaded;
    119 static kmutex_t ksyms_lock __cacheline_aligned;
    120 static struct ksyms_symtab kernel_symtab;
    121 
    122 static void ksyms_hdr_init(const void *);
    123 static void ksyms_sizes_calc(void);
    124 
    125 #ifdef KSYMS_DEBUG
    126 #define	FOLLOW_CALLS		1
    127 #define	FOLLOW_MORE_CALLS	2
    128 #define	FOLLOW_DEVKSYMS		4
    129 static int ksyms_debug;
    130 #endif
    131 
    132 #define		SYMTAB_FILLER	"|This is the symbol table!"
    133 
    134 #ifdef makeoptions_COPY_SYMTAB
    135 extern char db_symtab[];
    136 extern int db_symtabsize;
    137 #endif
    138 
    139 /*
    140  * used by savecore(8) so non-static
    141  */
    142 struct ksyms_hdr ksyms_hdr;
    143 int ksyms_symsz;
    144 int ksyms_strsz;
    145 int ksyms_ctfsz;	/* this is not currently used by savecore(8) */
    146 TAILQ_HEAD(ksyms_symtab_queue, ksyms_symtab) ksyms_symtabs =
    147     TAILQ_HEAD_INITIALIZER(ksyms_symtabs);
    148 
    149 static int
    150 ksyms_verify(const void *symstart, const void *strstart)
    151 {
    152 #if defined(DIAGNOSTIC) || defined(DEBUG)
    153 	if (symstart == NULL)
    154 		printf("ksyms: Symbol table not found\n");
    155 	if (strstart == NULL)
    156 		printf("ksyms: String table not found\n");
    157 	if (symstart == NULL || strstart == NULL)
    158 		printf("ksyms: Perhaps the kernel is stripped?\n");
    159 #endif
    160 	if (symstart == NULL || strstart == NULL)
    161 		return 0;
    162 	return 1;
    163 }
    164 
    165 /*
    166  * Finds a certain symbol name in a certain symbol table.
    167  */
    168 static Elf_Sym *
    169 findsym(const char *name, struct ksyms_symtab *table, int type)
    170 {
    171 	Elf_Sym *sym, *maxsym;
    172 	int low, mid, high, nglob;
    173 	char *str, *cmp;
    174 
    175 	sym = table->sd_symstart;
    176 	str = table->sd_strstart - table->sd_usroffset;
    177 	nglob = table->sd_nglob;
    178 	low = 0;
    179 	high = nglob;
    180 
    181 	/*
    182 	 * Start with a binary search of all global symbols in this table.
    183 	 * Global symbols must have unique names.
    184 	 */
    185 	while (low < high) {
    186 		mid = (low + high) >> 1;
    187 		cmp = sym[mid].st_name + str;
    188 		if (cmp[0] < name[0] || strcmp(cmp, name) < 0) {
    189 			low = mid + 1;
    190 		} else {
    191 			high = mid;
    192 		}
    193 	}
    194 	KASSERT(low == high);
    195 	if (__predict_true(low < nglob &&
    196 	    strcmp(sym[low].st_name + str, name) == 0)) {
    197 		KASSERT(ELF_ST_BIND(sym[low].st_info) == STB_GLOBAL);
    198 		return &sym[low];
    199 	}
    200 
    201 	/*
    202 	 * Perform a linear search of local symbols (rare).  Many local
    203 	 * symbols with the same name can exist so are not included in
    204 	 * the binary search.
    205 	 */
    206 	if (type != KSYMS_EXTERN) {
    207 		maxsym = sym + table->sd_symsize / sizeof(Elf_Sym);
    208 		for (sym += nglob; sym < maxsym; sym++) {
    209 			if (strcmp(name, sym->st_name + str) == 0) {
    210 				return sym;
    211 			}
    212 		}
    213 	}
    214 	return NULL;
    215 }
    216 
    217 /*
    218  * The "attach" is in reality done in ksyms_init().
    219  */
    220 #if NKSYMS > 0
    221 /*
    222  * ksyms can be loaded even if the kernel has a missing "pseudo-device ksyms"
    223  * statement because ddb and modules require it. Fixing it properly requires
    224  * fixing config to warn about required, but missing preudo-devices. For now,
    225  * if we don't have the pseudo-device we don't need the attach function; this
    226  * is fine, as it does nothing.
    227  */
    228 void
    229 ksymsattach(int arg)
    230 {
    231 }
    232 #endif
    233 
    234 void
    235 ksyms_init(void)
    236 {
    237 
    238 #ifdef makeoptions_COPY_SYMTAB
    239 	if (!ksyms_loaded &&
    240 	    strncmp(db_symtab, SYMTAB_FILLER, sizeof(SYMTAB_FILLER))) {
    241 		ksyms_addsyms_elf(db_symtabsize, db_symtab,
    242 		    db_symtab + db_symtabsize);
    243 	}
    244 #endif
    245 
    246 	if (!ksyms_initted) {
    247 		mutex_init(&ksyms_lock, MUTEX_DEFAULT, IPL_NONE);
    248 		ksyms_initted = true;
    249 	}
    250 }
    251 
    252 /*
    253  * Are any symbols available?
    254  */
    255 bool
    256 ksyms_available(void)
    257 {
    258 
    259 	return ksyms_loaded;
    260 }
    261 
    262 /*
    263  * Add a symbol table.
    264  * This is intended for use when the symbol table and its corresponding
    265  * string table are easily available.  If they are embedded in an ELF
    266  * image, use addsymtab_elf() instead.
    267  *
    268  * name - Symbol's table name.
    269  * symstart, symsize - Address and size of the symbol table.
    270  * strstart, strsize - Address and size of the string table.
    271  * tab - Symbol table to be updated with this information.
    272  * newstart - Address to which the symbol table has to be copied during
    273  *            shrinking.  If NULL, it is not moved.
    274  */
    275 static const char *addsymtab_strstart;
    276 
    277 static int
    278 addsymtab_compar(const void *a, const void *b)
    279 {
    280 	const Elf_Sym *sa, *sb;
    281 
    282 	sa = a;
    283 	sb = b;
    284 
    285 	/*
    286 	 * Split the symbol table into two, with globals at the start
    287 	 * and locals at the end.
    288 	 */
    289 	if (ELF_ST_BIND(sa->st_info) != ELF_ST_BIND(sb->st_info)) {
    290 		if (ELF_ST_BIND(sa->st_info) == STB_GLOBAL) {
    291 			return -1;
    292 		}
    293 		if (ELF_ST_BIND(sb->st_info) == STB_GLOBAL) {
    294 			return 1;
    295 		}
    296 	}
    297 
    298 	/* Within each band, sort by name. */
    299 	return strcmp(sa->st_name + addsymtab_strstart,
    300 	    sb->st_name + addsymtab_strstart);
    301 }
    302 
    303 static void
    304 addsymtab(const char *name, void *symstart, size_t symsize,
    305 	  void *strstart, size_t strsize, struct ksyms_symtab *tab,
    306 	  void *newstart, void *ctfstart, size_t ctfsize, uint32_t *nmap)
    307 {
    308 	Elf_Sym *sym, *nsym, ts;
    309 	int i, j, n, nglob;
    310 	char *str;
    311 	int nsyms = symsize / sizeof(Elf_Sym);
    312 	int s;
    313 
    314 	/* Sanity check for pre-allocated map table used during startup. */
    315 	if ((nmap == ksyms_nmap) && (nsyms >= KSYMS_MAX_ID)) {
    316 		printf("kern_ksyms: ERROR %d > %d, increase KSYMS_MAX_ID\n",
    317 		    nsyms, KSYMS_MAX_ID);
    318 
    319 		/* truncate for now */
    320 		nsyms = KSYMS_MAX_ID - 1;
    321 	}
    322 
    323 	tab->sd_symstart = symstart;
    324 	tab->sd_symsize = symsize;
    325 	tab->sd_strstart = strstart;
    326 	tab->sd_strsize = strsize;
    327 	tab->sd_name = name;
    328 	tab->sd_minsym = UINTPTR_MAX;
    329 	tab->sd_maxsym = 0;
    330 	tab->sd_usroffset = 0;
    331 	tab->sd_gone = false;
    332 	tab->sd_ctfstart = ctfstart;
    333 	tab->sd_ctfsize = ctfsize;
    334 	tab->sd_nmap = nmap;
    335 	tab->sd_nmapsize = nsyms;
    336 #ifdef KSYMS_DEBUG
    337 	printf("newstart %p sym %p ksyms_symsz %zu str %p strsz %zu send %p\n",
    338 	    newstart, symstart, symsize, strstart, strsize,
    339 	    tab->sd_strstart + tab->sd_strsize);
    340 #endif
    341 
    342 	if (nmap) {
    343 		memset(nmap, 0, nsyms * sizeof(uint32_t));
    344 	}
    345 
    346 	/* Pack symbol table by removing all file name references. */
    347 	sym = tab->sd_symstart;
    348 	nsym = (Elf_Sym *)newstart;
    349 	str = tab->sd_strstart;
    350 	nglob = 0;
    351 	for (i = n = 0; i < nsyms; i++) {
    352 
    353 		/*
    354 		 * This breaks CTF mapping, so don't do it when
    355 		 * DTrace is enabled.
    356 		 */
    357 #ifndef KDTRACE_HOOKS
    358 		/*
    359 		 * Remove useless symbols.
    360 		 * Should actually remove all typeless symbols.
    361 		 */
    362 		if (sym[i].st_name == 0)
    363 			continue; /* Skip nameless entries */
    364 		if (sym[i].st_shndx == SHN_UNDEF)
    365 			continue; /* Skip external references */
    366 		if (ELF_ST_TYPE(sym[i].st_info) == STT_FILE)
    367 			continue; /* Skip filenames */
    368 		if (ELF_ST_TYPE(sym[i].st_info) == STT_NOTYPE &&
    369 		    sym[i].st_value == 0 &&
    370 		    strcmp(str + sym[i].st_name, "*ABS*") == 0)
    371 			continue; /* XXX */
    372 		if (ELF_ST_TYPE(sym[i].st_info) == STT_NOTYPE &&
    373 		    strcmp(str + sym[i].st_name, "gcc2_compiled.") == 0)
    374 			continue; /* XXX */
    375 #endif
    376 
    377 		/* Save symbol. Set it as an absolute offset */
    378 		nsym[n] = sym[i];
    379 
    380 #ifdef KDTRACE_HOOKS
    381 		if (nmap != NULL) {
    382 			/*
    383 			 * Save the size, replace it with the symbol id so
    384 			 * the mapping can be done after the cleanup and sort.
    385 			 */
    386 			nmap[i] = nsym[n].st_size;
    387 			nsym[n].st_size = i + 1;	/* zero is reserved */
    388 		}
    389 #endif
    390 
    391 		if (sym[i].st_shndx != SHN_ABS) {
    392 			nsym[n].st_shndx = SHBSS;
    393 		} else {
    394 			/* SHN_ABS is a magic value, don't overwrite it */
    395 		}
    396 
    397 		j = strlen(nsym[n].st_name + str) + 1;
    398 		if (j > ksyms_maxlen)
    399 			ksyms_maxlen = j;
    400 		nglob += (ELF_ST_BIND(nsym[n].st_info) == STB_GLOBAL);
    401 
    402 		/* Compute min and max symbols. */
    403 		if (strcmp(str + sym[i].st_name, "*ABS*") != 0
    404 		    && ELF_ST_TYPE(nsym[n].st_info) != STT_NOTYPE) {
    405 			if (nsym[n].st_value < tab->sd_minsym) {
    406 				tab->sd_minsym = nsym[n].st_value;
    407 			}
    408 			if (nsym[n].st_value > tab->sd_maxsym) {
    409 				tab->sd_maxsym = nsym[n].st_value;
    410 			}
    411 		}
    412 		n++;
    413 	}
    414 
    415 	/* Fill the rest of the record, and sort the symbols. */
    416 	tab->sd_symstart = nsym;
    417 	tab->sd_symsize = n * sizeof(Elf_Sym);
    418 	tab->sd_nglob = nglob;
    419 
    420 	addsymtab_strstart = str;
    421 	if (kheapsort(nsym, n, sizeof(Elf_Sym), addsymtab_compar, &ts) != 0)
    422 		panic("addsymtab");
    423 
    424 #ifdef KDTRACE_HOOKS
    425 	/*
    426 	 * Build the mapping from original symbol id to new symbol table.
    427 	 * Deleted symbols will have a zero map, indices will be one based
    428 	 * instead of zero based.
    429 	 * Resulting map is sd_nmap[original_index] = new_index + 1
    430 	 */
    431 	if (nmap != NULL) {
    432 		int new;
    433 		for (new = 0; new < n; new++) {
    434 			uint32_t orig = nsym[new].st_size - 1;
    435 			uint32_t size = nmap[orig];
    436 
    437 			nmap[orig] = new + 1;
    438 
    439 			/* restore the size */
    440 			nsym[new].st_size = size;
    441 		}
    442 	}
    443 #endif
    444 
    445 	KASSERT(strcmp(name, "netbsd") == 0 || mutex_owned(&ksyms_lock));
    446 	KASSERT(cold || mutex_owned(&ksyms_lock));
    447 
    448 	/*
    449 	 * Ensure ddb never witnesses an inconsistent state of the
    450 	 * queue, unless memory is so corrupt that we crash in
    451 	 * TAILQ_INSERT_TAIL.
    452 	 */
    453 	s = splhigh();
    454 	TAILQ_INSERT_TAIL(&ksyms_symtabs, tab, sd_queue);
    455 	splx(s);
    456 
    457 	ksyms_sizes_calc();
    458 	ksyms_loaded = true;
    459 }
    460 
    461 /*
    462  * Setup the kernel symbol table stuff.
    463  */
    464 void
    465 ksyms_addsyms_elf(int symsize, void *start, void *end)
    466 {
    467 	int i, j;
    468 	Elf_Shdr *shdr;
    469 	char *symstart = NULL, *strstart = NULL;
    470 	size_t strsize = 0;
    471 	Elf_Ehdr *ehdr;
    472 	char *ctfstart = NULL;
    473 	size_t ctfsize = 0;
    474 
    475 	if (symsize <= 0) {
    476 		printf("[ Kernel symbol table missing! ]\n");
    477 		return;
    478 	}
    479 
    480 	/* Sanity check */
    481 	if (ALIGNED_POINTER(start, long) == 0) {
    482 		printf("[ Kernel symbol table has bad start address %p ]\n",
    483 		    start);
    484 		return;
    485 	}
    486 
    487 	ehdr = (Elf_Ehdr *)start;
    488 
    489 	/* check if this is a valid ELF header */
    490 	/* No reason to verify arch type, the kernel is actually running! */
    491 	if (memcmp(ehdr->e_ident, ELFMAG, SELFMAG) ||
    492 	    ehdr->e_ident[EI_CLASS] != ELFCLASS ||
    493 	    ehdr->e_version > 1) {
    494 		printf("[ Kernel symbol table invalid! ]\n");
    495 		return; /* nothing to do */
    496 	}
    497 
    498 	/* Loaded header will be scratched in addsymtab */
    499 	ksyms_hdr_init(start);
    500 
    501 	/* Find the symbol table and the corresponding string table. */
    502 	shdr = (Elf_Shdr *)((uint8_t *)start + ehdr->e_shoff);
    503 	for (i = 1; i < ehdr->e_shnum; i++) {
    504 		if (shdr[i].sh_type != SHT_SYMTAB)
    505 			continue;
    506 		if (shdr[i].sh_offset == 0)
    507 			continue;
    508 		symstart = (uint8_t *)start + shdr[i].sh_offset;
    509 		symsize = shdr[i].sh_size;
    510 		j = shdr[i].sh_link;
    511 		if (shdr[j].sh_offset == 0)
    512 			continue; /* Can this happen? */
    513 		strstart = (uint8_t *)start + shdr[j].sh_offset;
    514 		strsize = shdr[j].sh_size;
    515 		break;
    516 	}
    517 
    518 #ifdef KDTRACE_HOOKS
    519 	/* Find the CTF section */
    520 	shdr = (Elf_Shdr *)((uint8_t *)start + ehdr->e_shoff);
    521 	if (ehdr->e_shstrndx != 0) {
    522 		char *shstr = (uint8_t *)start +
    523 		    shdr[ehdr->e_shstrndx].sh_offset;
    524 		for (i = 1; i < ehdr->e_shnum; i++) {
    525 #ifdef DEBUG
    526 			printf("ksyms: checking %s\n", &shstr[shdr[i].sh_name]);
    527 #endif
    528 			if (shdr[i].sh_type != SHT_PROGBITS)
    529 				continue;
    530 			if (strncmp(".SUNW_ctf", &shstr[shdr[i].sh_name], 10)
    531 			    != 0)
    532 				continue;
    533 			ctfstart = (uint8_t *)start + shdr[i].sh_offset;
    534 			ctfsize = shdr[i].sh_size;
    535 			ksyms_ctfsz = ctfsize;
    536 #ifdef DEBUG
    537 			aprint_normal("Found CTF at %p, size 0x%zx\n",
    538 			    ctfstart, ctfsize);
    539 #endif
    540 			break;
    541 		}
    542 #ifdef DEBUG
    543 	} else {
    544 		printf("ksyms: e_shstrndx == 0\n");
    545 #endif
    546 	}
    547 #endif
    548 
    549 	if (!ksyms_verify(symstart, strstart))
    550 		return;
    551 
    552 	addsymtab("netbsd", symstart, symsize, strstart, strsize,
    553 	    &kernel_symtab, symstart, ctfstart, ctfsize, ksyms_nmap);
    554 
    555 #ifdef DEBUG
    556 	aprint_normal("Loaded initial symtab at %p, strtab at %p, # entries %ld\n",
    557 	    kernel_symtab.sd_symstart, kernel_symtab.sd_strstart,
    558 	    (long)kernel_symtab.sd_symsize/sizeof(Elf_Sym));
    559 #endif
    560 }
    561 
    562 /*
    563  * Setup the kernel symbol table stuff.
    564  * Use this when the address of the symbol and string tables are known;
    565  * otherwise use ksyms_init with an ELF image.
    566  * We need to pass a minimal ELF header which will later be completed by
    567  * ksyms_hdr_init and handed off to userland through /dev/ksyms.  We use
    568  * a void *rather than a pointer to avoid exposing the Elf_Ehdr type.
    569  */
    570 void
    571 ksyms_addsyms_explicit(void *ehdr, void *symstart, size_t symsize,
    572     void *strstart, size_t strsize)
    573 {
    574 	if (!ksyms_verify(symstart, strstart))
    575 		return;
    576 
    577 	ksyms_hdr_init(ehdr);
    578 	addsymtab("netbsd", symstart, symsize, strstart, strsize,
    579 	    &kernel_symtab, symstart, NULL, 0, ksyms_nmap);
    580 }
    581 
    582 /*
    583  * Get the value associated with a symbol.
    584  * "mod" is the module name, or null if any module.
    585  * "sym" is the symbol name.
    586  * "val" is a pointer to the corresponding value, if call succeeded.
    587  * Returns 0 if success or ENOENT if no such entry.
    588  *
    589  * Call with ksyms_lock, unless known that the symbol table can't change.
    590  */
    591 int
    592 ksyms_getval_unlocked(const char *mod, const char *sym, Elf_Sym **symp,
    593     unsigned long *val, int type)
    594 {
    595 	struct ksyms_symtab *st;
    596 	Elf_Sym *es;
    597 
    598 #ifdef KSYMS_DEBUG
    599 	if (ksyms_debug & FOLLOW_CALLS)
    600 		printf("%s: mod %s sym %s valp %p\n", __func__, mod, sym, val);
    601 #endif
    602 
    603 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    604 		if (__predict_false(st->sd_gone))
    605 			continue;
    606 		if (mod != NULL && strcmp(st->sd_name, mod))
    607 			continue;
    608 		if ((es = findsym(sym, st, type)) != NULL) {
    609 			*val = es->st_value;
    610 			if (symp)
    611 				*symp = es;
    612 			return 0;
    613 		}
    614 	}
    615 	return ENOENT;
    616 }
    617 
    618 int
    619 ksyms_getval(const char *mod, const char *sym, unsigned long *val, int type)
    620 {
    621 	int rc;
    622 
    623 	if (!ksyms_loaded)
    624 		return ENOENT;
    625 
    626 	mutex_enter(&ksyms_lock);
    627 	rc = ksyms_getval_unlocked(mod, sym, NULL, val, type);
    628 	mutex_exit(&ksyms_lock);
    629 	return rc;
    630 }
    631 
    632 struct ksyms_symtab *
    633 ksyms_get_mod(const char *mod)
    634 {
    635 	struct ksyms_symtab *st;
    636 
    637 	mutex_enter(&ksyms_lock);
    638 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    639 		if (__predict_false(st->sd_gone))
    640 			continue;
    641 		if (mod != NULL && strcmp(st->sd_name, mod))
    642 			continue;
    643 		break;
    644 	}
    645 	mutex_exit(&ksyms_lock);
    646 
    647 	return st;
    648 }
    649 
    650 
    651 /*
    652  * ksyms_mod_foreach()
    653  *
    654  * Iterate over the symbol table of the specified module, calling the callback
    655  * handler for each symbol. Stop iterating if the handler return is non-zero.
    656  *
    657  */
    658 
    659 int
    660 ksyms_mod_foreach(const char *mod, ksyms_callback_t callback, void *opaque)
    661 {
    662 	struct ksyms_symtab *st;
    663 	Elf_Sym *sym, *maxsym;
    664 	char *str;
    665 	int symindx;
    666 
    667 	if (!ksyms_loaded)
    668 		return ENOENT;
    669 
    670 	mutex_enter(&ksyms_lock);
    671 
    672 	/* find the module */
    673 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    674 		if (__predict_false(st->sd_gone))
    675 			continue;
    676 		if (mod != NULL && strcmp(st->sd_name, mod))
    677 			continue;
    678 
    679 		sym = st->sd_symstart;
    680 		str = st->sd_strstart - st->sd_usroffset;
    681 
    682 		/* now iterate through the symbols */
    683 		maxsym = sym + st->sd_symsize / sizeof(Elf_Sym);
    684 		for (symindx = 0; sym < maxsym; sym++, symindx++) {
    685 			if (callback(str + sym->st_name, symindx,
    686 			    (void *)sym->st_value,
    687 			    sym->st_size,
    688 			    sym->st_info,
    689 			    opaque) != 0) {
    690 				break;
    691 			}
    692 		}
    693 	}
    694 	mutex_exit(&ksyms_lock);
    695 
    696 	return 0;
    697 }
    698 
    699 /*
    700  * Get "mod" and "symbol" associated with an address.
    701  * Returns 0 if success or ENOENT if no such entry.
    702  *
    703  * Call with ksyms_lock, unless known that the symbol table can't change.
    704  */
    705 int
    706 ksyms_getname(const char **mod, const char **sym, vaddr_t v, int f)
    707 {
    708 	struct ksyms_symtab *st;
    709 	Elf_Sym *les, *es = NULL;
    710 	vaddr_t laddr = 0;
    711 	const char *lmod = NULL;
    712 	char *stable = NULL;
    713 	int type, i, sz;
    714 
    715 	if (!ksyms_loaded)
    716 		return ENOENT;
    717 
    718 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    719 		if (st->sd_gone)
    720 			continue;
    721 		if (v < st->sd_minsym || v > st->sd_maxsym)
    722 			continue;
    723 		sz = st->sd_symsize/sizeof(Elf_Sym);
    724 		for (i = 0; i < sz; i++) {
    725 			les = st->sd_symstart + i;
    726 			type = ELF_ST_TYPE(les->st_info);
    727 
    728 			if ((f & KSYMS_PROC) && (type != STT_FUNC))
    729 				continue;
    730 
    731 			if (type == STT_NOTYPE)
    732 				continue;
    733 
    734 			if (((f & KSYMS_ANY) == 0) &&
    735 			    (type != STT_FUNC) && (type != STT_OBJECT))
    736 				continue;
    737 
    738 			if ((les->st_value <= v) && (les->st_value > laddr)) {
    739 				laddr = les->st_value;
    740 				es = les;
    741 				lmod = st->sd_name;
    742 				stable = st->sd_strstart - st->sd_usroffset;
    743 			}
    744 		}
    745 	}
    746 	if (es == NULL)
    747 		return ENOENT;
    748 	if ((f & KSYMS_EXACT) && (v != es->st_value))
    749 		return ENOENT;
    750 	if (mod)
    751 		*mod = lmod;
    752 	if (sym)
    753 		*sym = stable + es->st_name;
    754 	return 0;
    755 }
    756 
    757 /*
    758  * Add a symbol table from a loadable module.
    759  */
    760 void
    761 ksyms_modload(const char *name, void *symstart, vsize_t symsize,
    762     char *strstart, vsize_t strsize)
    763 {
    764 	struct ksyms_symtab *st;
    765 	void *nmap;
    766 
    767 	st = kmem_zalloc(sizeof(*st), KM_SLEEP);
    768 	nmap = kmem_zalloc(symsize / sizeof(Elf_Sym) * sizeof (uint32_t),
    769 			   KM_SLEEP);
    770 	mutex_enter(&ksyms_lock);
    771 	addsymtab(name, symstart, symsize, strstart, strsize, st, symstart,
    772 	    NULL, 0, nmap);
    773 	mutex_exit(&ksyms_lock);
    774 }
    775 
    776 /*
    777  * Remove a symbol table from a loadable module.
    778  */
    779 void
    780 ksyms_modunload(const char *name)
    781 {
    782 	struct ksyms_symtab *st;
    783 	bool do_free = false;
    784 	int s;
    785 
    786 	mutex_enter(&ksyms_lock);
    787 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    788 		if (st->sd_gone)
    789 			continue;
    790 		if (strcmp(name, st->sd_name) != 0)
    791 			continue;
    792 		st->sd_gone = true;
    793 		ksyms_sizes_calc();
    794 		if (ksyms_opencnt == 0) {
    795 			/*
    796 			 * Ensure ddb never witnesses an inconsistent
    797 			 * state of the queue, unless memory is so
    798 			 * corrupt that we crash in TAILQ_REMOVE.
    799 			 */
    800 			s = splhigh();
    801 			TAILQ_REMOVE(&ksyms_symtabs, st, sd_queue);
    802 			splx(s);
    803 			do_free = true;
    804 		}
    805 		break;
    806 	}
    807 	mutex_exit(&ksyms_lock);
    808 	KASSERT(st != NULL);
    809 
    810 	if (do_free) {
    811 		kmem_free(st->sd_nmap, st->sd_nmapsize * sizeof(uint32_t));
    812 		kmem_free(st, sizeof(*st));
    813 	}
    814 }
    815 
    816 #ifdef DDB
    817 /*
    818  * Keep sifting stuff here, to avoid export of ksyms internals.
    819  *
    820  * Systems is expected to be quiescent, so no locking done.
    821  */
    822 int
    823 ksyms_sift(char *mod, char *sym, int mode)
    824 {
    825 	struct ksyms_symtab *st;
    826 	char *sb;
    827 	int i, sz;
    828 
    829 	if (!ksyms_loaded)
    830 		return ENOENT;
    831 
    832 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    833 		if (st->sd_gone)
    834 			continue;
    835 		if (mod && strcmp(mod, st->sd_name))
    836 			continue;
    837 		sb = st->sd_strstart - st->sd_usroffset;
    838 
    839 		sz = st->sd_symsize/sizeof(Elf_Sym);
    840 		for (i = 0; i < sz; i++) {
    841 			Elf_Sym *les = st->sd_symstart + i;
    842 			char c;
    843 
    844 			if (strstr(sb + les->st_name, sym) == NULL)
    845 				continue;
    846 
    847 			if (mode == 'F') {
    848 				switch (ELF_ST_TYPE(les->st_info)) {
    849 				case STT_OBJECT:
    850 					c = '+';
    851 					break;
    852 				case STT_FUNC:
    853 					c = '*';
    854 					break;
    855 				case STT_SECTION:
    856 					c = '&';
    857 					break;
    858 				case STT_FILE:
    859 					c = '/';
    860 					break;
    861 				default:
    862 					c = ' ';
    863 					break;
    864 				}
    865 				db_printf("%s%c ", sb + les->st_name, c);
    866 			} else
    867 				db_printf("%s ", sb + les->st_name);
    868 		}
    869 	}
    870 	return ENOENT;
    871 }
    872 #endif /* DDB */
    873 
    874 /*
    875  * In case we exposing the symbol table to the userland using the pseudo-
    876  * device /dev/ksyms, it is easier to provide all the tables as one.
    877  * However, it means we have to change all the st_name fields for the
    878  * symbols so they match the ELF image that the userland will read
    879  * through the device.
    880  *
    881  * The actual (correct) value of st_name is preserved through a global
    882  * offset stored in the symbol table structure.
    883  *
    884  * Call with ksyms_lock held.
    885  */
    886 static void
    887 ksyms_sizes_calc(void)
    888 {
    889 	struct ksyms_symtab *st;
    890 	int i, delta;
    891 
    892 	KASSERT(cold || mutex_owned(&ksyms_lock));
    893 
    894 	ksyms_symsz = ksyms_strsz = 0;
    895 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    896 		if (__predict_false(st->sd_gone))
    897 			continue;
    898 		delta = ksyms_strsz - st->sd_usroffset;
    899 		if (delta != 0) {
    900 			for (i = 0; i < st->sd_symsize/sizeof(Elf_Sym); i++)
    901 				st->sd_symstart[i].st_name += delta;
    902 			st->sd_usroffset = ksyms_strsz;
    903 		}
    904 		ksyms_symsz += st->sd_symsize;
    905 		ksyms_strsz += st->sd_strsize;
    906 	}
    907 }
    908 
    909 static void
    910 ksyms_fill_note(void)
    911 {
    912 	int32_t *note = ksyms_hdr.kh_note;
    913 	note[0] = ELF_NOTE_NETBSD_NAMESZ;
    914 	note[1] = ELF_NOTE_NETBSD_DESCSZ;
    915 	note[2] = ELF_NOTE_TYPE_NETBSD_TAG;
    916 	memcpy(&note[3],  "NetBSD\0", 8);
    917 	note[5] = __NetBSD_Version__;
    918 }
    919 
    920 static void
    921 ksyms_hdr_init(const void *hdraddr)
    922 {
    923 	/* Copy the loaded elf exec header */
    924 	memcpy(&ksyms_hdr.kh_ehdr, hdraddr, sizeof(Elf_Ehdr));
    925 
    926 	/* Set correct program/section header sizes, offsets and numbers */
    927 	ksyms_hdr.kh_ehdr.e_phoff = offsetof(struct ksyms_hdr, kh_phdr[0]);
    928 	ksyms_hdr.kh_ehdr.e_phentsize = sizeof(Elf_Phdr);
    929 	ksyms_hdr.kh_ehdr.e_phnum = NPRGHDR;
    930 	ksyms_hdr.kh_ehdr.e_shoff = offsetof(struct ksyms_hdr, kh_shdr[0]);
    931 	ksyms_hdr.kh_ehdr.e_shentsize = sizeof(Elf_Shdr);
    932 	ksyms_hdr.kh_ehdr.e_shnum = NSECHDR;
    933 	ksyms_hdr.kh_ehdr.e_shstrndx = SHSTRTAB;
    934 
    935 	/* Text/data - fake */
    936 	ksyms_hdr.kh_phdr[0].p_type = PT_LOAD;
    937 	ksyms_hdr.kh_phdr[0].p_memsz = (unsigned long)-1L;
    938 	ksyms_hdr.kh_phdr[0].p_flags = PF_R | PF_X | PF_W;
    939 
    940 #define SHTCOPY(name)  strlcpy(&ksyms_hdr.kh_strtab[offs], (name), \
    941     sizeof(ksyms_hdr.kh_strtab) - offs), offs += sizeof(name)
    942 
    943 	uint32_t offs = 1;
    944 	/* First section header ".note.netbsd.ident" */
    945 	ksyms_hdr.kh_shdr[SHNOTE].sh_name = offs;
    946 	ksyms_hdr.kh_shdr[SHNOTE].sh_type = SHT_NOTE;
    947 	ksyms_hdr.kh_shdr[SHNOTE].sh_offset =
    948 	    offsetof(struct ksyms_hdr, kh_note[0]);
    949 	ksyms_hdr.kh_shdr[SHNOTE].sh_size = sizeof(ksyms_hdr.kh_note);
    950 	ksyms_hdr.kh_shdr[SHNOTE].sh_addralign = sizeof(int);
    951 	SHTCOPY(".note.netbsd.ident");
    952 	ksyms_fill_note();
    953 
    954 	/* Second section header; ".symtab" */
    955 	ksyms_hdr.kh_shdr[SYMTAB].sh_name = offs;
    956 	ksyms_hdr.kh_shdr[SYMTAB].sh_type = SHT_SYMTAB;
    957 	ksyms_hdr.kh_shdr[SYMTAB].sh_offset = sizeof(struct ksyms_hdr);
    958 /*	ksyms_hdr.kh_shdr[SYMTAB].sh_size = filled in at open */
    959 	ksyms_hdr.kh_shdr[SYMTAB].sh_link = STRTAB; /* Corresponding strtab */
    960 	ksyms_hdr.kh_shdr[SYMTAB].sh_addralign = sizeof(long);
    961 	ksyms_hdr.kh_shdr[SYMTAB].sh_entsize = sizeof(Elf_Sym);
    962 	SHTCOPY(".symtab");
    963 
    964 	/* Third section header; ".strtab" */
    965 	ksyms_hdr.kh_shdr[STRTAB].sh_name = offs;
    966 	ksyms_hdr.kh_shdr[STRTAB].sh_type = SHT_STRTAB;
    967 /*	ksyms_hdr.kh_shdr[STRTAB].sh_offset = filled in at open */
    968 /*	ksyms_hdr.kh_shdr[STRTAB].sh_size = filled in at open */
    969 	ksyms_hdr.kh_shdr[STRTAB].sh_addralign = sizeof(char);
    970 	SHTCOPY(".strtab");
    971 
    972 	/* Fourth section, ".shstrtab" */
    973 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_name = offs;
    974 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_type = SHT_STRTAB;
    975 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_offset =
    976 	    offsetof(struct ksyms_hdr, kh_strtab);
    977 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_size = SHSTRSIZ;
    978 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_addralign = sizeof(char);
    979 	SHTCOPY(".shstrtab");
    980 
    981 	/* Fifth section, ".bss". All symbols reside here. */
    982 	ksyms_hdr.kh_shdr[SHBSS].sh_name = offs;
    983 	ksyms_hdr.kh_shdr[SHBSS].sh_type = SHT_NOBITS;
    984 	ksyms_hdr.kh_shdr[SHBSS].sh_offset = 0;
    985 	ksyms_hdr.kh_shdr[SHBSS].sh_size = (unsigned long)-1L;
    986 	ksyms_hdr.kh_shdr[SHBSS].sh_addralign = PAGE_SIZE;
    987 	ksyms_hdr.kh_shdr[SHBSS].sh_flags = SHF_ALLOC | SHF_EXECINSTR;
    988 	SHTCOPY(".bss");
    989 
    990 	/* Sixth section header; ".SUNW_ctf" */
    991 	ksyms_hdr.kh_shdr[SHCTF].sh_name = offs;
    992 	ksyms_hdr.kh_shdr[SHCTF].sh_type = SHT_PROGBITS;
    993 /*	ksyms_hdr.kh_shdr[SHCTF].sh_offset = filled in at open */
    994 /*	ksyms_hdr.kh_shdr[SHCTF].sh_size = filled in at open */
    995 	ksyms_hdr.kh_shdr[SHCTF].sh_link = SYMTAB; /* Corresponding symtab */
    996 	ksyms_hdr.kh_shdr[SHCTF].sh_addralign = sizeof(char);
    997 	SHTCOPY(".SUNW_ctf");
    998 }
    999 
   1000 static int
   1001 ksymsopen(dev_t dev, int oflags, int devtype, struct lwp *l)
   1002 {
   1003 	if (minor(dev) != 0 || !ksyms_loaded)
   1004 		return ENXIO;
   1005 
   1006 	/*
   1007 	 * Create a "snapshot" of the kernel symbol table.  Bumping
   1008 	 * ksyms_opencnt will prevent symbol tables from being freed.
   1009 	 */
   1010 	mutex_enter(&ksyms_lock);
   1011 	if (ksyms_opencnt++)
   1012 		goto out;
   1013 	ksyms_hdr.kh_shdr[SYMTAB].sh_size = ksyms_symsz;
   1014 	ksyms_hdr.kh_shdr[SYMTAB].sh_info = ksyms_symsz / sizeof(Elf_Sym);
   1015 	ksyms_hdr.kh_shdr[STRTAB].sh_offset = ksyms_symsz +
   1016 	    ksyms_hdr.kh_shdr[SYMTAB].sh_offset;
   1017 	ksyms_hdr.kh_shdr[STRTAB].sh_size = ksyms_strsz;
   1018 	ksyms_hdr.kh_shdr[SHCTF].sh_offset = ksyms_strsz +
   1019 	    ksyms_hdr.kh_shdr[STRTAB].sh_offset;
   1020 	ksyms_hdr.kh_shdr[SHCTF].sh_size = ksyms_ctfsz;
   1021 	ksyms_last_snapshot = TAILQ_LAST(&ksyms_symtabs, ksyms_symtab_queue);
   1022 out:	mutex_exit(&ksyms_lock);
   1023 
   1024 	return 0;
   1025 }
   1026 
   1027 static int
   1028 ksymsclose(dev_t dev, int oflags, int devtype, struct lwp *l)
   1029 {
   1030 	struct ksyms_symtab *st, *next;
   1031 	TAILQ_HEAD(, ksyms_symtab) to_free = TAILQ_HEAD_INITIALIZER(to_free);
   1032 	int s;
   1033 
   1034 	/* Discard references to symbol tables. */
   1035 	mutex_enter(&ksyms_lock);
   1036 	if (--ksyms_opencnt)
   1037 		goto out;
   1038 	ksyms_last_snapshot = NULL;
   1039 	TAILQ_FOREACH_SAFE(st, &ksyms_symtabs, sd_queue, next) {
   1040 		if (st->sd_gone) {
   1041 			/*
   1042 			 * Ensure ddb never witnesses an inconsistent
   1043 			 * state of the queue, unless memory is so
   1044 			 * corrupt that we crash in TAILQ_REMOVE.
   1045 			 */
   1046 			s = splhigh();
   1047 			TAILQ_REMOVE(&ksyms_symtabs, st, sd_queue);
   1048 			splx(s);
   1049 			TAILQ_INSERT_TAIL(&to_free, st, sd_queue);
   1050 		}
   1051 	}
   1052 	if (!TAILQ_EMPTY(&to_free))
   1053 		ksyms_sizes_calc();
   1054 out:	mutex_exit(&ksyms_lock);
   1055 
   1056 	TAILQ_FOREACH_SAFE(st, &to_free, sd_queue, next) {
   1057 		kmem_free(st->sd_nmap, st->sd_nmapsize * sizeof(uint32_t));
   1058 		kmem_free(st, sizeof(*st));
   1059 	}
   1060 
   1061 	return 0;
   1062 }
   1063 
   1064 static int
   1065 ksymsread(dev_t dev, struct uio *uio, int ioflag)
   1066 {
   1067 	struct ksyms_symtab *st;
   1068 	size_t filepos, inpos, off;
   1069 	int error;
   1070 
   1071 	/*
   1072 	 * First: Copy out the ELF header.   XXX Lose if ksymsopen()
   1073 	 * occurs during read of the header.
   1074 	 */
   1075 	off = uio->uio_offset;
   1076 	if (off < sizeof(struct ksyms_hdr)) {
   1077 		error = uiomove((char *)&ksyms_hdr + off,
   1078 		    sizeof(struct ksyms_hdr) - off, uio);
   1079 		if (error != 0)
   1080 			return error;
   1081 	}
   1082 
   1083 	/*
   1084 	 * Copy out the symbol table.
   1085 	 */
   1086 	filepos = sizeof(struct ksyms_hdr);
   1087 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
   1088 		if (__predict_false(st->sd_gone))
   1089 			continue;
   1090 		if (uio->uio_resid == 0)
   1091 			return 0;
   1092 		if (uio->uio_offset <= st->sd_symsize + filepos) {
   1093 			inpos = uio->uio_offset - filepos;
   1094 			error = uiomove((char *)st->sd_symstart + inpos,
   1095 			   st->sd_symsize - inpos, uio);
   1096 			if (error != 0)
   1097 				return error;
   1098 		}
   1099 		filepos += st->sd_symsize;
   1100 		if (st == ksyms_last_snapshot)
   1101 			break;
   1102 	}
   1103 
   1104 	/*
   1105 	 * Copy out the string table
   1106 	 */
   1107 	KASSERT(filepos == sizeof(struct ksyms_hdr) +
   1108 	    ksyms_hdr.kh_shdr[SYMTAB].sh_size);
   1109 	for (st = TAILQ_FIRST(&ksyms_symtabs);
   1110 	     ;
   1111 	     st = TAILQ_NEXT(st, sd_queue)) {
   1112 		if (uio->uio_resid == 0)
   1113 			return 0;
   1114 		if (uio->uio_offset <= st->sd_strsize + filepos) {
   1115 			inpos = uio->uio_offset - filepos;
   1116 			error = uiomove((char *)st->sd_strstart + inpos,
   1117 			   st->sd_strsize - inpos, uio);
   1118 			if (error != 0)
   1119 				return error;
   1120 		}
   1121 		filepos += st->sd_strsize;
   1122 		if (st == ksyms_last_snapshot)
   1123 			break;
   1124 	}
   1125 
   1126 	/*
   1127 	 * Copy out the CTF table.
   1128 	 */
   1129 	st = TAILQ_FIRST(&ksyms_symtabs);
   1130 	if (st->sd_ctfstart != NULL) {
   1131 		if (uio->uio_resid == 0)
   1132 			return 0;
   1133 		if (uio->uio_offset <= st->sd_ctfsize + filepos) {
   1134 			inpos = uio->uio_offset - filepos;
   1135 			error = uiomove((char *)st->sd_ctfstart + inpos,
   1136 			    st->sd_ctfsize - inpos, uio);
   1137 			if (error != 0)
   1138 				return error;
   1139 		}
   1140 		filepos += st->sd_ctfsize;
   1141 	}
   1142 
   1143 	return 0;
   1144 }
   1145 
   1146 static int
   1147 ksymswrite(dev_t dev, struct uio *uio, int ioflag)
   1148 {
   1149 	return EROFS;
   1150 }
   1151 
   1152 __CTASSERT(offsetof(struct ksyms_ogsymbol, kg_name) == offsetof(struct ksyms_gsymbol, kg_name));
   1153 __CTASSERT(offsetof(struct ksyms_gvalue, kv_name) == offsetof(struct ksyms_gsymbol, kg_name));
   1154 
   1155 static int
   1156 ksymsioctl(dev_t dev, u_long cmd, void *data, int fflag, struct lwp *l)
   1157 {
   1158 	struct ksyms_ogsymbol *okg = (struct ksyms_ogsymbol *)data;
   1159 	struct ksyms_gsymbol *kg = (struct ksyms_gsymbol *)data;
   1160 	struct ksyms_gvalue *kv = (struct ksyms_gvalue *)data;
   1161 	struct ksyms_symtab *st;
   1162 	Elf_Sym *sym = NULL, copy;
   1163 	unsigned long val;
   1164 	int error = 0;
   1165 	char *str = NULL;
   1166 	int len;
   1167 
   1168 	/* Read ksyms_maxlen only once while not holding the lock. */
   1169 	len = ksyms_maxlen;
   1170 
   1171 	if (cmd == OKIOCGVALUE || cmd == OKIOCGSYMBOL ||
   1172 	    cmd == KIOCGVALUE || cmd == KIOCGSYMBOL) {
   1173 		str = kmem_alloc(len, KM_SLEEP);
   1174 		if ((error = copyinstr(kg->kg_name, str, len, NULL)) != 0) {
   1175 			kmem_free(str, len);
   1176 			return error;
   1177 		}
   1178 	}
   1179 
   1180 	switch (cmd) {
   1181 	case OKIOCGVALUE:
   1182 		/*
   1183 		 * Use the in-kernel symbol lookup code for fast
   1184 		 * retreival of a value.
   1185 		 */
   1186 		error = ksyms_getval(NULL, str, &val, KSYMS_EXTERN);
   1187 		if (error == 0)
   1188 			error = copyout(&val, okg->kg_value, sizeof(long));
   1189 		kmem_free(str, len);
   1190 		break;
   1191 
   1192 	case OKIOCGSYMBOL:
   1193 		/*
   1194 		 * Use the in-kernel symbol lookup code for fast
   1195 		 * retreival of a symbol.
   1196 		 */
   1197 		mutex_enter(&ksyms_lock);
   1198 		TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
   1199 			if (st->sd_gone)
   1200 				continue;
   1201 			if ((sym = findsym(str, st, KSYMS_ANY)) == NULL)
   1202 				continue;
   1203 #ifdef notdef
   1204 			/* Skip if bad binding */
   1205 			if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL) {
   1206 				sym = NULL;
   1207 				continue;
   1208 			}
   1209 #endif
   1210 			break;
   1211 		}
   1212 		if (sym != NULL) {
   1213 			memcpy(&copy, sym, sizeof(copy));
   1214 			mutex_exit(&ksyms_lock);
   1215 			error = copyout(&copy, okg->kg_sym, sizeof(Elf_Sym));
   1216 		} else {
   1217 			mutex_exit(&ksyms_lock);
   1218 			error = ENOENT;
   1219 		}
   1220 		kmem_free(str, len);
   1221 		break;
   1222 
   1223 	case KIOCGVALUE:
   1224 		/*
   1225 		 * Use the in-kernel symbol lookup code for fast
   1226 		 * retreival of a value.
   1227 		 */
   1228 		error = ksyms_getval(NULL, str, &val, KSYMS_EXTERN);
   1229 		if (error == 0)
   1230 			kv->kv_value = val;
   1231 		kmem_free(str, len);
   1232 		break;
   1233 
   1234 	case KIOCGSYMBOL:
   1235 		/*
   1236 		 * Use the in-kernel symbol lookup code for fast
   1237 		 * retreival of a symbol.
   1238 		 */
   1239 		mutex_enter(&ksyms_lock);
   1240 		TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
   1241 			if (st->sd_gone)
   1242 				continue;
   1243 			if ((sym = findsym(str, st, KSYMS_ANY)) == NULL)
   1244 				continue;
   1245 #ifdef notdef
   1246 			/* Skip if bad binding */
   1247 			if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL) {
   1248 				sym = NULL;
   1249 				continue;
   1250 			}
   1251 #endif
   1252 			break;
   1253 		}
   1254 		if (sym != NULL) {
   1255 			kg->kg_sym = *sym;
   1256 		} else {
   1257 			error = ENOENT;
   1258 		}
   1259 		mutex_exit(&ksyms_lock);
   1260 		kmem_free(str, len);
   1261 		break;
   1262 
   1263 	case KIOCGSIZE:
   1264 		/*
   1265 		 * Get total size of symbol table.
   1266 		 */
   1267 		mutex_enter(&ksyms_lock);
   1268 		*(int *)data = ksyms_strsz + ksyms_symsz +
   1269 		    sizeof(struct ksyms_hdr);
   1270 		mutex_exit(&ksyms_lock);
   1271 		break;
   1272 
   1273 	default:
   1274 		error = ENOTTY;
   1275 		break;
   1276 	}
   1277 
   1278 	return error;
   1279 }
   1280 
   1281 const struct cdevsw ksyms_cdevsw = {
   1282 	.d_open = ksymsopen,
   1283 	.d_close = ksymsclose,
   1284 	.d_read = ksymsread,
   1285 	.d_write = ksymswrite,
   1286 	.d_ioctl = ksymsioctl,
   1287 	.d_stop = nullstop,
   1288 	.d_tty = notty,
   1289 	.d_poll = nopoll,
   1290 	.d_mmap = nommap,
   1291 	.d_kqfilter = nullkqfilter,
   1292 	.d_discard = nodiscard,
   1293 	.d_flag = D_OTHER | D_MPSAFE
   1294 };
   1295