xref: /freebsd/sys/kern/kern_linker.c (revision f9218d3d4fd34f082473b3a021c6d4d109fb47cf)
1 /*-
2  * Copyright (c) 1997-2000 Doug Rabson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 #include "opt_ddb.h"
30 #include "opt_mac.h"
31 
32 #include <sys/param.h>
33 #include <sys/kernel.h>
34 #include <sys/systm.h>
35 #include <sys/malloc.h>
36 #include <sys/sysproto.h>
37 #include <sys/sysent.h>
38 #include <sys/proc.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/sx.h>
42 #include <sys/mac.h>
43 #include <sys/module.h>
44 #include <sys/linker.h>
45 #include <sys/fcntl.h>
46 #include <sys/libkern.h>
47 #include <sys/namei.h>
48 #include <sys/vnode.h>
49 #include <sys/sysctl.h>
50 
51 #include "linker_if.h"
52 
53 #ifdef KLD_DEBUG
54 int kld_debug = 0;
55 #endif
56 
57 /*
58  * static char *linker_search_path(const char *name, struct mod_depend
59  * *verinfo);
60  */
61 static const char 	*linker_basename(const char *path);
62 
63 /* Metadata from the static kernel */
64 SET_DECLARE(modmetadata_set, struct mod_metadata);
65 
66 MALLOC_DEFINE(M_LINKER, "linker", "kernel linker");
67 
68 linker_file_t linker_kernel_file;
69 
70 static struct mtx kld_mtx;	/* kernel linker mutex */
71 
72 static linker_class_list_t classes;
73 static linker_file_list_t linker_files;
74 static int next_file_id = 1;
75 static int linker_no_more_classes = 0;
76 
77 #define	LINKER_GET_NEXT_FILE_ID(a) do {					\
78 	linker_file_t lftmp;						\
79 									\
80 retry:									\
81 	mtx_lock(&kld_mtx);						\
82 	TAILQ_FOREACH(lftmp, &linker_files, link) {			\
83 		if (next_file_id == lftmp->id) {			\
84 			next_file_id++;					\
85 			mtx_unlock(&kld_mtx);				\
86 			goto retry;					\
87 		}							\
88 	}								\
89 	(a) = next_file_id;						\
90 	mtx_unlock(&kld_mtx);	/* Hold for safe read of id variable */	\
91 } while(0)
92 
93 
94 /* XXX wrong name; we're looking at version provision tags here, not modules */
95 typedef TAILQ_HEAD(, modlist) modlisthead_t;
96 struct modlist {
97 	TAILQ_ENTRY(modlist) link;	/* chain together all modules */
98 	linker_file_t   container;
99 	const char 	*name;
100 	int             version;
101 };
102 typedef struct modlist *modlist_t;
103 static modlisthead_t found_modules;
104 
105 static modlist_t	modlist_lookup2(const char *name,
106 			    struct mod_depend *verinfo);
107 
108 static char *
109 linker_strdup(const char *str)
110 {
111 	char *result;
112 
113 	if ((result = malloc((strlen(str) + 1), M_LINKER, M_WAITOK)) != NULL)
114 		strcpy(result, str);
115 	return (result);
116 }
117 
118 static void
119 linker_init(void *arg)
120 {
121 
122 	mtx_init(&kld_mtx, "kernel linker", NULL, MTX_DEF);
123 	TAILQ_INIT(&classes);
124 	TAILQ_INIT(&linker_files);
125 }
126 
127 SYSINIT(linker, SI_SUB_KLD, SI_ORDER_FIRST, linker_init, 0)
128 
129 static void
130 linker_stop_class_add(void *arg)
131 {
132 
133 	linker_no_more_classes = 1;
134 }
135 
136 SYSINIT(linker_class, SI_SUB_KLD, SI_ORDER_ANY, linker_stop_class_add, NULL)
137 
138 int
139 linker_add_class(linker_class_t lc)
140 {
141 
142 	/*
143 	 * We disallow any class registration passt SI_ORDER_ANY
144 	 * of SI_SUB_KLD.
145 	 */
146 	if (linker_no_more_classes == 1)
147 		return (EPERM);
148 	kobj_class_compile((kobj_class_t) lc);
149 	TAILQ_INSERT_TAIL(&classes, lc, link);
150 	return (0);
151 }
152 
153 static void
154 linker_file_sysinit(linker_file_t lf)
155 {
156 	struct sysinit **start, **stop, **sipp, **xipp, *save;
157 
158 	KLD_DPF(FILE, ("linker_file_sysinit: calling SYSINITs for %s\n",
159 	    lf->filename));
160 
161 	if (linker_file_lookup_set(lf, "sysinit_set", &start, &stop, NULL) != 0)
162 		return;
163 	/*
164 	 * Perform a bubble sort of the system initialization objects by
165 	 * their subsystem (primary key) and order (secondary key).
166 	 *
167 	 * Since some things care about execution order, this is the operation
168 	 * which ensures continued function.
169 	 */
170 	for (sipp = start; sipp < stop; sipp++) {
171 		for (xipp = sipp + 1; xipp < stop; xipp++) {
172 			if ((*sipp)->subsystem < (*xipp)->subsystem ||
173 			    ((*sipp)->subsystem == (*xipp)->subsystem &&
174 			    (*sipp)->order <= (*xipp)->order))
175 				continue;	/* skip */
176 			save = *sipp;
177 			*sipp = *xipp;
178 			*xipp = save;
179 		}
180 	}
181 
182 	/*
183 	 * Traverse the (now) ordered list of system initialization tasks.
184 	 * Perform each task, and continue on to the next task.
185 	 */
186 	for (sipp = start; sipp < stop; sipp++) {
187 		if ((*sipp)->subsystem == SI_SUB_DUMMY)
188 			continue;	/* skip dummy task(s) */
189 
190 		/* Call function */
191 		(*((*sipp)->func)) ((*sipp)->udata);
192 	}
193 }
194 
195 static void
196 linker_file_sysuninit(linker_file_t lf)
197 {
198 	struct sysinit **start, **stop, **sipp, **xipp, *save;
199 
200 	KLD_DPF(FILE, ("linker_file_sysuninit: calling SYSUNINITs for %s\n",
201 	    lf->filename));
202 
203 	if (linker_file_lookup_set(lf, "sysuninit_set", &start, &stop,
204 	    NULL) != 0)
205 		return;
206 
207 	/*
208 	 * Perform a reverse bubble sort of the system initialization objects
209 	 * by their subsystem (primary key) and order (secondary key).
210 	 *
211 	 * Since some things care about execution order, this is the operation
212 	 * which ensures continued function.
213 	 */
214 	for (sipp = start; sipp < stop; sipp++) {
215 		for (xipp = sipp + 1; xipp < stop; xipp++) {
216 			if ((*sipp)->subsystem > (*xipp)->subsystem ||
217 			    ((*sipp)->subsystem == (*xipp)->subsystem &&
218 			    (*sipp)->order >= (*xipp)->order))
219 				continue;	/* skip */
220 			save = *sipp;
221 			*sipp = *xipp;
222 			*xipp = save;
223 		}
224 	}
225 
226 	/*
227 	 * Traverse the (now) ordered list of system initialization tasks.
228 	 * Perform each task, and continue on to the next task.
229 	 */
230 	for (sipp = start; sipp < stop; sipp++) {
231 		if ((*sipp)->subsystem == SI_SUB_DUMMY)
232 			continue;	/* skip dummy task(s) */
233 
234 		/* Call function */
235 		(*((*sipp)->func)) ((*sipp)->udata);
236 	}
237 }
238 
239 static void
240 linker_file_register_sysctls(linker_file_t lf)
241 {
242 	struct sysctl_oid **start, **stop, **oidp;
243 
244 	KLD_DPF(FILE,
245 	    ("linker_file_register_sysctls: registering SYSCTLs for %s\n",
246 	    lf->filename));
247 
248 	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
249 		return;
250 
251 	for (oidp = start; oidp < stop; oidp++)
252 		sysctl_register_oid(*oidp);
253 }
254 
255 static void
256 linker_file_unregister_sysctls(linker_file_t lf)
257 {
258 	struct sysctl_oid **start, **stop, **oidp;
259 
260 	KLD_DPF(FILE, ("linker_file_unregister_sysctls: registering SYSCTLs"
261 	    " for %s\n", lf->filename));
262 
263 	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
264 		return;
265 
266 	for (oidp = start; oidp < stop; oidp++)
267 		sysctl_unregister_oid(*oidp);
268 }
269 
270 static int
271 linker_file_register_modules(linker_file_t lf)
272 {
273 	struct mod_metadata **start, **stop, **mdp;
274 	const moduledata_t *moddata;
275 	int error;
276 
277 	KLD_DPF(FILE, ("linker_file_register_modules: registering modules"
278 	    " in %s\n", lf->filename));
279 
280 	if (linker_file_lookup_set(lf, "modmetadata_set", &start,
281 	    &stop, 0) != 0) {
282 		/*
283 		 * This fallback should be unnecessary, but if we get booted
284 		 * from boot2 instead of loader and we are missing our
285 		 * metadata then we have to try the best we can.
286 		 */
287 		if (lf == linker_kernel_file) {
288 			start = SET_BEGIN(modmetadata_set);
289 			stop = SET_LIMIT(modmetadata_set);
290 		} else
291 			return (0);
292 	}
293 	for (mdp = start; mdp < stop; mdp++) {
294 		if ((*mdp)->md_type != MDT_MODULE)
295 			continue;
296 		moddata = (*mdp)->md_data;
297 		KLD_DPF(FILE, ("Registering module %s in %s\n",
298 		    moddata->name, lf->filename));
299 		error = module_register(moddata, lf);
300 		if (error)
301 			printf("Module %s failed to register: %d\n",
302 			    moddata->name, error);
303 	}
304 	return (0);
305 }
306 
307 static void
308 linker_init_kernel_modules(void)
309 {
310 
311 	linker_file_register_modules(linker_kernel_file);
312 }
313 
314 SYSINIT(linker_kernel, SI_SUB_KLD, SI_ORDER_ANY, linker_init_kernel_modules, 0)
315 
316 static int
317 linker_load_file(const char *filename, linker_file_t *result)
318 {
319 	linker_class_t lc;
320 	linker_file_t lf;
321 	int foundfile, error = 0;
322 
323 	/* Refuse to load modules if securelevel raised */
324 	if (securelevel > 0)
325 		return (EPERM);
326 
327 	lf = linker_find_file_by_name(filename);
328 	if (lf) {
329 		KLD_DPF(FILE, ("linker_load_file: file %s is already loaded,"
330 		    " incrementing refs\n", filename));
331 		*result = lf;
332 		lf->refs++;
333 		goto out;
334 	}
335 	lf = NULL;
336 	foundfile = 0;
337 
338 	/*
339 	 * We do not need to protect (lock) classes here because there is
340 	 * no class registration past startup (SI_SUB_KLD, SI_ORDER_ANY)
341 	 * and there is no class deregistration mechanism at this time.
342 	 */
343 	TAILQ_FOREACH(lc, &classes, link) {
344 		KLD_DPF(FILE, ("linker_load_file: trying to load %s\n",
345 		    filename));
346 		error = LINKER_LOAD_FILE(lc, filename, &lf);
347 		/*
348 		 * If we got something other than ENOENT, then it exists but
349 		 * we cannot load it for some other reason.
350 		 */
351 		if (error != ENOENT)
352 			foundfile = 1;
353 		if (lf) {
354 			linker_file_register_modules(lf);
355 			linker_file_register_sysctls(lf);
356 			linker_file_sysinit(lf);
357 			lf->flags |= LINKER_FILE_LINKED;
358 			*result = lf;
359 			error = 0;
360 			goto out;
361 		}
362 	}
363 	/*
364 	 * Less than ideal, but tells the user whether it failed to load or
365 	 * the module was not found.
366 	 */
367 	if (foundfile) {
368 		/*
369 		 * Format not recognized or otherwise unloadable.
370 		 * When loading a module that is statically built into
371 		 * the kernel EEXIST percolates back up as the return
372 		 * value.  Preserve this so that apps like sysinstall
373 		 * can recognize this special case and not post bogus
374 		 * dialog boxes.
375 		 */
376 		if (error != EEXIST)
377 			error = ENOEXEC;
378 	} else
379 		error = ENOENT;		/* Nothing found */
380 out:
381 	return (error);
382 }
383 
384 int
385 linker_reference_module(const char *modname, struct mod_depend *verinfo,
386     linker_file_t *result)
387 {
388 	modlist_t mod;
389 
390 	if ((mod = modlist_lookup2(modname, verinfo)) != NULL) {
391 		*result = mod->container;
392 		(*result)->refs++;
393 		return (0);
394 	}
395 
396 	return (linker_load_module(NULL, modname, NULL, verinfo, result));
397 }
398 
399 linker_file_t
400 linker_find_file_by_name(const char *filename)
401 {
402 	linker_file_t lf = 0;
403 	char *koname;
404 
405 	koname = malloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
406 	if (koname == NULL)
407 		goto out;
408 	sprintf(koname, "%s.ko", filename);
409 
410 	mtx_lock(&kld_mtx);
411 	TAILQ_FOREACH(lf, &linker_files, link) {
412 		if (strcmp(lf->filename, koname) == 0)
413 			break;
414 		if (strcmp(lf->filename, filename) == 0)
415 			break;
416 	}
417 	mtx_unlock(&kld_mtx);
418 out:
419 	if (koname)
420 		free(koname, M_LINKER);
421 	return (lf);
422 }
423 
424 linker_file_t
425 linker_find_file_by_id(int fileid)
426 {
427 	linker_file_t lf = 0;
428 
429 	mtx_lock(&kld_mtx);
430 	TAILQ_FOREACH(lf, &linker_files, link)
431 		if (lf->id == fileid)
432 			break;
433 	mtx_unlock(&kld_mtx);
434 	return (lf);
435 }
436 
437 linker_file_t
438 linker_make_file(const char *pathname, linker_class_t lc)
439 {
440 	linker_file_t lf;
441 	const char *filename;
442 
443 	lf = NULL;
444 	filename = linker_basename(pathname);
445 
446 	KLD_DPF(FILE, ("linker_make_file: new file, filename=%s\n", filename));
447 	lf = (linker_file_t)kobj_create((kobj_class_t)lc, M_LINKER, M_WAITOK);
448 	if (lf == NULL)
449 		goto out;
450 	lf->refs = 1;
451 	lf->userrefs = 0;
452 	lf->flags = 0;
453 	lf->filename = linker_strdup(filename);
454 	LINKER_GET_NEXT_FILE_ID(lf->id);
455 	lf->ndeps = 0;
456 	lf->deps = NULL;
457 	STAILQ_INIT(&lf->common);
458 	TAILQ_INIT(&lf->modules);
459 	mtx_lock(&kld_mtx);
460 	TAILQ_INSERT_TAIL(&linker_files, lf, link);
461 	mtx_unlock(&kld_mtx);
462 out:
463 	return (lf);
464 }
465 
466 int
467 linker_file_unload(linker_file_t file)
468 {
469 	module_t mod, next;
470 	modlist_t ml, nextml;
471 	struct common_symbol *cp;
472 	int error, i;
473 
474 	error = 0;
475 
476 	/* Refuse to unload modules if securelevel raised. */
477 	if (securelevel > 0)
478 		return (EPERM);
479 #ifdef MAC
480 	error = mac_check_kld_unload(curthread->td_ucred);
481 	if (error)
482 		return (error);
483 #endif
484 
485 	KLD_DPF(FILE, ("linker_file_unload: lf->refs=%d\n", file->refs));
486 	if (file->refs == 1) {
487 		KLD_DPF(FILE, ("linker_file_unload: file is unloading,"
488 		    " informing modules\n"));
489 
490 		/*
491 		 * Inform any modules associated with this file.
492 		 */
493 		MOD_XLOCK;
494 		for (mod = TAILQ_FIRST(&file->modules); mod; mod = next) {
495 			next = module_getfnext(mod);
496 			MOD_XUNLOCK;
497 
498 			/*
499 			 * Give the module a chance to veto the unload.
500 			 */
501 			if ((error = module_unload(mod)) != 0) {
502 				KLD_DPF(FILE, ("linker_file_unload: module %p"
503 				    " vetoes unload\n", mod));
504 				goto out;
505 			} else
506 				MOD_XLOCK;
507 			module_release(mod);
508 		}
509 		MOD_XUNLOCK;
510 	}
511 	file->refs--;
512 	if (file->refs > 0) {
513 		goto out;
514 	}
515 	for (ml = TAILQ_FIRST(&found_modules); ml; ml = nextml) {
516 		nextml = TAILQ_NEXT(ml, link);
517 		if (ml->container == file)
518 			TAILQ_REMOVE(&found_modules, ml, link);
519 	}
520 
521 	/*
522 	 * Don't try to run SYSUNINITs if we are unloaded due to a
523 	 * link error.
524 	 */
525 	if (file->flags & LINKER_FILE_LINKED) {
526 		linker_file_sysuninit(file);
527 		linker_file_unregister_sysctls(file);
528 	}
529 	mtx_lock(&kld_mtx);
530 	TAILQ_REMOVE(&linker_files, file, link);
531 	mtx_unlock(&kld_mtx);
532 
533 	if (file->deps) {
534 		for (i = 0; i < file->ndeps; i++)
535 			linker_file_unload(file->deps[i]);
536 		free(file->deps, M_LINKER);
537 		file->deps = NULL;
538 	}
539 	for (cp = STAILQ_FIRST(&file->common); cp;
540 	    cp = STAILQ_FIRST(&file->common)) {
541 		STAILQ_REMOVE(&file->common, cp, common_symbol, link);
542 		free(cp, M_LINKER);
543 	}
544 
545 	LINKER_UNLOAD(file);
546 	if (file->filename) {
547 		free(file->filename, M_LINKER);
548 		file->filename = NULL;
549 	}
550 	kobj_delete((kobj_t) file, M_LINKER);
551 out:
552 	return (error);
553 }
554 
555 int
556 linker_file_add_dependency(linker_file_t file, linker_file_t dep)
557 {
558 	linker_file_t *newdeps;
559 
560 	newdeps = malloc((file->ndeps + 1) * sizeof(linker_file_t *),
561 	    M_LINKER, M_WAITOK | M_ZERO);
562 	if (newdeps == NULL)
563 		return (ENOMEM);
564 
565 	if (file->deps) {
566 		bcopy(file->deps, newdeps,
567 		    file->ndeps * sizeof(linker_file_t *));
568 		free(file->deps, M_LINKER);
569 	}
570 	file->deps = newdeps;
571 	file->deps[file->ndeps] = dep;
572 	file->ndeps++;
573 	return (0);
574 }
575 
576 /*
577  * Locate a linker set and its contents.  This is a helper function to avoid
578  * linker_if.h exposure elsewhere.  Note: firstp and lastp are really void ***
579  */
580 int
581 linker_file_lookup_set(linker_file_t file, const char *name,
582     void *firstp, void *lastp, int *countp)
583 {
584 
585 	return (LINKER_LOOKUP_SET(file, name, firstp, lastp, countp));
586 }
587 
588 caddr_t
589 linker_file_lookup_symbol(linker_file_t file, const char *name, int deps)
590 {
591 	c_linker_sym_t sym;
592 	linker_symval_t symval;
593 	caddr_t address;
594 	size_t common_size = 0;
595 	int i;
596 
597 	KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%p, name=%s, deps=%d\n",
598 	    file, name, deps));
599 
600 	if (LINKER_LOOKUP_SYMBOL(file, name, &sym) == 0) {
601 		LINKER_SYMBOL_VALUES(file, sym, &symval);
602 		if (symval.value == 0)
603 			/*
604 			 * For commons, first look them up in the
605 			 * dependencies and only allocate space if not found
606 			 * there.
607 			 */
608 			common_size = symval.size;
609 		else {
610 			KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol"
611 			    ".value=%p\n", symval.value));
612 			return (symval.value);
613 		}
614 	}
615 	if (deps) {
616 		for (i = 0; i < file->ndeps; i++) {
617 			address = linker_file_lookup_symbol(file->deps[i],
618 			    name, 0);
619 			if (address) {
620 				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
621 				    " deps value=%p\n", address));
622 				return (address);
623 			}
624 		}
625 	}
626 	if (common_size > 0) {
627 		/*
628 		 * This is a common symbol which was not found in the
629 		 * dependencies.  We maintain a simple common symbol table in
630 		 * the file object.
631 		 */
632 		struct common_symbol *cp;
633 
634 		STAILQ_FOREACH(cp, &file->common, link) {
635 			if (strcmp(cp->name, name) == 0) {
636 				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
637 				    " old common value=%p\n", cp->address));
638 				return (cp->address);
639 			}
640 		}
641 		/*
642 		 * Round the symbol size up to align.
643 		 */
644 		common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
645 		cp = malloc(sizeof(struct common_symbol)
646 		    + common_size + strlen(name) + 1, M_LINKER,
647 		    M_WAITOK | M_ZERO);
648 		if (cp == NULL) {
649 			KLD_DPF(SYM, ("linker_file_lookup_symbol: nomem\n"));
650 			return (0);
651 		}
652 		cp->address = (caddr_t)(cp + 1);
653 		cp->name = cp->address + common_size;
654 		strcpy(cp->name, name);
655 		bzero(cp->address, common_size);
656 		STAILQ_INSERT_TAIL(&file->common, cp, link);
657 
658 		KLD_DPF(SYM, ("linker_file_lookup_symbol: new common"
659 		    " value=%p\n", cp->address));
660 		return (cp->address);
661 	}
662 	KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
663 	return (0);
664 }
665 
666 #ifdef DDB
667 /*
668  * DDB Helpers.  DDB has to look across multiple files with their own symbol
669  * tables and string tables.
670  *
671  * Note that we do not obey list locking protocols here.  We really don't need
672  * DDB to hang because somebody's got the lock held.  We'll take the chance
673  * that the files list is inconsistant instead.
674  */
675 
676 int
677 linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
678 {
679 	linker_file_t lf;
680 
681 	TAILQ_FOREACH(lf, &linker_files, link) {
682 		if (LINKER_LOOKUP_SYMBOL(lf, symstr, sym) == 0)
683 			return (0);
684 	}
685 	return (ENOENT);
686 }
687 
688 int
689 linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
690 {
691 	linker_file_t lf;
692 	c_linker_sym_t best, es;
693 	u_long diff, bestdiff, off;
694 
695 	best = 0;
696 	off = (uintptr_t)value;
697 	bestdiff = off;
698 	TAILQ_FOREACH(lf, &linker_files, link) {
699 		if (LINKER_SEARCH_SYMBOL(lf, value, &es, &diff) != 0)
700 			continue;
701 		if (es != 0 && diff < bestdiff) {
702 			best = es;
703 			bestdiff = diff;
704 		}
705 		if (bestdiff == 0)
706 			break;
707 	}
708 	if (best) {
709 		*sym = best;
710 		*diffp = bestdiff;
711 		return (0);
712 	} else {
713 		*sym = 0;
714 		*diffp = off;
715 		return (ENOENT);
716 	}
717 }
718 
719 int
720 linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
721 {
722 	linker_file_t lf;
723 
724 	TAILQ_FOREACH(lf, &linker_files, link) {
725 		if (LINKER_SYMBOL_VALUES(lf, sym, symval) == 0)
726 			return (0);
727 	}
728 	return (ENOENT);
729 }
730 #endif
731 
732 /*
733  * Syscalls.
734  */
735 /*
736  * MPSAFE
737  */
738 int
739 kldload(struct thread *td, struct kldload_args *uap)
740 {
741 	char *kldname, *modname;
742 	char *pathname = NULL;
743 	linker_file_t lf;
744 	int error = 0;
745 
746 	td->td_retval[0] = -1;
747 
748 	mtx_lock(&Giant);
749 
750 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
751 		goto out;
752 
753 	if ((error = suser(td)) != 0)
754 		goto out;
755 
756 	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
757 	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
758 		goto out;
759 
760 	/*
761 	 * If path do not contain qualified name or any dot in it
762 	 * (kldname.ko, or kldname.ver.ko) treat it as interface
763 	 * name.
764 	 */
765 	if (index(pathname, '/') || index(pathname, '.')) {
766 		kldname = pathname;
767 		modname = NULL;
768 	} else {
769 		kldname = NULL;
770 		modname = pathname;
771 	}
772 	error = linker_load_module(kldname, modname, NULL, NULL, &lf);
773 	if (error)
774 		goto out;
775 
776 	lf->userrefs++;
777 	td->td_retval[0] = lf->id;
778 out:
779 	if (pathname)
780 		free(pathname, M_TEMP);
781 	mtx_unlock(&Giant);
782 	return (error);
783 }
784 
785 /*
786  * MPSAFE
787  */
788 int
789 kldunload(struct thread *td, struct kldunload_args *uap)
790 {
791 	linker_file_t lf;
792 	int error = 0;
793 
794 	mtx_lock(&Giant);
795 
796 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
797 		goto out;
798 
799 	if ((error = suser(td)) != 0)
800 		goto out;
801 
802 	lf = linker_find_file_by_id(uap->fileid);
803 	if (lf) {
804 		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
805 		if (lf->userrefs == 0) {
806 			printf("kldunload: attempt to unload file that was"
807 			    " loaded by the kernel\n");
808 			error = EBUSY;
809 			goto out;
810 		}
811 		lf->userrefs--;
812 		error = linker_file_unload(lf);
813 		if (error)
814 			lf->userrefs++;
815 	} else
816 		error = ENOENT;
817 out:
818 	mtx_unlock(&Giant);
819 	return (error);
820 }
821 
822 /*
823  * MPSAFE
824  */
825 int
826 kldfind(struct thread *td, struct kldfind_args *uap)
827 {
828 	char *pathname;
829 	const char *filename;
830 	linker_file_t lf;
831 	int error = 0;
832 
833 #ifdef MAC
834 	error = mac_check_kld_stat(td->td_ucred);
835 	if (error)
836 		return (error);
837 #endif
838 
839 	mtx_lock(&Giant);
840 	td->td_retval[0] = -1;
841 
842 	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
843 	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
844 		goto out;
845 
846 	filename = linker_basename(pathname);
847 	lf = linker_find_file_by_name(filename);
848 	if (lf)
849 		td->td_retval[0] = lf->id;
850 	else
851 		error = ENOENT;
852 out:
853 	if (pathname)
854 		free(pathname, M_TEMP);
855 	mtx_unlock(&Giant);
856 	return (error);
857 }
858 
859 /*
860  * MPSAFE
861  */
862 int
863 kldnext(struct thread *td, struct kldnext_args *uap)
864 {
865 	linker_file_t lf;
866 	int error = 0;
867 
868 #ifdef MAC
869 	error = mac_check_kld_stat(td->td_ucred);
870 	if (error)
871 		return (error);
872 #endif
873 
874 	mtx_lock(&Giant);
875 
876 	if (uap->fileid == 0) {
877 		mtx_lock(&kld_mtx);
878 		if (TAILQ_FIRST(&linker_files))
879 			td->td_retval[0] = TAILQ_FIRST(&linker_files)->id;
880 		else
881 			td->td_retval[0] = 0;
882 		mtx_unlock(&kld_mtx);
883 		goto out;
884 	}
885 	lf = linker_find_file_by_id(uap->fileid);
886 	if (lf) {
887 		if (TAILQ_NEXT(lf, link))
888 			td->td_retval[0] = TAILQ_NEXT(lf, link)->id;
889 		else
890 			td->td_retval[0] = 0;
891 	} else
892 		error = ENOENT;
893 out:
894 	mtx_unlock(&Giant);
895 	return (error);
896 }
897 
898 /*
899  * MPSAFE
900  */
901 int
902 kldstat(struct thread *td, struct kldstat_args *uap)
903 {
904 	linker_file_t lf;
905 	int error = 0;
906 	int namelen, version;
907 	struct kld_file_stat *stat;
908 
909 #ifdef MAC
910 	error = mac_check_kld_stat(td->td_ucred);
911 	if (error)
912 		return (error);
913 #endif
914 
915 	mtx_lock(&Giant);
916 
917 	lf = linker_find_file_by_id(uap->fileid);
918 	if (lf == NULL) {
919 		error = ENOENT;
920 		goto out;
921 	}
922 	stat = uap->stat;
923 
924 	/*
925 	 * Check the version of the user's structure.
926 	 */
927 	if ((error = copyin(&stat->version, &version, sizeof(version))) != 0)
928 		goto out;
929 	if (version != sizeof(struct kld_file_stat)) {
930 		error = EINVAL;
931 		goto out;
932 	}
933 	namelen = strlen(lf->filename) + 1;
934 	if (namelen > MAXPATHLEN)
935 		namelen = MAXPATHLEN;
936 	if ((error = copyout(lf->filename, &stat->name[0], namelen)) != 0)
937 		goto out;
938 	if ((error = copyout(&lf->refs, &stat->refs, sizeof(int))) != 0)
939 		goto out;
940 	if ((error = copyout(&lf->id, &stat->id, sizeof(int))) != 0)
941 		goto out;
942 	if ((error = copyout(&lf->address, &stat->address,
943 	    sizeof(caddr_t))) != 0)
944 		goto out;
945 	if ((error = copyout(&lf->size, &stat->size, sizeof(size_t))) != 0)
946 		goto out;
947 
948 	td->td_retval[0] = 0;
949 out:
950 	mtx_unlock(&Giant);
951 	return (error);
952 }
953 
954 /*
955  * MPSAFE
956  */
957 int
958 kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
959 {
960 	linker_file_t lf;
961 	module_t mp;
962 	int error = 0;
963 
964 #ifdef MAC
965 	error = mac_check_kld_stat(td->td_ucred);
966 	if (error)
967 		return (error);
968 #endif
969 
970 	mtx_lock(&Giant);
971 	lf = linker_find_file_by_id(uap->fileid);
972 	if (lf) {
973 		MOD_SLOCK;
974 		mp = TAILQ_FIRST(&lf->modules);
975 		if (mp != NULL)
976 			td->td_retval[0] = module_getid(mp);
977 		else
978 			td->td_retval[0] = 0;
979 		MOD_SUNLOCK;
980 	} else
981 		error = ENOENT;
982 	mtx_unlock(&Giant);
983 	return (error);
984 }
985 
986 /*
987  * MPSAFE
988  */
989 int
990 kldsym(struct thread *td, struct kldsym_args *uap)
991 {
992 	char *symstr = NULL;
993 	c_linker_sym_t sym;
994 	linker_symval_t symval;
995 	linker_file_t lf;
996 	struct kld_sym_lookup lookup;
997 	int error = 0;
998 
999 #ifdef MAC
1000 	error = mac_check_kld_stat(td->td_ucred);
1001 	if (error)
1002 		return (error);
1003 #endif
1004 
1005 	mtx_lock(&Giant);
1006 
1007 	if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
1008 		goto out;
1009 	if (lookup.version != sizeof(lookup) ||
1010 	    uap->cmd != KLDSYM_LOOKUP) {
1011 		error = EINVAL;
1012 		goto out;
1013 	}
1014 	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1015 	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
1016 		goto out;
1017 	if (uap->fileid != 0) {
1018 		lf = linker_find_file_by_id(uap->fileid);
1019 		if (lf == NULL) {
1020 			error = ENOENT;
1021 			goto out;
1022 		}
1023 		if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1024 		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1025 			lookup.symvalue = (uintptr_t) symval.value;
1026 			lookup.symsize = symval.size;
1027 			error = copyout(&lookup, uap->data, sizeof(lookup));
1028 		} else
1029 			error = ENOENT;
1030 	} else {
1031 		mtx_lock(&kld_mtx);
1032 		TAILQ_FOREACH(lf, &linker_files, link) {
1033 			if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1034 			    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1035 				lookup.symvalue = (uintptr_t)symval.value;
1036 				lookup.symsize = symval.size;
1037 				error = copyout(&lookup, uap->data,
1038 				    sizeof(lookup));
1039 				break;
1040 			}
1041 		}
1042 		mtx_unlock(&kld_mtx);
1043 		if (lf == NULL)
1044 			error = ENOENT;
1045 	}
1046 out:
1047 	if (symstr)
1048 		free(symstr, M_TEMP);
1049 	mtx_unlock(&Giant);
1050 	return (error);
1051 }
1052 
1053 /*
1054  * Preloaded module support
1055  */
1056 
1057 static modlist_t
1058 modlist_lookup(const char *name, int ver)
1059 {
1060 	modlist_t mod;
1061 
1062 	TAILQ_FOREACH(mod, &found_modules, link) {
1063 		if (strcmp(mod->name, name) == 0 &&
1064 		    (ver == 0 || mod->version == ver))
1065 			return (mod);
1066 	}
1067 	return (NULL);
1068 }
1069 
1070 static modlist_t
1071 modlist_lookup2(const char *name, struct mod_depend *verinfo)
1072 {
1073 	modlist_t mod, bestmod;
1074 	int ver;
1075 
1076 	if (verinfo == NULL)
1077 		return (modlist_lookup(name, 0));
1078 	bestmod = NULL;
1079 	for (mod = TAILQ_FIRST(&found_modules); mod;
1080 	    mod = TAILQ_NEXT(mod, link)) {
1081 		if (strcmp(mod->name, name) != 0)
1082 			continue;
1083 		ver = mod->version;
1084 		if (ver == verinfo->md_ver_preferred)
1085 			return (mod);
1086 		if (ver >= verinfo->md_ver_minimum &&
1087 		    ver <= verinfo->md_ver_maximum &&
1088 		    ver > bestmod->version)
1089 			bestmod = mod;
1090 	}
1091 	return (bestmod);
1092 }
1093 
1094 static modlist_t
1095 modlist_newmodule(const char *modname, int version, linker_file_t container)
1096 {
1097 	modlist_t mod;
1098 
1099 	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1100 	if (mod == NULL)
1101 		panic("no memory for module list");
1102 	mod->container = container;
1103 	mod->name = modname;
1104 	mod->version = version;
1105 	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1106 	return (mod);
1107 }
1108 
1109 static void
1110 linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1111     struct mod_metadata **stop, int preload)
1112 {
1113 	struct mod_metadata *mp, **mdp;
1114 	const char *modname;
1115 	int ver;
1116 
1117 	for (mdp = start; mdp < stop; mdp++) {
1118 		mp = *mdp;
1119 		if (mp->md_type != MDT_VERSION)
1120 			continue;
1121 		modname = mp->md_cval;
1122 		ver = ((struct mod_version *)mp->md_data)->mv_version;
1123 		if (modlist_lookup(modname, ver) != NULL) {
1124 			printf("module %s already present!\n", modname);
1125 			/* XXX what can we do? this is a build error. :-( */
1126 			continue;
1127 		}
1128 		modlist_newmodule(modname, ver, lf);
1129 	}
1130 }
1131 
1132 static void
1133 linker_preload(void *arg)
1134 {
1135 	caddr_t modptr;
1136 	const char *modname, *nmodname;
1137 	char *modtype;
1138 	linker_file_t lf;
1139 	linker_class_t lc;
1140 	int error;
1141 	linker_file_list_t loaded_files;
1142 	linker_file_list_t depended_files;
1143 	struct mod_metadata *mp, *nmp;
1144 	struct mod_metadata **start, **stop, **mdp, **nmdp;
1145 	struct mod_depend *verinfo;
1146 	int nver;
1147 	int resolves;
1148 	modlist_t mod;
1149 	struct sysinit **si_start, **si_stop;
1150 
1151 	TAILQ_INIT(&loaded_files);
1152 	TAILQ_INIT(&depended_files);
1153 	TAILQ_INIT(&found_modules);
1154 	error = 0;
1155 
1156 	modptr = NULL;
1157 	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1158 		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1159 		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1160 		if (modname == NULL) {
1161 			printf("Preloaded module at %p does not have a"
1162 			    " name!\n", modptr);
1163 			continue;
1164 		}
1165 		if (modtype == NULL) {
1166 			printf("Preloaded module at %p does not have a type!\n",
1167 			    modptr);
1168 			continue;
1169 		}
1170 		printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1171 		    modptr);
1172 		lf = NULL;
1173 		TAILQ_FOREACH(lc, &classes, link) {
1174 			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1175 			if (error) {
1176 				lf = NULL;
1177 				break;
1178 			}
1179 		}
1180 		if (lf)
1181 			TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1182 	}
1183 
1184 	/*
1185 	 * First get a list of stuff in the kernel.
1186 	 */
1187 	if (linker_file_lookup_set(linker_kernel_file, MDT_SETNAME, &start,
1188 	    &stop, NULL) == 0)
1189 		linker_addmodules(linker_kernel_file, start, stop, 1);
1190 
1191 	/*
1192 	 * this is a once-off kinky bubble sort resolve relocation dependency
1193 	 * requirements
1194 	 */
1195 restart:
1196 	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1197 		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1198 		    &stop, NULL);
1199 		/*
1200 		 * First, look to see if we would successfully link with this
1201 		 * stuff.
1202 		 */
1203 		resolves = 1;	/* unless we know otherwise */
1204 		if (!error) {
1205 			for (mdp = start; mdp < stop; mdp++) {
1206 				mp = *mdp;
1207 				if (mp->md_type != MDT_DEPEND)
1208 					continue;
1209 				modname = mp->md_cval;
1210 				verinfo = mp->md_data;
1211 				for (nmdp = start; nmdp < stop; nmdp++) {
1212 					nmp = *nmdp;
1213 					if (nmp->md_type != MDT_VERSION)
1214 						continue;
1215 					nmodname = nmp->md_cval;
1216 					if (strcmp(modname, nmodname) == 0)
1217 						break;
1218 				}
1219 				if (nmdp < stop)   /* it's a self reference */
1220 					continue;
1221 
1222 				/*
1223 				 * ok, the module isn't here yet, we
1224 				 * are not finished
1225 				 */
1226 				if (modlist_lookup2(modname, verinfo) == NULL)
1227 					resolves = 0;
1228 			}
1229 		}
1230 		/*
1231 		 * OK, if we found our modules, we can link.  So, "provide"
1232 		 * the modules inside and add it to the end of the link order
1233 		 * list.
1234 		 */
1235 		if (resolves) {
1236 			if (!error) {
1237 				for (mdp = start; mdp < stop; mdp++) {
1238 					mp = *mdp;
1239 					if (mp->md_type != MDT_VERSION)
1240 						continue;
1241 					modname = mp->md_cval;
1242 					nver = ((struct mod_version *)
1243 					    mp->md_data)->mv_version;
1244 					if (modlist_lookup(modname,
1245 					    nver) != NULL) {
1246 						printf("module %s already"
1247 						    " present!\n", modname);
1248 						linker_file_unload(lf);
1249 						TAILQ_REMOVE(&loaded_files,
1250 						    lf, loaded);
1251 						/* we changed tailq next ptr */
1252 						goto restart;
1253 					}
1254 					modlist_newmodule(modname, nver, lf);
1255 				}
1256 			}
1257 			TAILQ_REMOVE(&loaded_files, lf, loaded);
1258 			TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1259 			/*
1260 			 * Since we provided modules, we need to restart the
1261 			 * sort so that the previous files that depend on us
1262 			 * have a chance. Also, we've busted the tailq next
1263 			 * pointer with the REMOVE.
1264 			 */
1265 			goto restart;
1266 		}
1267 	}
1268 
1269 	/*
1270 	 * At this point, we check to see what could not be resolved..
1271 	 */
1272 	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1273 		printf("KLD file %s is missing dependencies\n", lf->filename);
1274 		linker_file_unload(lf);
1275 		TAILQ_REMOVE(&loaded_files, lf, loaded);
1276 	}
1277 
1278 	/*
1279 	 * We made it. Finish off the linking in the order we determined.
1280 	 */
1281 	TAILQ_FOREACH(lf, &depended_files, loaded) {
1282 		if (linker_kernel_file) {
1283 			linker_kernel_file->refs++;
1284 			error = linker_file_add_dependency(lf,
1285 			    linker_kernel_file);
1286 			if (error)
1287 				panic("cannot add dependency");
1288 		}
1289 		lf->userrefs++;	/* so we can (try to) kldunload it */
1290 		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1291 		    &stop, NULL);
1292 		if (!error) {
1293 			for (mdp = start; mdp < stop; mdp++) {
1294 				mp = *mdp;
1295 				if (mp->md_type != MDT_DEPEND)
1296 					continue;
1297 				modname = mp->md_cval;
1298 				verinfo = mp->md_data;
1299 				mod = modlist_lookup2(modname, verinfo);
1300 				mod->container->refs++;
1301 				error = linker_file_add_dependency(lf,
1302 				    mod->container);
1303 				if (error)
1304 					panic("cannot add dependency");
1305 			}
1306 		}
1307 		/*
1308 		 * Now do relocation etc using the symbol search paths
1309 		 * established by the dependencies
1310 		 */
1311 		error = LINKER_LINK_PRELOAD_FINISH(lf);
1312 		if (error) {
1313 			printf("KLD file %s - could not finalize loading\n",
1314 			    lf->filename);
1315 			linker_file_unload(lf);
1316 			continue;
1317 		}
1318 		linker_file_register_modules(lf);
1319 		if (linker_file_lookup_set(lf, "sysinit_set", &si_start,
1320 		    &si_stop, NULL) == 0)
1321 			sysinit_add(si_start, si_stop);
1322 		linker_file_register_sysctls(lf);
1323 		lf->flags |= LINKER_FILE_LINKED;
1324 	}
1325 	/* woohoo! we made it! */
1326 }
1327 
1328 SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, 0)
1329 
1330 /*
1331  * Search for a not-loaded module by name.
1332  *
1333  * Modules may be found in the following locations:
1334  *
1335  * - preloaded (result is just the module name) - on disk (result is full path
1336  * to module)
1337  *
1338  * If the module name is qualified in any way (contains path, etc.) the we
1339  * simply return a copy of it.
1340  *
1341  * The search path can be manipulated via sysctl.  Note that we use the ';'
1342  * character as a separator to be consistent with the bootloader.
1343  */
1344 
1345 static char linker_hintfile[] = "linker.hints";
1346 static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules;/modules";
1347 
1348 SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RW, linker_path,
1349     sizeof(linker_path), "module load search path");
1350 
1351 TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1352 
1353 static char *linker_ext_list[] = {
1354 	"",
1355 	".ko",
1356 	NULL
1357 };
1358 
1359 /*
1360  * Check if file actually exists either with or without extension listed in
1361  * the linker_ext_list. (probably should be generic for the rest of the
1362  * kernel)
1363  */
1364 static char *
1365 linker_lookup_file(const char *path, int pathlen, const char *name,
1366     int namelen, struct vattr *vap)
1367 {
1368 	struct nameidata nd;
1369 	struct thread *td = curthread;	/* XXX */
1370 	char *result, **cpp, *sep;
1371 	int error, len, extlen, reclen, flags;
1372 	enum vtype type;
1373 
1374 	extlen = 0;
1375 	for (cpp = linker_ext_list; *cpp; cpp++) {
1376 		len = strlen(*cpp);
1377 		if (len > extlen)
1378 			extlen = len;
1379 	}
1380 	extlen++;		/* trailing '\0' */
1381 	sep = (path[pathlen - 1] != '/') ? "/" : "";
1382 
1383 	reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1384 	result = malloc(reclen, M_LINKER, M_WAITOK);
1385 	for (cpp = linker_ext_list; *cpp; cpp++) {
1386 		snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1387 		    namelen, name, *cpp);
1388 		/*
1389 		 * Attempt to open the file, and return the path if
1390 		 * we succeed and it's a regular file.
1391 		 */
1392 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, result, td);
1393 		flags = FREAD;
1394 		error = vn_open(&nd, &flags, 0);
1395 		if (error == 0) {
1396 			NDFREE(&nd, NDF_ONLY_PNBUF);
1397 			type = nd.ni_vp->v_type;
1398 			if (vap)
1399 				VOP_GETATTR(nd.ni_vp, vap, td->td_ucred, td);
1400 			VOP_UNLOCK(nd.ni_vp, 0, td);
1401 			vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1402 			if (type == VREG)
1403 				return (result);
1404 		}
1405 	}
1406 	free(result, M_LINKER);
1407 	return (NULL);
1408 }
1409 
1410 #define	INT_ALIGN(base, ptr)	ptr =					\
1411 	(base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
1412 
1413 /*
1414  * Lookup KLD which contains requested module in the "linker.hints" file. If
1415  * version specification is available, then try to find the best KLD.
1416  * Otherwise just find the latest one.
1417  */
1418 static char *
1419 linker_hints_lookup(const char *path, int pathlen, const char *modname,
1420     int modnamelen, struct mod_depend *verinfo)
1421 {
1422 	struct thread *td = curthread;	/* XXX */
1423 	struct ucred *cred = td ? td->td_ucred : NULL;
1424 	struct nameidata nd;
1425 	struct vattr vattr, mattr;
1426 	u_char *hints = NULL;
1427 	u_char *cp, *recptr, *bufend, *result, *best, *pathbuf, *sep;
1428 	int error, ival, bestver, *intp, reclen, found, flags, clen, blen;
1429 
1430 	result = NULL;
1431 	bestver = found = 0;
1432 
1433 	sep = (path[pathlen - 1] != '/') ? "/" : "";
1434 	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1435 	    strlen(sep) + 1;
1436 	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1437 	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1438 	    linker_hintfile);
1439 
1440 	NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, pathbuf, td);
1441 	flags = FREAD;
1442 	error = vn_open(&nd, &flags, 0);
1443 	if (error)
1444 		goto bad;
1445 	NDFREE(&nd, NDF_ONLY_PNBUF);
1446 	if (nd.ni_vp->v_type != VREG)
1447 		goto bad;
1448 	best = cp = NULL;
1449 	error = VOP_GETATTR(nd.ni_vp, &vattr, cred, td);
1450 	if (error)
1451 		goto bad;
1452 	/*
1453 	 * XXX: we need to limit this number to some reasonable value
1454 	 */
1455 	if (vattr.va_size > 100 * 1024) {
1456 		printf("hints file too large %ld\n", (long)vattr.va_size);
1457 		goto bad;
1458 	}
1459 	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
1460 	if (hints == NULL)
1461 		goto bad;
1462 	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
1463 	    UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
1464 	if (error)
1465 		goto bad;
1466 	VOP_UNLOCK(nd.ni_vp, 0, td);
1467 	vn_close(nd.ni_vp, FREAD, cred, td);
1468 	nd.ni_vp = NULL;
1469 	if (reclen != 0) {
1470 		printf("can't read %d\n", reclen);
1471 		goto bad;
1472 	}
1473 	intp = (int *)hints;
1474 	ival = *intp++;
1475 	if (ival != LINKER_HINTS_VERSION) {
1476 		printf("hints file version mismatch %d\n", ival);
1477 		goto bad;
1478 	}
1479 	bufend = hints + vattr.va_size;
1480 	recptr = (u_char *)intp;
1481 	clen = blen = 0;
1482 	while (recptr < bufend && !found) {
1483 		intp = (int *)recptr;
1484 		reclen = *intp++;
1485 		ival = *intp++;
1486 		cp = (char *)intp;
1487 		switch (ival) {
1488 		case MDT_VERSION:
1489 			clen = *cp++;
1490 			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1491 				break;
1492 			cp += clen;
1493 			INT_ALIGN(hints, cp);
1494 			ival = *(int *)cp;
1495 			cp += sizeof(int);
1496 			clen = *cp++;
1497 			if (verinfo == NULL ||
1498 			    ival == verinfo->md_ver_preferred) {
1499 				found = 1;
1500 				break;
1501 			}
1502 			if (ival >= verinfo->md_ver_minimum &&
1503 			    ival <= verinfo->md_ver_maximum &&
1504 			    ival > bestver) {
1505 				bestver = ival;
1506 				best = cp;
1507 				blen = clen;
1508 			}
1509 			break;
1510 		default:
1511 			break;
1512 		}
1513 		recptr += reclen + sizeof(int);
1514 	}
1515 	/*
1516 	 * Finally check if KLD is in the place
1517 	 */
1518 	if (found)
1519 		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
1520 	else if (best)
1521 		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
1522 
1523 	/*
1524 	 * KLD is newer than hints file. What we should do now?
1525 	 */
1526 	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
1527 		printf("warning: KLD '%s' is newer than the linker.hints"
1528 		    " file\n", result);
1529 bad:
1530 	free(pathbuf, M_LINKER);
1531 	if (hints)
1532 		free(hints, M_TEMP);
1533 	if (nd.ni_vp != NULL) {
1534 		VOP_UNLOCK(nd.ni_vp, 0, td);
1535 		vn_close(nd.ni_vp, FREAD, cred, td);
1536 	}
1537 	/*
1538 	 * If nothing found or hints is absent - fallback to the old
1539 	 * way by using "kldname[.ko]" as module name.
1540 	 */
1541 	if (!found && !bestver && result == NULL)
1542 		result = linker_lookup_file(path, pathlen, modname,
1543 		    modnamelen, NULL);
1544 	return (result);
1545 }
1546 
1547 /*
1548  * Lookup KLD which contains requested module in the all directories.
1549  */
1550 static char *
1551 linker_search_module(const char *modname, int modnamelen,
1552     struct mod_depend *verinfo)
1553 {
1554 	char *cp, *ep, *result;
1555 
1556 	/*
1557 	 * traverse the linker path
1558 	 */
1559 	for (cp = linker_path; *cp; cp = ep + 1) {
1560 		/* find the end of this component */
1561 		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
1562 		result = linker_hints_lookup(cp, ep - cp, modname,
1563 		    modnamelen, verinfo);
1564 		if (result != NULL)
1565 			return (result);
1566 		if (*ep == 0)
1567 			break;
1568 	}
1569 	return (NULL);
1570 }
1571 
1572 /*
1573  * Search for module in all directories listed in the linker_path.
1574  */
1575 static char *
1576 linker_search_kld(const char *name)
1577 {
1578 	char *cp, *ep, *result, **cpp;
1579 	int extlen, len;
1580 
1581 	/* qualified at all? */
1582 	if (index(name, '/'))
1583 		return (linker_strdup(name));
1584 
1585 	extlen = 0;
1586 	for (cpp = linker_ext_list; *cpp; cpp++) {
1587 		len = strlen(*cpp);
1588 		if (len > extlen)
1589 			extlen = len;
1590 	}
1591 	extlen++;		/* trailing '\0' */
1592 
1593 	/* traverse the linker path */
1594 	len = strlen(name);
1595 	for (ep = linker_path; *ep; ep++) {
1596 		cp = ep;
1597 		/* find the end of this component */
1598 		for (; *ep != 0 && *ep != ';'; ep++);
1599 		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
1600 		if (result != NULL)
1601 			return (result);
1602 	}
1603 	return (NULL);
1604 }
1605 
1606 static const char *
1607 linker_basename(const char *path)
1608 {
1609 	const char *filename;
1610 
1611 	filename = rindex(path, '/');
1612 	if (filename == NULL)
1613 		return path;
1614 	if (filename[1])
1615 		filename++;
1616 	return (filename);
1617 }
1618 
1619 /*
1620  * Find a file which contains given module and load it, if "parent" is not
1621  * NULL, register a reference to it.
1622  */
1623 int
1624 linker_load_module(const char *kldname, const char *modname,
1625     struct linker_file *parent, struct mod_depend *verinfo,
1626     struct linker_file **lfpp)
1627 {
1628 	linker_file_t lfdep;
1629 	const char *filename;
1630 	char *pathname;
1631 	int error;
1632 
1633 	if (modname == NULL) {
1634 		/*
1635  		 * We have to load KLD
1636  		 */
1637 		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
1638 		    " is not NULL"));
1639 		pathname = linker_search_kld(kldname);
1640 	} else {
1641 		if (modlist_lookup2(modname, verinfo) != NULL)
1642 			return (EEXIST);
1643 		if (kldname != NULL)
1644 			pathname = linker_strdup(kldname);
1645 		else if (rootvnode == NULL)
1646 			pathname = NULL;
1647 		else
1648 			/*
1649 			 * Need to find a KLD with required module
1650 			 */
1651 			pathname = linker_search_module(modname,
1652 			    strlen(modname), verinfo);
1653 	}
1654 	if (pathname == NULL)
1655 		return (ENOENT);
1656 
1657 	/*
1658 	 * Can't load more than one file with the same basename XXX:
1659 	 * Actually it should be possible to have multiple KLDs with
1660 	 * the same basename but different path because they can
1661 	 * provide different versions of the same modules.
1662 	 */
1663 	filename = linker_basename(pathname);
1664 	if (linker_find_file_by_name(filename)) {
1665 		error = EEXIST;
1666 		goto out;
1667 	}
1668 	do {
1669 		error = linker_load_file(pathname, &lfdep);
1670 		if (error)
1671 			break;
1672 		if (modname && verinfo &&
1673 		    modlist_lookup2(modname, verinfo) == NULL) {
1674 			linker_file_unload(lfdep);
1675 			error = ENOENT;
1676 			break;
1677 		}
1678 		if (parent) {
1679 			error = linker_file_add_dependency(parent, lfdep);
1680 			if (error)
1681 				break;
1682 		}
1683 		if (lfpp)
1684 			*lfpp = lfdep;
1685 	} while (0);
1686 out:
1687 	if (pathname)
1688 		free(pathname, M_LINKER);
1689 	return (error);
1690 }
1691 
1692 /*
1693  * This routine is responsible for finding dependencies of userland initiated
1694  * kldload(2)'s of files.
1695  */
1696 int
1697 linker_load_dependencies(linker_file_t lf)
1698 {
1699 	linker_file_t lfdep;
1700 	struct mod_metadata **start, **stop, **mdp, **nmdp;
1701 	struct mod_metadata *mp, *nmp;
1702 	struct mod_depend *verinfo;
1703 	modlist_t mod;
1704 	const char *modname, *nmodname;
1705 	int ver, error = 0, count;
1706 
1707 	/*
1708 	 * All files are dependant on /kernel.
1709 	 */
1710 	if (linker_kernel_file) {
1711 		linker_kernel_file->refs++;
1712 		error = linker_file_add_dependency(lf, linker_kernel_file);
1713 		if (error)
1714 			return (error);
1715 	}
1716 	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
1717 	    &count) != 0)
1718 		return (0);
1719 	for (mdp = start; mdp < stop; mdp++) {
1720 		mp = *mdp;
1721 		if (mp->md_type != MDT_VERSION)
1722 			continue;
1723 		modname = mp->md_cval;
1724 		ver = ((struct mod_version *)mp->md_data)->mv_version;
1725 		mod = modlist_lookup(modname, ver);
1726 		if (mod != NULL) {
1727 			printf("interface %s.%d already present in the KLD"
1728 			    " '%s'!\n", modname, ver,
1729 			    mod->container->filename);
1730 			return (EEXIST);
1731 		}
1732 	}
1733 
1734 	for (mdp = start; mdp < stop; mdp++) {
1735 		mp = *mdp;
1736 		if (mp->md_type != MDT_DEPEND)
1737 			continue;
1738 		modname = mp->md_cval;
1739 		verinfo = mp->md_data;
1740 		nmodname = NULL;
1741 		for (nmdp = start; nmdp < stop; nmdp++) {
1742 			nmp = *nmdp;
1743 			if (nmp->md_type != MDT_VERSION)
1744 				continue;
1745 			nmodname = nmp->md_cval;
1746 			if (strcmp(modname, nmodname) == 0)
1747 				break;
1748 		}
1749 		if (nmdp < stop)/* early exit, it's a self reference */
1750 			continue;
1751 		mod = modlist_lookup2(modname, verinfo);
1752 		if (mod) {	/* woohoo, it's loaded already */
1753 			lfdep = mod->container;
1754 			lfdep->refs++;
1755 			error = linker_file_add_dependency(lf, lfdep);
1756 			if (error)
1757 				break;
1758 			continue;
1759 		}
1760 		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
1761 		if (error) {
1762 			printf("KLD %s: depends on %s - not available\n",
1763 			    lf->filename, modname);
1764 			break;
1765 		}
1766 	}
1767 
1768 	if (error)
1769 		return (error);
1770 	linker_addmodules(lf, start, stop, 0);
1771 	return (error);
1772 }
1773 
1774 static int
1775 sysctl_kern_function_list_iterate(const char *name, void *opaque)
1776 {
1777 	struct sysctl_req *req;
1778 
1779 	req = opaque;
1780 	return (SYSCTL_OUT(req, name, strlen(name) + 1));
1781 }
1782 
1783 /*
1784  * Export a nul-separated, double-nul-terminated list of all function names
1785  * in the kernel.
1786  */
1787 static int
1788 sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
1789 {
1790 	linker_file_t lf;
1791 	int error;
1792 
1793 #ifdef MAC
1794 	error = mac_check_kld_stat(req->td->td_ucred);
1795 	if (error)
1796 		return (error);
1797 #endif
1798 	sysctl_wire_old_buffer(req, 0);
1799 	mtx_lock(&kld_mtx);
1800 	TAILQ_FOREACH(lf, &linker_files, link) {
1801 		error = LINKER_EACH_FUNCTION_NAME(lf,
1802 		    sysctl_kern_function_list_iterate, req);
1803 		if (error) {
1804 			mtx_unlock(&kld_mtx);
1805 			return (error);
1806 		}
1807 	}
1808 	mtx_unlock(&kld_mtx);
1809 	return (SYSCTL_OUT(req, "", 1));
1810 }
1811 
1812 SYSCTL_PROC(_kern, OID_AUTO, function_list, CTLFLAG_RD,
1813     NULL, 0, sysctl_kern_function_list, "", "kernel function list");
1814