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