xref: /freebsd/sys/kern/kern_linker.c (revision f0adf7f5cdd241db2f2c817683191a6ef64a4e95)
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 passt SI_ORDER_ANY
145 	 * of SI_SUB_KLD.
146 	 */
147 	if (linker_no_more_classes == 1)
148 		return (EPERM);
149 	kobj_class_compile((kobj_class_t) lc);
150 	((kobj_class_t)lc)->refs++;	/* prevent ops being freed */
151 	TAILQ_INSERT_TAIL(&classes, lc, link);
152 	return (0);
153 }
154 
155 static void
156 linker_file_sysinit(linker_file_t lf)
157 {
158 	struct sysinit **start, **stop, **sipp, **xipp, *save;
159 
160 	KLD_DPF(FILE, ("linker_file_sysinit: calling SYSINITs for %s\n",
161 	    lf->filename));
162 
163 	if (linker_file_lookup_set(lf, "sysinit_set", &start, &stop, NULL) != 0)
164 		return;
165 	/*
166 	 * Perform a bubble sort of the system initialization objects by
167 	 * their subsystem (primary key) and order (secondary key).
168 	 *
169 	 * Since some things care about execution order, this is the operation
170 	 * which ensures continued function.
171 	 */
172 	for (sipp = start; sipp < stop; sipp++) {
173 		for (xipp = sipp + 1; xipp < stop; xipp++) {
174 			if ((*sipp)->subsystem < (*xipp)->subsystem ||
175 			    ((*sipp)->subsystem == (*xipp)->subsystem &&
176 			    (*sipp)->order <= (*xipp)->order))
177 				continue;	/* skip */
178 			save = *sipp;
179 			*sipp = *xipp;
180 			*xipp = save;
181 		}
182 	}
183 
184 	/*
185 	 * Traverse the (now) ordered list of system initialization tasks.
186 	 * Perform each task, and continue on to the next task.
187 	 */
188 	for (sipp = start; sipp < stop; sipp++) {
189 		if ((*sipp)->subsystem == SI_SUB_DUMMY)
190 			continue;	/* skip dummy task(s) */
191 
192 		/* Call function */
193 		(*((*sipp)->func)) ((*sipp)->udata);
194 	}
195 }
196 
197 static void
198 linker_file_sysuninit(linker_file_t lf)
199 {
200 	struct sysinit **start, **stop, **sipp, **xipp, *save;
201 
202 	KLD_DPF(FILE, ("linker_file_sysuninit: calling SYSUNINITs for %s\n",
203 	    lf->filename));
204 
205 	if (linker_file_lookup_set(lf, "sysuninit_set", &start, &stop,
206 	    NULL) != 0)
207 		return;
208 
209 	/*
210 	 * Perform a reverse bubble sort of the system initialization objects
211 	 * by their subsystem (primary key) and order (secondary key).
212 	 *
213 	 * Since some things care about execution order, this is the operation
214 	 * which ensures continued function.
215 	 */
216 	for (sipp = start; sipp < stop; sipp++) {
217 		for (xipp = sipp + 1; xipp < stop; xipp++) {
218 			if ((*sipp)->subsystem > (*xipp)->subsystem ||
219 			    ((*sipp)->subsystem == (*xipp)->subsystem &&
220 			    (*sipp)->order >= (*xipp)->order))
221 				continue;	/* skip */
222 			save = *sipp;
223 			*sipp = *xipp;
224 			*xipp = save;
225 		}
226 	}
227 
228 	/*
229 	 * Traverse the (now) ordered list of system initialization tasks.
230 	 * Perform each task, and continue on to the next task.
231 	 */
232 	for (sipp = start; sipp < stop; sipp++) {
233 		if ((*sipp)->subsystem == SI_SUB_DUMMY)
234 			continue;	/* skip dummy task(s) */
235 
236 		/* Call function */
237 		(*((*sipp)->func)) ((*sipp)->udata);
238 	}
239 }
240 
241 static void
242 linker_file_register_sysctls(linker_file_t lf)
243 {
244 	struct sysctl_oid **start, **stop, **oidp;
245 
246 	KLD_DPF(FILE,
247 	    ("linker_file_register_sysctls: registering SYSCTLs for %s\n",
248 	    lf->filename));
249 
250 	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
251 		return;
252 
253 	for (oidp = start; oidp < stop; oidp++)
254 		sysctl_register_oid(*oidp);
255 }
256 
257 static void
258 linker_file_unregister_sysctls(linker_file_t lf)
259 {
260 	struct sysctl_oid **start, **stop, **oidp;
261 
262 	KLD_DPF(FILE, ("linker_file_unregister_sysctls: registering SYSCTLs"
263 	    " for %s\n", lf->filename));
264 
265 	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
266 		return;
267 
268 	for (oidp = start; oidp < stop; oidp++)
269 		sysctl_unregister_oid(*oidp);
270 }
271 
272 static int
273 linker_file_register_modules(linker_file_t lf)
274 {
275 	struct mod_metadata **start, **stop, **mdp;
276 	const moduledata_t *moddata;
277 	int error;
278 
279 	KLD_DPF(FILE, ("linker_file_register_modules: registering modules"
280 	    " in %s\n", lf->filename));
281 
282 	if (linker_file_lookup_set(lf, "modmetadata_set", &start,
283 	    &stop, 0) != 0) {
284 		/*
285 		 * This fallback should be unnecessary, but if we get booted
286 		 * from boot2 instead of loader and we are missing our
287 		 * metadata then we have to try the best we can.
288 		 */
289 		if (lf == linker_kernel_file) {
290 			start = SET_BEGIN(modmetadata_set);
291 			stop = SET_LIMIT(modmetadata_set);
292 		} else
293 			return (0);
294 	}
295 	for (mdp = start; mdp < stop; mdp++) {
296 		if ((*mdp)->md_type != MDT_MODULE)
297 			continue;
298 		moddata = (*mdp)->md_data;
299 		KLD_DPF(FILE, ("Registering module %s in %s\n",
300 		    moddata->name, lf->filename));
301 		error = module_register(moddata, lf);
302 		if (error)
303 			printf("Module %s failed to register: %d\n",
304 			    moddata->name, error);
305 	}
306 	return (0);
307 }
308 
309 static void
310 linker_init_kernel_modules(void)
311 {
312 
313 	linker_file_register_modules(linker_kernel_file);
314 }
315 
316 SYSINIT(linker_kernel, SI_SUB_KLD, SI_ORDER_ANY, linker_init_kernel_modules, 0)
317 
318 static int
319 linker_load_file(const char *filename, linker_file_t *result)
320 {
321 	linker_class_t lc;
322 	linker_file_t lf;
323 	int foundfile, error = 0;
324 
325 	/* Refuse to load modules if securelevel raised */
326 	if (securelevel > 0)
327 		return (EPERM);
328 
329 	lf = linker_find_file_by_name(filename);
330 	if (lf) {
331 		KLD_DPF(FILE, ("linker_load_file: file %s is already loaded,"
332 		    " incrementing refs\n", filename));
333 		*result = lf;
334 		lf->refs++;
335 		goto out;
336 	}
337 	lf = NULL;
338 	foundfile = 0;
339 
340 	/*
341 	 * We do not need to protect (lock) classes here because there is
342 	 * no class registration past startup (SI_SUB_KLD, SI_ORDER_ANY)
343 	 * and there is no class deregistration mechanism at this time.
344 	 */
345 	TAILQ_FOREACH(lc, &classes, link) {
346 		KLD_DPF(FILE, ("linker_load_file: trying to load %s\n",
347 		    filename));
348 		error = LINKER_LOAD_FILE(lc, filename, &lf);
349 		/*
350 		 * If we got something other than ENOENT, then it exists but
351 		 * we cannot load it for some other reason.
352 		 */
353 		if (error != ENOENT)
354 			foundfile = 1;
355 		if (lf) {
356 			linker_file_register_modules(lf);
357 			linker_file_register_sysctls(lf);
358 			linker_file_sysinit(lf);
359 			lf->flags |= LINKER_FILE_LINKED;
360 			*result = lf;
361 			error = 0;
362 			goto out;
363 		}
364 	}
365 	/*
366 	 * Less than ideal, but tells the user whether it failed to load or
367 	 * the module was not found.
368 	 */
369 	if (foundfile) {
370 		/*
371 		 * Format not recognized or otherwise unloadable.
372 		 * When loading a module that is statically built into
373 		 * the kernel EEXIST percolates back up as the return
374 		 * value.  Preserve this so that apps like sysinstall
375 		 * can recognize this special case and not post bogus
376 		 * dialog boxes.
377 		 */
378 		if (error != EEXIST)
379 			error = ENOEXEC;
380 	} else
381 		error = ENOENT;		/* Nothing found */
382 out:
383 	return (error);
384 }
385 
386 int
387 linker_reference_module(const char *modname, struct mod_depend *verinfo,
388     linker_file_t *result)
389 {
390 	modlist_t mod;
391 
392 	if ((mod = modlist_lookup2(modname, verinfo)) != NULL) {
393 		*result = mod->container;
394 		(*result)->refs++;
395 		return (0);
396 	}
397 
398 	return (linker_load_module(NULL, modname, NULL, verinfo, result));
399 }
400 
401 linker_file_t
402 linker_find_file_by_name(const char *filename)
403 {
404 	linker_file_t lf = 0;
405 	char *koname;
406 
407 	koname = malloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
408 	if (koname == NULL)
409 		goto out;
410 	sprintf(koname, "%s.ko", filename);
411 
412 	mtx_lock(&kld_mtx);
413 	TAILQ_FOREACH(lf, &linker_files, link) {
414 		if (strcmp(lf->filename, koname) == 0)
415 			break;
416 		if (strcmp(lf->filename, filename) == 0)
417 			break;
418 	}
419 	mtx_unlock(&kld_mtx);
420 out:
421 	if (koname)
422 		free(koname, M_LINKER);
423 	return (lf);
424 }
425 
426 linker_file_t
427 linker_find_file_by_id(int fileid)
428 {
429 	linker_file_t lf = 0;
430 
431 	mtx_lock(&kld_mtx);
432 	TAILQ_FOREACH(lf, &linker_files, link)
433 		if (lf->id == fileid)
434 			break;
435 	mtx_unlock(&kld_mtx);
436 	return (lf);
437 }
438 
439 linker_file_t
440 linker_make_file(const char *pathname, linker_class_t lc)
441 {
442 	linker_file_t lf;
443 	const char *filename;
444 
445 	lf = NULL;
446 	filename = linker_basename(pathname);
447 
448 	KLD_DPF(FILE, ("linker_make_file: new file, filename=%s\n", filename));
449 	lf = (linker_file_t)kobj_create((kobj_class_t)lc, M_LINKER, M_WAITOK);
450 	if (lf == NULL)
451 		goto out;
452 	lf->refs = 1;
453 	lf->userrefs = 0;
454 	lf->flags = 0;
455 	lf->filename = linker_strdup(filename);
456 	LINKER_GET_NEXT_FILE_ID(lf->id);
457 	lf->ndeps = 0;
458 	lf->deps = NULL;
459 	STAILQ_INIT(&lf->common);
460 	TAILQ_INIT(&lf->modules);
461 	mtx_lock(&kld_mtx);
462 	TAILQ_INSERT_TAIL(&linker_files, lf, link);
463 	mtx_unlock(&kld_mtx);
464 out:
465 	return (lf);
466 }
467 
468 int
469 linker_file_unload(linker_file_t file, int flags)
470 {
471 	module_t mod, next;
472 	modlist_t ml, nextml;
473 	struct common_symbol *cp;
474 	int error, i;
475 
476 	error = 0;
477 
478 	/* Refuse to unload modules if securelevel raised. */
479 	if (securelevel > 0)
480 		return (EPERM);
481 #ifdef MAC
482 	error = mac_check_kld_unload(curthread->td_ucred);
483 	if (error)
484 		return (error);
485 #endif
486 
487 	KLD_DPF(FILE, ("linker_file_unload: lf->refs=%d\n", file->refs));
488 	if (file->refs == 1) {
489 		KLD_DPF(FILE, ("linker_file_unload: file is unloading,"
490 		    " informing modules\n"));
491 
492 		/*
493 		 * Inform any modules associated with this file.
494 		 */
495 		MOD_XLOCK;
496 		for (mod = TAILQ_FIRST(&file->modules); mod; mod = next) {
497 			next = module_getfnext(mod);
498 			MOD_XUNLOCK;
499 
500 			/*
501 			 * Give the module a chance to veto the unload.
502 			 */
503 			if ((error = module_unload(mod, flags)) != 0) {
504 				KLD_DPF(FILE, ("linker_file_unload: module %p"
505 				    " vetoes unload\n", mod));
506 				goto out;
507 			} else
508 				MOD_XLOCK;
509 			module_release(mod);
510 		}
511 		MOD_XUNLOCK;
512 	}
513 	file->refs--;
514 	if (file->refs > 0) {
515 		goto out;
516 	}
517 	for (ml = TAILQ_FIRST(&found_modules); ml; ml = nextml) {
518 		nextml = TAILQ_NEXT(ml, link);
519 		if (ml->container == file) {
520 			TAILQ_REMOVE(&found_modules, ml, link);
521 			free(ml, M_LINKER);
522 		}
523 	}
524 
525 	/*
526 	 * Don't try to run SYSUNINITs if we are unloaded due to a
527 	 * link error.
528 	 */
529 	if (file->flags & LINKER_FILE_LINKED) {
530 		linker_file_sysuninit(file);
531 		linker_file_unregister_sysctls(file);
532 	}
533 	mtx_lock(&kld_mtx);
534 	TAILQ_REMOVE(&linker_files, file, link);
535 	mtx_unlock(&kld_mtx);
536 
537 	if (file->deps) {
538 		for (i = 0; i < file->ndeps; i++)
539 			linker_file_unload(file->deps[i], flags);
540 		free(file->deps, M_LINKER);
541 		file->deps = NULL;
542 	}
543 	for (cp = STAILQ_FIRST(&file->common); cp;
544 	    cp = STAILQ_FIRST(&file->common)) {
545 		STAILQ_REMOVE(&file->common, cp, common_symbol, link);
546 		free(cp, M_LINKER);
547 	}
548 
549 	LINKER_UNLOAD(file);
550 	if (file->filename) {
551 		free(file->filename, M_LINKER);
552 		file->filename = NULL;
553 	}
554 	kobj_delete((kobj_t) file, M_LINKER);
555 out:
556 	return (error);
557 }
558 
559 int
560 linker_file_add_dependency(linker_file_t file, linker_file_t dep)
561 {
562 	linker_file_t *newdeps;
563 
564 	newdeps = malloc((file->ndeps + 1) * sizeof(linker_file_t *),
565 	    M_LINKER, M_WAITOK | M_ZERO);
566 	if (newdeps == NULL)
567 		return (ENOMEM);
568 
569 	if (file->deps) {
570 		bcopy(file->deps, newdeps,
571 		    file->ndeps * sizeof(linker_file_t *));
572 		free(file->deps, M_LINKER);
573 	}
574 	file->deps = newdeps;
575 	file->deps[file->ndeps] = dep;
576 	file->ndeps++;
577 	return (0);
578 }
579 
580 /*
581  * Locate a linker set and its contents.  This is a helper function to avoid
582  * linker_if.h exposure elsewhere.  Note: firstp and lastp are really void ***
583  */
584 int
585 linker_file_lookup_set(linker_file_t file, const char *name,
586     void *firstp, void *lastp, int *countp)
587 {
588 
589 	return (LINKER_LOOKUP_SET(file, name, firstp, lastp, countp));
590 }
591 
592 caddr_t
593 linker_file_lookup_symbol(linker_file_t file, const char *name, int deps)
594 {
595 	c_linker_sym_t sym;
596 	linker_symval_t symval;
597 	caddr_t address;
598 	size_t common_size = 0;
599 	int i;
600 
601 	KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%p, name=%s, deps=%d\n",
602 	    file, name, deps));
603 
604 	if (LINKER_LOOKUP_SYMBOL(file, name, &sym) == 0) {
605 		LINKER_SYMBOL_VALUES(file, sym, &symval);
606 		if (symval.value == 0)
607 			/*
608 			 * For commons, first look them up in the
609 			 * dependencies and only allocate space if not found
610 			 * there.
611 			 */
612 			common_size = symval.size;
613 		else {
614 			KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol"
615 			    ".value=%p\n", symval.value));
616 			return (symval.value);
617 		}
618 	}
619 	if (deps) {
620 		for (i = 0; i < file->ndeps; i++) {
621 			address = linker_file_lookup_symbol(file->deps[i],
622 			    name, 0);
623 			if (address) {
624 				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
625 				    " deps value=%p\n", address));
626 				return (address);
627 			}
628 		}
629 	}
630 	if (common_size > 0) {
631 		/*
632 		 * This is a common symbol which was not found in the
633 		 * dependencies.  We maintain a simple common symbol table in
634 		 * the file object.
635 		 */
636 		struct common_symbol *cp;
637 
638 		STAILQ_FOREACH(cp, &file->common, link) {
639 			if (strcmp(cp->name, name) == 0) {
640 				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
641 				    " old common value=%p\n", cp->address));
642 				return (cp->address);
643 			}
644 		}
645 		/*
646 		 * Round the symbol size up to align.
647 		 */
648 		common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
649 		cp = malloc(sizeof(struct common_symbol)
650 		    + common_size + strlen(name) + 1, M_LINKER,
651 		    M_WAITOK | M_ZERO);
652 		if (cp == NULL) {
653 			KLD_DPF(SYM, ("linker_file_lookup_symbol: nomem\n"));
654 			return (0);
655 		}
656 		cp->address = (caddr_t)(cp + 1);
657 		cp->name = cp->address + common_size;
658 		strcpy(cp->name, name);
659 		bzero(cp->address, common_size);
660 		STAILQ_INSERT_TAIL(&file->common, cp, link);
661 
662 		KLD_DPF(SYM, ("linker_file_lookup_symbol: new common"
663 		    " value=%p\n", cp->address));
664 		return (cp->address);
665 	}
666 	KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
667 	return (0);
668 }
669 
670 #ifdef DDB
671 /*
672  * DDB Helpers.  DDB has to look across multiple files with their own symbol
673  * tables and string tables.
674  *
675  * Note that we do not obey list locking protocols here.  We really don't need
676  * DDB to hang because somebody's got the lock held.  We'll take the chance
677  * that the files list is inconsistant instead.
678  */
679 
680 int
681 linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
682 {
683 	linker_file_t lf;
684 
685 	TAILQ_FOREACH(lf, &linker_files, link) {
686 		if (LINKER_LOOKUP_SYMBOL(lf, symstr, sym) == 0)
687 			return (0);
688 	}
689 	return (ENOENT);
690 }
691 
692 int
693 linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
694 {
695 	linker_file_t lf;
696 	c_linker_sym_t best, es;
697 	u_long diff, bestdiff, off;
698 
699 	best = 0;
700 	off = (uintptr_t)value;
701 	bestdiff = off;
702 	TAILQ_FOREACH(lf, &linker_files, link) {
703 		if (LINKER_SEARCH_SYMBOL(lf, value, &es, &diff) != 0)
704 			continue;
705 		if (es != 0 && diff < bestdiff) {
706 			best = es;
707 			bestdiff = diff;
708 		}
709 		if (bestdiff == 0)
710 			break;
711 	}
712 	if (best) {
713 		*sym = best;
714 		*diffp = bestdiff;
715 		return (0);
716 	} else {
717 		*sym = 0;
718 		*diffp = off;
719 		return (ENOENT);
720 	}
721 }
722 
723 int
724 linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
725 {
726 	linker_file_t lf;
727 
728 	TAILQ_FOREACH(lf, &linker_files, link) {
729 		if (LINKER_SYMBOL_VALUES(lf, sym, symval) == 0)
730 			return (0);
731 	}
732 	return (ENOENT);
733 }
734 #endif
735 
736 /*
737  * Syscalls.
738  */
739 /*
740  * MPSAFE
741  */
742 int
743 kldload(struct thread *td, struct kldload_args *uap)
744 {
745 	char *kldname, *modname;
746 	char *pathname = NULL;
747 	linker_file_t lf;
748 	int error = 0;
749 
750 	td->td_retval[0] = -1;
751 
752 	mtx_lock(&Giant);
753 
754 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
755 		goto out;
756 
757 	if ((error = suser(td)) != 0)
758 		goto out;
759 
760 	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
761 	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
762 		goto out;
763 
764 	/*
765 	 * If path do not contain qualified name or any dot in it
766 	 * (kldname.ko, or kldname.ver.ko) treat it as interface
767 	 * name.
768 	 */
769 	if (index(pathname, '/') || index(pathname, '.')) {
770 		kldname = pathname;
771 		modname = NULL;
772 	} else {
773 		kldname = NULL;
774 		modname = pathname;
775 	}
776 	error = linker_load_module(kldname, modname, NULL, NULL, &lf);
777 	if (error)
778 		goto out;
779 
780 	lf->userrefs++;
781 	td->td_retval[0] = lf->id;
782 out:
783 	if (pathname)
784 		free(pathname, M_TEMP);
785 	mtx_unlock(&Giant);
786 	return (error);
787 }
788 
789 /*
790  * MPSAFE
791  */
792 static int
793 kern_kldunload(struct thread *td, int fileid, int flags)
794 {
795 	linker_file_t lf;
796 	int error = 0;
797 
798 	mtx_lock(&Giant);
799 
800 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
801 		goto out;
802 
803 	if ((error = suser(td)) != 0)
804 		goto out;
805 
806 	lf = linker_find_file_by_id(fileid);
807 	if (lf) {
808 		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
809 		if (lf->userrefs == 0) {
810 			/*
811 			 * XXX: maybe LINKER_UNLOAD_FORCE should override ?
812 			 */
813 			printf("kldunload: attempt to unload file that was"
814 			    " loaded by the kernel\n");
815 			error = EBUSY;
816 			goto out;
817 		}
818 		lf->userrefs--;
819 		error = linker_file_unload(lf, flags);
820 		if (error)
821 			lf->userrefs++;
822 	} else
823 		error = ENOENT;
824 out:
825 	mtx_unlock(&Giant);
826 	return (error);
827 }
828 
829 /*
830  * MPSAFE
831  */
832 int
833 kldunload(struct thread *td, struct kldunload_args *uap)
834 {
835 
836 	return (kern_kldunload(td, uap->fileid, LINKER_UNLOAD_NORMAL));
837 }
838 
839 /*
840  * MPSAFE
841  */
842 int
843 kldunloadf(struct thread *td, struct kldunloadf_args *uap)
844 {
845 
846 	if (uap->flags != LINKER_UNLOAD_NORMAL &&
847 	    uap->flags != LINKER_UNLOAD_FORCE)
848 		return (EINVAL);
849 	return (kern_kldunload(td, uap->fileid, uap->flags));
850 }
851 
852 /*
853  * MPSAFE
854  */
855 int
856 kldfind(struct thread *td, struct kldfind_args *uap)
857 {
858 	char *pathname;
859 	const char *filename;
860 	linker_file_t lf;
861 	int error = 0;
862 
863 #ifdef MAC
864 	error = mac_check_kld_stat(td->td_ucred);
865 	if (error)
866 		return (error);
867 #endif
868 
869 	mtx_lock(&Giant);
870 	td->td_retval[0] = -1;
871 
872 	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
873 	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
874 		goto out;
875 
876 	filename = linker_basename(pathname);
877 	lf = linker_find_file_by_name(filename);
878 	if (lf)
879 		td->td_retval[0] = lf->id;
880 	else
881 		error = ENOENT;
882 out:
883 	if (pathname)
884 		free(pathname, M_TEMP);
885 	mtx_unlock(&Giant);
886 	return (error);
887 }
888 
889 /*
890  * MPSAFE
891  */
892 int
893 kldnext(struct thread *td, struct kldnext_args *uap)
894 {
895 	linker_file_t lf;
896 	int error = 0;
897 
898 #ifdef MAC
899 	error = mac_check_kld_stat(td->td_ucred);
900 	if (error)
901 		return (error);
902 #endif
903 
904 	mtx_lock(&Giant);
905 
906 	if (uap->fileid == 0) {
907 		mtx_lock(&kld_mtx);
908 		if (TAILQ_FIRST(&linker_files))
909 			td->td_retval[0] = TAILQ_FIRST(&linker_files)->id;
910 		else
911 			td->td_retval[0] = 0;
912 		mtx_unlock(&kld_mtx);
913 		goto out;
914 	}
915 	lf = linker_find_file_by_id(uap->fileid);
916 	if (lf) {
917 		if (TAILQ_NEXT(lf, link))
918 			td->td_retval[0] = TAILQ_NEXT(lf, link)->id;
919 		else
920 			td->td_retval[0] = 0;
921 	} else
922 		error = ENOENT;
923 out:
924 	mtx_unlock(&Giant);
925 	return (error);
926 }
927 
928 /*
929  * MPSAFE
930  */
931 int
932 kldstat(struct thread *td, struct kldstat_args *uap)
933 {
934 	linker_file_t lf;
935 	int error = 0;
936 	int namelen, version;
937 	struct kld_file_stat *stat;
938 
939 #ifdef MAC
940 	error = mac_check_kld_stat(td->td_ucred);
941 	if (error)
942 		return (error);
943 #endif
944 
945 	mtx_lock(&Giant);
946 
947 	lf = linker_find_file_by_id(uap->fileid);
948 	if (lf == NULL) {
949 		error = ENOENT;
950 		goto out;
951 	}
952 	stat = uap->stat;
953 
954 	/*
955 	 * Check the version of the user's structure.
956 	 */
957 	if ((error = copyin(&stat->version, &version, sizeof(version))) != 0)
958 		goto out;
959 	if (version != sizeof(struct kld_file_stat)) {
960 		error = EINVAL;
961 		goto out;
962 	}
963 	namelen = strlen(lf->filename) + 1;
964 	if (namelen > MAXPATHLEN)
965 		namelen = MAXPATHLEN;
966 	if ((error = copyout(lf->filename, &stat->name[0], namelen)) != 0)
967 		goto out;
968 	if ((error = copyout(&lf->refs, &stat->refs, sizeof(int))) != 0)
969 		goto out;
970 	if ((error = copyout(&lf->id, &stat->id, sizeof(int))) != 0)
971 		goto out;
972 	if ((error = copyout(&lf->address, &stat->address,
973 	    sizeof(caddr_t))) != 0)
974 		goto out;
975 	if ((error = copyout(&lf->size, &stat->size, sizeof(size_t))) != 0)
976 		goto out;
977 
978 	td->td_retval[0] = 0;
979 out:
980 	mtx_unlock(&Giant);
981 	return (error);
982 }
983 
984 /*
985  * MPSAFE
986  */
987 int
988 kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
989 {
990 	linker_file_t lf;
991 	module_t mp;
992 	int error = 0;
993 
994 #ifdef MAC
995 	error = mac_check_kld_stat(td->td_ucred);
996 	if (error)
997 		return (error);
998 #endif
999 
1000 	mtx_lock(&Giant);
1001 	lf = linker_find_file_by_id(uap->fileid);
1002 	if (lf) {
1003 		MOD_SLOCK;
1004 		mp = TAILQ_FIRST(&lf->modules);
1005 		if (mp != NULL)
1006 			td->td_retval[0] = module_getid(mp);
1007 		else
1008 			td->td_retval[0] = 0;
1009 		MOD_SUNLOCK;
1010 	} else
1011 		error = ENOENT;
1012 	mtx_unlock(&Giant);
1013 	return (error);
1014 }
1015 
1016 /*
1017  * MPSAFE
1018  */
1019 int
1020 kldsym(struct thread *td, struct kldsym_args *uap)
1021 {
1022 	char *symstr = NULL;
1023 	c_linker_sym_t sym;
1024 	linker_symval_t symval;
1025 	linker_file_t lf;
1026 	struct kld_sym_lookup lookup;
1027 	int error = 0;
1028 
1029 #ifdef MAC
1030 	error = mac_check_kld_stat(td->td_ucred);
1031 	if (error)
1032 		return (error);
1033 #endif
1034 
1035 	mtx_lock(&Giant);
1036 
1037 	if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
1038 		goto out;
1039 	if (lookup.version != sizeof(lookup) ||
1040 	    uap->cmd != KLDSYM_LOOKUP) {
1041 		error = EINVAL;
1042 		goto out;
1043 	}
1044 	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1045 	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
1046 		goto out;
1047 	if (uap->fileid != 0) {
1048 		lf = linker_find_file_by_id(uap->fileid);
1049 		if (lf == NULL) {
1050 			error = ENOENT;
1051 			goto out;
1052 		}
1053 		if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1054 		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1055 			lookup.symvalue = (uintptr_t) symval.value;
1056 			lookup.symsize = symval.size;
1057 			error = copyout(&lookup, uap->data, sizeof(lookup));
1058 		} else
1059 			error = ENOENT;
1060 	} else {
1061 		mtx_lock(&kld_mtx);
1062 		TAILQ_FOREACH(lf, &linker_files, link) {
1063 			if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1064 			    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1065 				lookup.symvalue = (uintptr_t)symval.value;
1066 				lookup.symsize = symval.size;
1067 				error = copyout(&lookup, uap->data,
1068 				    sizeof(lookup));
1069 				break;
1070 			}
1071 		}
1072 		mtx_unlock(&kld_mtx);
1073 		if (lf == NULL)
1074 			error = ENOENT;
1075 	}
1076 out:
1077 	if (symstr)
1078 		free(symstr, M_TEMP);
1079 	mtx_unlock(&Giant);
1080 	return (error);
1081 }
1082 
1083 /*
1084  * Preloaded module support
1085  */
1086 
1087 static modlist_t
1088 modlist_lookup(const char *name, int ver)
1089 {
1090 	modlist_t mod;
1091 
1092 	TAILQ_FOREACH(mod, &found_modules, link) {
1093 		if (strcmp(mod->name, name) == 0 &&
1094 		    (ver == 0 || mod->version == ver))
1095 			return (mod);
1096 	}
1097 	return (NULL);
1098 }
1099 
1100 static modlist_t
1101 modlist_lookup2(const char *name, struct mod_depend *verinfo)
1102 {
1103 	modlist_t mod, bestmod;
1104 	int ver;
1105 
1106 	if (verinfo == NULL)
1107 		return (modlist_lookup(name, 0));
1108 	bestmod = NULL;
1109 	for (mod = TAILQ_FIRST(&found_modules); mod;
1110 	    mod = TAILQ_NEXT(mod, link)) {
1111 		if (strcmp(mod->name, name) != 0)
1112 			continue;
1113 		ver = mod->version;
1114 		if (ver == verinfo->md_ver_preferred)
1115 			return (mod);
1116 		if (ver >= verinfo->md_ver_minimum &&
1117 		    ver <= verinfo->md_ver_maximum &&
1118 		    (bestmod == NULL || ver > bestmod->version))
1119 			bestmod = mod;
1120 	}
1121 	return (bestmod);
1122 }
1123 
1124 static modlist_t
1125 modlist_newmodule(const char *modname, int version, linker_file_t container)
1126 {
1127 	modlist_t mod;
1128 
1129 	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1130 	if (mod == NULL)
1131 		panic("no memory for module list");
1132 	mod->container = container;
1133 	mod->name = modname;
1134 	mod->version = version;
1135 	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1136 	return (mod);
1137 }
1138 
1139 static void
1140 linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1141     struct mod_metadata **stop, int preload)
1142 {
1143 	struct mod_metadata *mp, **mdp;
1144 	const char *modname;
1145 	int ver;
1146 
1147 	for (mdp = start; mdp < stop; mdp++) {
1148 		mp = *mdp;
1149 		if (mp->md_type != MDT_VERSION)
1150 			continue;
1151 		modname = mp->md_cval;
1152 		ver = ((struct mod_version *)mp->md_data)->mv_version;
1153 		if (modlist_lookup(modname, ver) != NULL) {
1154 			printf("module %s already present!\n", modname);
1155 			/* XXX what can we do? this is a build error. :-( */
1156 			continue;
1157 		}
1158 		modlist_newmodule(modname, ver, lf);
1159 	}
1160 }
1161 
1162 static void
1163 linker_preload(void *arg)
1164 {
1165 	caddr_t modptr;
1166 	const char *modname, *nmodname;
1167 	char *modtype;
1168 	linker_file_t lf;
1169 	linker_class_t lc;
1170 	int error;
1171 	linker_file_list_t loaded_files;
1172 	linker_file_list_t depended_files;
1173 	struct mod_metadata *mp, *nmp;
1174 	struct mod_metadata **start, **stop, **mdp, **nmdp;
1175 	struct mod_depend *verinfo;
1176 	int nver;
1177 	int resolves;
1178 	modlist_t mod;
1179 	struct sysinit **si_start, **si_stop;
1180 
1181 	TAILQ_INIT(&loaded_files);
1182 	TAILQ_INIT(&depended_files);
1183 	TAILQ_INIT(&found_modules);
1184 	error = 0;
1185 
1186 	modptr = NULL;
1187 	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1188 		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1189 		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1190 		if (modname == NULL) {
1191 			printf("Preloaded module at %p does not have a"
1192 			    " name!\n", modptr);
1193 			continue;
1194 		}
1195 		if (modtype == NULL) {
1196 			printf("Preloaded module at %p does not have a type!\n",
1197 			    modptr);
1198 			continue;
1199 		}
1200 		if (bootverbose)
1201 			printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1202 			    modptr);
1203 		lf = NULL;
1204 		TAILQ_FOREACH(lc, &classes, link) {
1205 			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1206 			if (error) {
1207 				lf = NULL;
1208 				break;
1209 			}
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