Home | History | Annotate | Line # | Download | only in kern
kern_ksyms.c revision 1.35.6.3
      1 /*	$NetBSD: kern_ksyms.c,v 1.35.6.3 2009/01/17 13:29:18 mjf 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.35.6.3 2009/01/17 13:29:18 mjf Exp $");
     75 
     76 #if defined(_KERNEL) && defined(_KERNEL_OPT)
     77 #include "opt_ddb.h"
     78 #include "opt_ddbparam.h"	/* for SYMTAB_SPACE */
     79 #endif
     80 
     81 #define _KSYMS_PRIVATE
     82 
     83 #include <sys/param.h>
     84 #include <sys/queue.h>
     85 #include <sys/exec.h>
     86 #include <sys/systm.h>
     87 #include <sys/conf.h>
     88 #include <sys/kmem.h>
     89 #include <sys/proc.h>
     90 #include <sys/atomic.h>
     91 #include <sys/ksyms.h>
     92 
     93 #include <uvm/uvm_extern.h>
     94 
     95 #ifdef DDB
     96 #include <ddb/db_output.h>
     97 #endif
     98 
     99 #include "ksyms.h"
    100 
    101 static int ksyms_maxlen;
    102 static bool ksyms_isopen;
    103 static bool ksyms_initted;
    104 static struct ksyms_hdr ksyms_hdr;
    105 static kmutex_t ksyms_lock;
    106 
    107 void ksymsattach(int);
    108 static void ksyms_hdr_init(void *);
    109 static void ksyms_sizes_calc(void);
    110 
    111 #ifdef KSYMS_DEBUG
    112 #define	FOLLOW_CALLS		1
    113 #define	FOLLOW_MORE_CALLS	2
    114 #define	FOLLOW_DEVKSYMS		4
    115 static int ksyms_debug;
    116 #endif
    117 
    118 #ifdef SYMTAB_SPACE
    119 #define		SYMTAB_FILLER	"|This is the symbol table!"
    120 
    121 char		db_symtab[SYMTAB_SPACE] = SYMTAB_FILLER;
    122 int		db_symtabsize = SYMTAB_SPACE;
    123 #endif
    124 
    125 int ksyms_symsz;
    126 int ksyms_strsz;
    127 TAILQ_HEAD(, ksyms_symtab) ksyms_symtabs =
    128     TAILQ_HEAD_INITIALIZER(ksyms_symtabs);
    129 static struct ksyms_symtab kernel_symtab;
    130 
    131 static int
    132 ksyms_verify(void *symstart, void *strstart)
    133 {
    134 #if defined(DIAGNOSTIC) || defined(DEBUG)
    135 	if (symstart == NULL)
    136 		printf("ksyms: Symbol table not found\n");
    137 	if (strstart == NULL)
    138 		printf("ksyms: String table not found\n");
    139 	if (symstart == NULL || strstart == NULL)
    140 		printf("ksyms: Perhaps the kernel is stripped?\n");
    141 #endif
    142 	if (symstart == NULL || strstart == NULL)
    143 		return 0;
    144 	KASSERT(symstart <= strstart);
    145 	return 1;
    146 }
    147 
    148 /*
    149  * Finds a certain symbol name in a certain symbol table.
    150  */
    151 static Elf_Sym *
    152 findsym(const char *name, struct ksyms_symtab *table, int type)
    153 {
    154 	Elf_Sym *sym, *maxsym;
    155 	int low, mid, high, nglob;
    156 	char *str, *cmp;
    157 
    158 	sym = table->sd_symstart;
    159 	str = table->sd_strstart - table->sd_usroffset;
    160 	nglob = table->sd_nglob;
    161 	low = 0;
    162 	high = nglob;
    163 
    164 	/*
    165 	 * Start with a binary search of all global symbols in this table.
    166 	 * Global symbols must have unique names.
    167 	 */
    168 	while (low < high) {
    169 		mid = (low + high) >> 1;
    170 		cmp = sym[mid].st_name + str;
    171 		if (cmp[0] < name[0] || strcmp(cmp, name) < 0) {
    172 			low = mid + 1;
    173 		} else {
    174 			high = mid;
    175 		}
    176 	}
    177 	KASSERT(low == high);
    178 	if (__predict_true(low < nglob &&
    179 	    strcmp(sym[low].st_name + str, name) == 0)) {
    180 		KASSERT(ELF_ST_BIND(sym[low].st_info) == STB_GLOBAL);
    181 		return &sym[low];
    182 	}
    183 
    184 	/*
    185 	 * Perform a linear search of local symbols (rare).  Many local
    186 	 * symbols with the same name can exist so are not included in
    187 	 * the binary search.
    188 	 */
    189 	if (type != KSYMS_EXTERN) {
    190 		maxsym = sym + table->sd_symsize / sizeof(Elf_Sym);
    191 		for (sym += nglob; sym < maxsym; sym++) {
    192 			if (strcmp(name, sym->st_name + str) == 0) {
    193 				return sym;
    194 			}
    195 		}
    196 	}
    197 	return NULL;
    198 }
    199 
    200 /*
    201  * The "attach" is in reality done in ksyms_init().
    202  */
    203 void
    204 ksymsattach(int arg)
    205 {
    206 	int maj = cdevsw_lookup_major(&ksyms_cdevsw);
    207 
    208 	device_register_name(makedev(maj, 0), NULL, true, DEV_OTHER, "ksyms");
    209 }
    210 
    211 void
    212 ksyms_init()
    213 {
    214 
    215 	mutex_init(&ksyms_lock, MUTEX_DEFAULT, IPL_NONE);
    216 }
    217 
    218 /*
    219  * Add a symbol table.
    220  * This is intended for use when the symbol table and its corresponding
    221  * string table are easily available.  If they are embedded in an ELF
    222  * image, use addsymtab_elf() instead.
    223  *
    224  * name - Symbol's table name.
    225  * symstart, symsize - Address and size of the symbol table.
    226  * strstart, strsize - Address and size of the string table.
    227  * tab - Symbol table to be updated with this information.
    228  * newstart - Address to which the symbol table has to be copied during
    229  *            shrinking.  If NULL, it is not moved.
    230  */
    231 static const char *addsymtab_strstart;
    232 
    233 static int
    234 addsymtab_compar(const void *a, const void *b)
    235 {
    236 	const Elf_Sym *sa, *sb;
    237 
    238 	sa = a;
    239 	sb = b;
    240 
    241 	/*
    242 	 * Split the symbol table into two, with globals at the start
    243 	 * and locals at the end.
    244 	 */
    245 	if (ELF_ST_BIND(sa->st_info) != ELF_ST_BIND(sb->st_info)) {
    246 		if (ELF_ST_BIND(sa->st_info) == STB_GLOBAL) {
    247 			return -1;
    248 		}
    249 		if (ELF_ST_BIND(sb->st_info) == STB_GLOBAL) {
    250 			return 1;
    251 		}
    252 	}
    253 
    254 	/* Within each band, sort by name. */
    255 	return strcmp(sa->st_name + addsymtab_strstart,
    256 	    sb->st_name + addsymtab_strstart);
    257 }
    258 
    259 static void
    260 addsymtab(const char *name, void *symstart, size_t symsize,
    261 	  void *strstart, size_t strsize, struct ksyms_symtab *tab,
    262 	  void *newstart)
    263 {
    264 	Elf_Sym *sym, *nsym, ts;
    265 	int i, j, n, nglob;
    266 	char *str;
    267 
    268 	tab->sd_symstart = symstart;
    269 	tab->sd_symsize = symsize;
    270 	tab->sd_strstart = strstart;
    271 	tab->sd_strsize = strsize;
    272 	tab->sd_name = name;
    273 	tab->sd_minsym = UINTPTR_MAX;
    274 	tab->sd_maxsym = 0;
    275 	tab->sd_usroffset = 0;
    276 	tab->sd_gone = false;
    277 #ifdef KSYMS_DEBUG
    278 	printf("newstart %p sym %p ksyms_symsz %d str %p strsz %d send %p\n",
    279 	    newstart, symstart, symsize, strstart, strsize,
    280 	    tab->sd_strstart + tab->sd_strsize);
    281 #endif
    282 
    283 	/* Pack symbol table by removing all file name references. */
    284 	sym = tab->sd_symstart;
    285 	nsym = (Elf_Sym *)newstart;
    286 	str = tab->sd_strstart;
    287 	nglob = 0;
    288 	for (i = n = 0; i < tab->sd_symsize/sizeof(Elf_Sym); i++) {
    289 		/*
    290 		 * Remove useless symbols.
    291 		 * Should actually remove all typeless symbols.
    292 		 */
    293 		if (sym[i].st_name == 0)
    294 			continue; /* Skip nameless entries */
    295 		if (sym[i].st_shndx == SHN_UNDEF)
    296 			continue; /* Skip external references */
    297 		if (ELF_ST_TYPE(sym[i].st_info) == STT_FILE)
    298 			continue; /* Skip filenames */
    299 		if (ELF_ST_TYPE(sym[i].st_info) == STT_NOTYPE &&
    300 		    sym[i].st_value == 0 &&
    301 		    strcmp(str + sym[i].st_name, "*ABS*") == 0)
    302 			continue; /* XXX */
    303 		if (ELF_ST_TYPE(sym[i].st_info) == STT_NOTYPE &&
    304 		    strcmp(str + sym[i].st_name, "gcc2_compiled.") == 0)
    305 			continue; /* XXX */
    306 
    307 		/* Save symbol. Set it as an absolute offset */
    308 		nsym[n] = sym[i];
    309 		nsym[n].st_shndx = SHBSS;
    310 		j = strlen(nsym[n].st_name + str) + 1;
    311 		if (j > ksyms_maxlen)
    312 			ksyms_maxlen = j;
    313 		nglob += (ELF_ST_BIND(nsym[n].st_info) == STB_GLOBAL);
    314 
    315 		/* Compute min and max symbols. */
    316 		if (nsym[n].st_value < tab->sd_minsym) {
    317 		    	tab->sd_minsym = nsym[n].st_value;
    318 		}
    319 		if (nsym[n].st_value > tab->sd_maxsym) {
    320 		    	tab->sd_maxsym = nsym[n].st_value;
    321 		}
    322 		n++;
    323 	}
    324 
    325 	/* Fill the rest of the record, and sort the symbols. */
    326 	tab->sd_symstart = nsym;
    327 	tab->sd_symsize = n * sizeof(Elf_Sym);
    328 	tab->sd_nglob = nglob;
    329 	addsymtab_strstart = str;
    330 	if (kheapsort(nsym, n, sizeof(Elf_Sym), addsymtab_compar, &ts) != 0)
    331 		panic("addsymtab");
    332 
    333 	/* ksymsread() is unlocked, so membar. */
    334 	membar_producer();
    335 	TAILQ_INSERT_TAIL(&ksyms_symtabs, tab, sd_queue);
    336 	ksyms_sizes_calc();
    337 	ksyms_initted = true;
    338 }
    339 
    340 /*
    341  * Setup the kernel symbol table stuff.
    342  */
    343 void
    344 ksyms_addsyms_elf(int symsize, void *start, void *end)
    345 {
    346 	int i, j;
    347 	Elf_Shdr *shdr;
    348 	char *symstart = NULL, *strstart = NULL;
    349 	size_t strsize = 0;
    350 	Elf_Ehdr *ehdr;
    351 
    352 #ifdef SYMTAB_SPACE
    353 	if (symsize <= 0 &&
    354 	    strncmp(db_symtab, SYMTAB_FILLER, sizeof(SYMTAB_FILLER))) {
    355 		symsize = db_symtabsize;
    356 		start = db_symtab;
    357 		end = db_symtab + db_symtabsize;
    358 	}
    359 #endif
    360 	if (symsize <= 0) {
    361 		printf("[ Kernel symbol table missing! ]\n");
    362 		return;
    363 	}
    364 
    365 	/* Sanity check */
    366 	if (ALIGNED_POINTER(start, long) == 0) {
    367 		printf("[ Kernel symbol table has bad start address %p ]\n",
    368 		    start);
    369 		return;
    370 	}
    371 
    372 	ehdr = (Elf_Ehdr *)start;
    373 
    374 	/* check if this is a valid ELF header */
    375 	/* No reason to verify arch type, the kernel is actually running! */
    376 	if (memcmp(ehdr->e_ident, ELFMAG, SELFMAG) ||
    377 	    ehdr->e_ident[EI_CLASS] != ELFCLASS ||
    378 	    ehdr->e_version > 1) {
    379 		printf("[ Kernel symbol table invalid! ]\n");
    380 		return; /* nothing to do */
    381 	}
    382 
    383 	/* Loaded header will be scratched in addsymtab */
    384 	ksyms_hdr_init(start);
    385 
    386 	/* Find the symbol table and the corresponding string table. */
    387 	shdr = (Elf_Shdr *)((uint8_t *)start + ehdr->e_shoff);
    388 	for (i = 1; i < ehdr->e_shnum; i++) {
    389 		if (shdr[i].sh_type != SHT_SYMTAB)
    390 			continue;
    391 		if (shdr[i].sh_offset == 0)
    392 			continue;
    393 		symstart = (uint8_t *)start + shdr[i].sh_offset;
    394 		symsize = shdr[i].sh_size;
    395 		j = shdr[i].sh_link;
    396 		if (shdr[j].sh_offset == 0)
    397 			continue; /* Can this happen? */
    398 		strstart = (uint8_t *)start + shdr[j].sh_offset;
    399 		strsize = shdr[j].sh_size;
    400 		break;
    401 	}
    402 
    403 	if (!ksyms_verify(symstart, strstart))
    404 		return;
    405 	addsymtab("netbsd", symstart, symsize, strstart, strsize,
    406 	    &kernel_symtab, start);
    407 
    408 #ifdef DEBUG
    409 	printf("Loaded initial symtab at %p, strtab at %p, # entries %ld\n",
    410 	    kernel_symtab.sd_symstart, kernel_symtab.sd_strstart,
    411 	    (long)kernel_symtab.sd_symsize/sizeof(Elf_Sym));
    412 #endif
    413 }
    414 
    415 /*
    416  * Setup the kernel symbol table stuff.
    417  * Use this when the address of the symbol and string tables are known;
    418  * otherwise use ksyms_init with an ELF image.
    419  * We need to pass a minimal ELF header which will later be completed by
    420  * ksyms_hdr_init and handed off to userland through /dev/ksyms.  We use
    421  * a void *rather than a pointer to avoid exposing the Elf_Ehdr type.
    422  */
    423 void
    424 ksyms_addsyms_explicit(void *ehdr, void *symstart, size_t symsize,
    425 		    void *strstart, size_t strsize)
    426 {
    427 
    428 	if (!ksyms_verify(symstart, strstart))
    429 		return;
    430 
    431 	ksyms_hdr_init(ehdr);
    432 	addsymtab("netbsd", symstart, symsize, strstart, strsize,
    433 	    &kernel_symtab, symstart);
    434 }
    435 
    436 /*
    437  * Get the value associated with a symbol.
    438  * "mod" is the module name, or null if any module.
    439  * "sym" is the symbol name.
    440  * "val" is a pointer to the corresponding value, if call succeeded.
    441  * Returns 0 if success or ENOENT if no such entry.
    442  *
    443  * Call with ksyms_lock, unless known that the symbol table can't change.
    444  */
    445 int
    446 ksyms_getval_unlocked(const char *mod, const char *sym, unsigned long *val,
    447 		      int type)
    448 {
    449 	struct ksyms_symtab *st;
    450 	Elf_Sym *es;
    451 
    452 #ifdef KSYMS_DEBUG
    453 	if (ksyms_debug & FOLLOW_CALLS)
    454 		printf("ksyms_getval_unlocked: mod %s sym %s valp %p\n",
    455 		    mod, sym, val);
    456 #endif
    457 
    458 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    459 		if (__predict_false(st->sd_gone))
    460 			continue;
    461 		if (mod != NULL && strcmp(st->sd_name, mod))
    462 			continue;
    463 		if ((es = findsym(sym, st, type)) != NULL) {
    464 			*val = es->st_value;
    465 			return 0;
    466 		}
    467 	}
    468 	return ENOENT;
    469 }
    470 
    471 int
    472 ksyms_getval(const char *mod, const char *sym, unsigned long *val, int type)
    473 {
    474 	int rc;
    475 
    476 	if (!ksyms_initted)
    477 		return ENOENT;
    478 
    479 	mutex_enter(&ksyms_lock);
    480 	rc = ksyms_getval_unlocked(mod, sym, val, type);
    481 	mutex_exit(&ksyms_lock);
    482 	return rc;
    483 }
    484 
    485 /*
    486  * Get "mod" and "symbol" associated with an address.
    487  * Returns 0 if success or ENOENT if no such entry.
    488  *
    489  * Call with ksyms_lock, unless known that the symbol table can't change.
    490  */
    491 int
    492 ksyms_getname(const char **mod, const char **sym, vaddr_t v, int f)
    493 {
    494 	struct ksyms_symtab *st;
    495 	Elf_Sym *les, *es = NULL;
    496 	vaddr_t laddr = 0;
    497 	const char *lmod = NULL;
    498 	char *stable = NULL;
    499 	int type, i, sz;
    500 
    501 	if (!ksyms_initted)
    502 		return ENOENT;
    503 
    504 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    505 		if (st->sd_gone)
    506 			continue;
    507 		if (v < st->sd_minsym || v > st->sd_maxsym)
    508 			continue;
    509 		sz = st->sd_symsize/sizeof(Elf_Sym);
    510 		for (i = 0; i < sz; i++) {
    511 			les = st->sd_symstart + i;
    512 			type = ELF_ST_TYPE(les->st_info);
    513 
    514 			if ((f & KSYMS_PROC) && (type != STT_FUNC))
    515 				continue;
    516 
    517 			if (type == STT_NOTYPE)
    518 				continue;
    519 
    520 			if (((f & KSYMS_ANY) == 0) &&
    521 			    (type != STT_FUNC) && (type != STT_OBJECT))
    522 				continue;
    523 
    524 			if ((les->st_value <= v) && (les->st_value > laddr)) {
    525 				laddr = les->st_value;
    526 				es = les;
    527 				lmod = st->sd_name;
    528 				stable = st->sd_strstart - st->sd_usroffset;
    529 			}
    530 		}
    531 	}
    532 	if (es == NULL)
    533 		return ENOENT;
    534 	if ((f & KSYMS_EXACT) && (v != es->st_value))
    535 		return ENOENT;
    536 	if (mod)
    537 		*mod = lmod;
    538 	if (sym)
    539 		*sym = stable + es->st_name;
    540 	return 0;
    541 }
    542 
    543 /*
    544  * Add a symbol table from a loadable module.
    545  */
    546 void
    547 ksyms_modload(const char *name, void *symstart, vsize_t symsize,
    548 	      char *strstart, vsize_t strsize)
    549 {
    550 	struct ksyms_symtab *st;
    551 
    552 	st = kmem_zalloc(sizeof(*st), KM_SLEEP);
    553 	mutex_enter(&ksyms_lock);
    554 	addsymtab(name, symstart, symsize, strstart, strsize, st, symstart);
    555 	mutex_exit(&ksyms_lock);
    556 }
    557 
    558 /*
    559  * Remove a symbol table from a loadable module.
    560  */
    561 void
    562 ksyms_modunload(const char *name)
    563 {
    564 	struct ksyms_symtab *st;
    565 
    566 	mutex_enter(&ksyms_lock);
    567 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    568 		if (st->sd_gone)
    569 			continue;
    570 		if (strcmp(name, st->sd_name) != 0)
    571 			continue;
    572 		st->sd_gone = true;
    573 		if (!ksyms_isopen) {
    574 			TAILQ_REMOVE(&ksyms_symtabs, st, sd_queue);
    575 			ksyms_sizes_calc();
    576 			kmem_free(st, sizeof(*st));
    577 		}
    578 		break;
    579 	}
    580 	mutex_exit(&ksyms_lock);
    581 	KASSERT(st != NULL);
    582 }
    583 
    584 #ifdef DDB
    585 /*
    586  * Keep sifting stuff here, to avoid export of ksyms internals.
    587  *
    588  * Systems is expected to be quiescent, so no locking done.
    589  */
    590 int
    591 ksyms_sift(char *mod, char *sym, int mode)
    592 {
    593 	struct ksyms_symtab *st;
    594 	char *sb;
    595 	int i, sz;
    596 
    597 	if (!ksyms_initted)
    598 		return ENOENT;
    599 
    600 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    601 		if (st->sd_gone)
    602 			continue;
    603 		if (mod && strcmp(mod, st->sd_name))
    604 			continue;
    605 		sb = st->sd_strstart - st->sd_usroffset;
    606 
    607 		sz = st->sd_symsize/sizeof(Elf_Sym);
    608 		for (i = 0; i < sz; i++) {
    609 			Elf_Sym *les = st->sd_symstart + i;
    610 			char c;
    611 
    612 			if (strstr(sb + les->st_name, sym) == NULL)
    613 				continue;
    614 
    615 			if (mode == 'F') {
    616 				switch (ELF_ST_TYPE(les->st_info)) {
    617 				case STT_OBJECT:
    618 					c = '+';
    619 					break;
    620 				case STT_FUNC:
    621 					c = '*';
    622 					break;
    623 				case STT_SECTION:
    624 					c = '&';
    625 					break;
    626 				case STT_FILE:
    627 					c = '/';
    628 					break;
    629 				default:
    630 					c = ' ';
    631 					break;
    632 				}
    633 				db_printf("%s%c ", sb + les->st_name, c);
    634 			} else
    635 				db_printf("%s ", sb + les->st_name);
    636 		}
    637 	}
    638 	return ENOENT;
    639 }
    640 #endif /* DDB */
    641 
    642 /*
    643  * In case we exposing the symbol table to the userland using the pseudo-
    644  * device /dev/ksyms, it is easier to provide all the tables as one.
    645  * However, it means we have to change all the st_name fields for the
    646  * symbols so they match the ELF image that the userland will read
    647  * through the device.
    648  *
    649  * The actual (correct) value of st_name is preserved through a global
    650  * offset stored in the symbol table structure.
    651  *
    652  * Call with ksyms_lock held.
    653  */
    654 static void
    655 ksyms_sizes_calc(void)
    656 {
    657         struct ksyms_symtab *st;
    658 	int i, delta;
    659 
    660         ksyms_symsz = ksyms_strsz = 0;
    661         TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    662 		delta = ksyms_strsz - st->sd_usroffset;
    663 		if (delta != 0) {
    664 			for (i = 0; i < st->sd_symsize/sizeof(Elf_Sym); i++)
    665 				st->sd_symstart[i].st_name += delta;
    666 			st->sd_usroffset = ksyms_strsz;
    667 		}
    668                 ksyms_symsz += st->sd_symsize;
    669                 ksyms_strsz += st->sd_strsize;
    670         }
    671 }
    672 
    673 static void
    674 ksyms_hdr_init(void *hdraddr)
    675 {
    676 
    677 	/* Copy the loaded elf exec header */
    678 	memcpy(&ksyms_hdr.kh_ehdr, hdraddr, sizeof(Elf_Ehdr));
    679 
    680 	/* Set correct program/section header sizes, offsets and numbers */
    681 	ksyms_hdr.kh_ehdr.e_phoff = offsetof(struct ksyms_hdr, kh_phdr[0]);
    682 	ksyms_hdr.kh_ehdr.e_phentsize = sizeof(Elf_Phdr);
    683 	ksyms_hdr.kh_ehdr.e_phnum = NPRGHDR;
    684 	ksyms_hdr.kh_ehdr.e_shoff = offsetof(struct ksyms_hdr, kh_shdr[0]);
    685 	ksyms_hdr.kh_ehdr.e_shentsize = sizeof(Elf_Shdr);
    686 	ksyms_hdr.kh_ehdr.e_shnum = NSECHDR;
    687 	ksyms_hdr.kh_ehdr.e_shstrndx = SHSTRTAB;
    688 
    689 	/* Text/data - fake */
    690 	ksyms_hdr.kh_phdr[0].p_type = PT_LOAD;
    691 	ksyms_hdr.kh_phdr[0].p_memsz = (unsigned long)-1L;
    692 	ksyms_hdr.kh_phdr[0].p_flags = PF_R | PF_X | PF_W;
    693 
    694 	/* First section is null */
    695 
    696 	/* Second section header; ".symtab" */
    697 	ksyms_hdr.kh_shdr[SYMTAB].sh_name = 1; /* Section 3 offset */
    698 	ksyms_hdr.kh_shdr[SYMTAB].sh_type = SHT_SYMTAB;
    699 	ksyms_hdr.kh_shdr[SYMTAB].sh_offset = sizeof(struct ksyms_hdr);
    700 /*	ksyms_hdr.kh_shdr[SYMTAB].sh_size = filled in at open */
    701 	ksyms_hdr.kh_shdr[SYMTAB].sh_link = 2; /* Corresponding strtab */
    702 	ksyms_hdr.kh_shdr[SYMTAB].sh_addralign = sizeof(long);
    703 	ksyms_hdr.kh_shdr[SYMTAB].sh_entsize = sizeof(Elf_Sym);
    704 
    705 	/* Third section header; ".strtab" */
    706 	ksyms_hdr.kh_shdr[STRTAB].sh_name = 9; /* Section 3 offset */
    707 	ksyms_hdr.kh_shdr[STRTAB].sh_type = SHT_STRTAB;
    708 /*	ksyms_hdr.kh_shdr[STRTAB].sh_offset = filled in at open */
    709 /*	ksyms_hdr.kh_shdr[STRTAB].sh_size = filled in at open */
    710 	ksyms_hdr.kh_shdr[STRTAB].sh_addralign = sizeof(char);
    711 
    712 	/* Fourth section, ".shstrtab" */
    713 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_name = 17; /* This section name offset */
    714 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_type = SHT_STRTAB;
    715 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_offset =
    716 	    offsetof(struct ksyms_hdr, kh_strtab);
    717 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_size = SHSTRSIZ;
    718 	ksyms_hdr.kh_shdr[SHSTRTAB].sh_addralign = sizeof(char);
    719 
    720 	/* Fifth section, ".bss". All symbols reside here. */
    721 	ksyms_hdr.kh_shdr[SHBSS].sh_name = 27; /* This section name offset */
    722 	ksyms_hdr.kh_shdr[SHBSS].sh_type = SHT_NOBITS;
    723 	ksyms_hdr.kh_shdr[SHBSS].sh_offset = 0;
    724 	ksyms_hdr.kh_shdr[SHBSS].sh_size = (unsigned long)-1L;
    725 	ksyms_hdr.kh_shdr[SHBSS].sh_addralign = PAGE_SIZE;
    726 	ksyms_hdr.kh_shdr[SHBSS].sh_flags = SHF_ALLOC | SHF_EXECINSTR;
    727 
    728 	/* Set section names */
    729 	strlcpy(&ksyms_hdr.kh_strtab[1], ".symtab",
    730 	    sizeof(ksyms_hdr.kh_strtab) - 1);
    731 	strlcpy(&ksyms_hdr.kh_strtab[9], ".strtab",
    732 	    sizeof(ksyms_hdr.kh_strtab) - 9);
    733 	strlcpy(&ksyms_hdr.kh_strtab[17], ".shstrtab",
    734 	    sizeof(ksyms_hdr.kh_strtab) - 17);
    735 	strlcpy(&ksyms_hdr.kh_strtab[27], ".bss",
    736 	    sizeof(ksyms_hdr.kh_strtab) - 27);
    737 }
    738 
    739 static int
    740 ksymsopen(dev_t dev, int oflags, int devtype, struct lwp *l)
    741 {
    742 
    743 	if (minor(dev) != 0 || !ksyms_initted)
    744 		return ENXIO;
    745 
    746 	/*
    747 	 * Create a "snapshot" of the kernel symbol table.  Setting
    748 	 * ksyms_isopen will prevent symbol tables from being freed.
    749 	 */
    750 	mutex_enter(&ksyms_lock);
    751 	ksyms_hdr.kh_shdr[SYMTAB].sh_size = ksyms_symsz;
    752 	ksyms_hdr.kh_shdr[SYMTAB].sh_info = ksyms_symsz / sizeof(Elf_Sym);
    753 	ksyms_hdr.kh_shdr[STRTAB].sh_offset = ksyms_symsz +
    754 	    ksyms_hdr.kh_shdr[SYMTAB].sh_offset;
    755 	ksyms_hdr.kh_shdr[STRTAB].sh_size = ksyms_strsz;
    756 	ksyms_isopen = true;
    757 	mutex_exit(&ksyms_lock);
    758 
    759 	return 0;
    760 }
    761 
    762 static int
    763 ksymsclose(dev_t dev, int oflags, int devtype, struct lwp *l)
    764 {
    765 	struct ksyms_symtab *st, *next;
    766 	bool resize;
    767 
    768 	/* Discard refernces to symbol tables. */
    769 	mutex_enter(&ksyms_lock);
    770 	ksyms_isopen = false;
    771 	resize = false;
    772 	for (st = TAILQ_FIRST(&ksyms_symtabs); st != NULL; st = next) {
    773 		next = TAILQ_NEXT(st, sd_queue);
    774 		if (st->sd_gone) {
    775 			TAILQ_REMOVE(&ksyms_symtabs, st, sd_queue);
    776 			kmem_free(st, sizeof(*st));
    777 			resize = true;
    778 		}
    779 	}
    780 	if (resize)
    781 		ksyms_sizes_calc();
    782 	mutex_exit(&ksyms_lock);
    783 
    784 	return 0;
    785 }
    786 
    787 static int
    788 ksymsread(dev_t dev, struct uio *uio, int ioflag)
    789 {
    790 	struct ksyms_symtab *st;
    791 	size_t filepos, inpos, off;
    792 	int error;
    793 
    794 	/*
    795 	 * First: Copy out the ELF header.   XXX Lose if ksymsopen()
    796 	 * occurs during read of the header.
    797 	 */
    798 	off = uio->uio_offset;
    799 	if (off < sizeof(struct ksyms_hdr)) {
    800 		error = uiomove((char *)&ksyms_hdr + off,
    801 		    sizeof(struct ksyms_hdr) - off, uio);
    802 		if (error != 0)
    803 			return error;
    804 	}
    805 
    806 	/*
    807 	 * Copy out the symbol table.
    808 	 */
    809 	filepos = sizeof(struct ksyms_hdr);
    810 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    811 		if (uio->uio_resid == 0)
    812 			return 0;
    813 		if (uio->uio_offset <= st->sd_symsize + filepos) {
    814 			inpos = uio->uio_offset - filepos;
    815 			error = uiomove((char *)st->sd_symstart + inpos,
    816 			   st->sd_symsize - inpos, uio);
    817 			if (error != 0)
    818 				return error;
    819 		}
    820 		filepos += st->sd_symsize;
    821 	}
    822 
    823 	/*
    824 	 * Copy out the string table
    825 	 */
    826 	KASSERT(filepos == sizeof(struct ksyms_hdr) +
    827 	    ksyms_hdr.kh_shdr[SYMTAB].sh_size);
    828 	TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    829 		if (uio->uio_resid == 0)
    830 			return 0;
    831 		if (uio->uio_offset <= st->sd_strsize + filepos) {
    832 			inpos = uio->uio_offset - filepos;
    833 			error = uiomove((char *)st->sd_strstart + inpos,
    834 			   st->sd_strsize - inpos, uio);
    835 			if (error != 0)
    836 				return error;
    837 		}
    838 		filepos += st->sd_strsize;
    839 	}
    840 
    841 	return 0;
    842 }
    843 
    844 static int
    845 ksymswrite(dev_t dev, struct uio *uio, int ioflag)
    846 {
    847 
    848 	return EROFS;
    849 }
    850 
    851 static int
    852 ksymsioctl(dev_t dev, u_long cmd, void *data, int fflag, struct lwp *l)
    853 {
    854 	struct ksyms_gsymbol *kg = (struct ksyms_gsymbol *)data;
    855 	struct ksyms_symtab *st;
    856 	Elf_Sym *sym = NULL, copy;
    857 	unsigned long val;
    858 	int error = 0;
    859 	char *str = NULL;
    860 	int len;
    861 
    862 	/* Read ksyms_maxlen only once while not holding the lock. */
    863 	len = ksyms_maxlen;
    864 
    865 	if (cmd == KIOCGVALUE || cmd == KIOCGSYMBOL) {
    866 		str = kmem_alloc(len, KM_SLEEP);
    867 		if ((error = copyinstr(kg->kg_name, str, len, NULL)) != 0) {
    868 			kmem_free(str, len);
    869 			return error;
    870 		}
    871 	}
    872 
    873 	switch (cmd) {
    874 	case KIOCGVALUE:
    875 		/*
    876 		 * Use the in-kernel symbol lookup code for fast
    877 		 * retreival of a value.
    878 		 */
    879 		error = ksyms_getval(NULL, str, &val, KSYMS_EXTERN);
    880 		if (error == 0)
    881 			error = copyout(&val, kg->kg_value, sizeof(long));
    882 		kmem_free(str, len);
    883 		break;
    884 
    885 	case KIOCGSYMBOL:
    886 		/*
    887 		 * Use the in-kernel symbol lookup code for fast
    888 		 * retreival of a symbol.
    889 		 */
    890 		mutex_enter(&ksyms_lock);
    891 		TAILQ_FOREACH(st, &ksyms_symtabs, sd_queue) {
    892 			if (st->sd_gone)
    893 				continue;
    894 			if ((sym = findsym(str, st, KSYMS_ANY)) == NULL)
    895 				continue;
    896 #ifdef notdef
    897 			/* Skip if bad binding */
    898 			if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL) {
    899 				sym = NULL;
    900 				continue;
    901 			}
    902 #endif
    903 			break;
    904 		}
    905 		if (sym != NULL) {
    906 			memcpy(&copy, sym, sizeof(copy));
    907 			mutex_exit(&ksyms_lock);
    908 			error = copyout(&copy, kg->kg_sym, sizeof(Elf_Sym));
    909 		} else {
    910 			mutex_exit(&ksyms_lock);
    911 			error = ENOENT;
    912 		}
    913 		kmem_free(str, len);
    914 		break;
    915 
    916 	case KIOCGSIZE:
    917 		/*
    918 		 * Get total size of symbol table.
    919 		 */
    920 		mutex_enter(&ksyms_lock);
    921 		*(int *)data = ksyms_strsz + ksyms_symsz +
    922 		    sizeof(struct ksyms_hdr);
    923 		mutex_exit(&ksyms_lock);
    924 		break;
    925 
    926 	default:
    927 		error = ENOTTY;
    928 		break;
    929 	}
    930 
    931 	return error;
    932 }
    933 
    934 const struct cdevsw ksyms_cdevsw = {
    935 	ksymsopen, ksymsclose, ksymsread, ksymswrite, ksymsioctl,
    936 	nullstop, notty, nopoll, nommap, nullkqfilter, D_OTHER | D_MPSAFE
    937 };
    938