xref: /freebsd/sys/kern/kern_linker.c (revision dba6dd177bdee890cf445fbe21a5dccefd5de18e)
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)
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)) != 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]);
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 int
793 kldunload(struct thread *td, struct kldunload_args *uap)
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(uap->fileid);
807 	if (lf) {
808 		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
809 		if (lf->userrefs == 0) {
810 			printf("kldunload: attempt to unload file that was"
811 			    " loaded by the kernel\n");
812 			error = EBUSY;
813 			goto out;
814 		}
815 		lf->userrefs--;
816 		error = linker_file_unload(lf);
817 		if (error)
818 			lf->userrefs++;
819 	} else
820 		error = ENOENT;
821 out:
822 	mtx_unlock(&Giant);
823 	return (error);
824 }
825 
826 /*
827  * MPSAFE
828  */
829 int
830 kldfind(struct thread *td, struct kldfind_args *uap)
831 {
832 	char *pathname;
833 	const char *filename;
834 	linker_file_t lf;
835 	int error = 0;
836 
837 #ifdef MAC
838 	error = mac_check_kld_stat(td->td_ucred);
839 	if (error)
840 		return (error);
841 #endif
842 
843 	mtx_lock(&Giant);
844 	td->td_retval[0] = -1;
845 
846 	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
847 	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
848 		goto out;
849 
850 	filename = linker_basename(pathname);
851 	lf = linker_find_file_by_name(filename);
852 	if (lf)
853 		td->td_retval[0] = lf->id;
854 	else
855 		error = ENOENT;
856 out:
857 	if (pathname)
858 		free(pathname, M_TEMP);
859 	mtx_unlock(&Giant);
860 	return (error);
861 }
862 
863 /*
864  * MPSAFE
865  */
866 int
867 kldnext(struct thread *td, struct kldnext_args *uap)
868 {
869 	linker_file_t lf;
870 	int error = 0;
871 
872 #ifdef MAC
873 	error = mac_check_kld_stat(td->td_ucred);
874 	if (error)
875 		return (error);
876 #endif
877 
878 	mtx_lock(&Giant);
879 
880 	if (uap->fileid == 0) {
881 		mtx_lock(&kld_mtx);
882 		if (TAILQ_FIRST(&linker_files))
883 			td->td_retval[0] = TAILQ_FIRST(&linker_files)->id;
884 		else
885 			td->td_retval[0] = 0;
886 		mtx_unlock(&kld_mtx);
887 		goto out;
888 	}
889 	lf = linker_find_file_by_id(uap->fileid);
890 	if (lf) {
891 		if (TAILQ_NEXT(lf, link))
892 			td->td_retval[0] = TAILQ_NEXT(lf, link)->id;
893 		else
894 			td->td_retval[0] = 0;
895 	} else
896 		error = ENOENT;
897 out:
898 	mtx_unlock(&Giant);
899 	return (error);
900 }
901 
902 /*
903  * MPSAFE
904  */
905 int
906 kldstat(struct thread *td, struct kldstat_args *uap)
907 {
908 	linker_file_t lf;
909 	int error = 0;
910 	int namelen, version;
911 	struct kld_file_stat *stat;
912 
913 #ifdef MAC
914 	error = mac_check_kld_stat(td->td_ucred);
915 	if (error)
916 		return (error);
917 #endif
918 
919 	mtx_lock(&Giant);
920 
921 	lf = linker_find_file_by_id(uap->fileid);
922 	if (lf == NULL) {
923 		error = ENOENT;
924 		goto out;
925 	}
926 	stat = uap->stat;
927 
928 	/*
929 	 * Check the version of the user's structure.
930 	 */
931 	if ((error = copyin(&stat->version, &version, sizeof(version))) != 0)
932 		goto out;
933 	if (version != sizeof(struct kld_file_stat)) {
934 		error = EINVAL;
935 		goto out;
936 	}
937 	namelen = strlen(lf->filename) + 1;
938 	if (namelen > MAXPATHLEN)
939 		namelen = MAXPATHLEN;
940 	if ((error = copyout(lf->filename, &stat->name[0], namelen)) != 0)
941 		goto out;
942 	if ((error = copyout(&lf->refs, &stat->refs, sizeof(int))) != 0)
943 		goto out;
944 	if ((error = copyout(&lf->id, &stat->id, sizeof(int))) != 0)
945 		goto out;
946 	if ((error = copyout(&lf->address, &stat->address,
947 	    sizeof(caddr_t))) != 0)
948 		goto out;
949 	if ((error = copyout(&lf->size, &stat->size, sizeof(size_t))) != 0)
950 		goto out;
951 
952 	td->td_retval[0] = 0;
953 out:
954 	mtx_unlock(&Giant);
955 	return (error);
956 }
957 
958 /*
959  * MPSAFE
960  */
961 int
962 kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
963 {
964 	linker_file_t lf;
965 	module_t mp;
966 	int error = 0;
967 
968 #ifdef MAC
969 	error = mac_check_kld_stat(td->td_ucred);
970 	if (error)
971 		return (error);
972 #endif
973 
974 	mtx_lock(&Giant);
975 	lf = linker_find_file_by_id(uap->fileid);
976 	if (lf) {
977 		MOD_SLOCK;
978 		mp = TAILQ_FIRST(&lf->modules);
979 		if (mp != NULL)
980 			td->td_retval[0] = module_getid(mp);
981 		else
982 			td->td_retval[0] = 0;
983 		MOD_SUNLOCK;
984 	} else
985 		error = ENOENT;
986 	mtx_unlock(&Giant);
987 	return (error);
988 }
989 
990 /*
991  * MPSAFE
992  */
993 int
994 kldsym(struct thread *td, struct kldsym_args *uap)
995 {
996 	char *symstr = NULL;
997 	c_linker_sym_t sym;
998 	linker_symval_t symval;
999 	linker_file_t lf;
1000 	struct kld_sym_lookup lookup;
1001 	int error = 0;
1002 
1003 #ifdef MAC
1004 	error = mac_check_kld_stat(td->td_ucred);
1005 	if (error)
1006 		return (error);
1007 #endif
1008 
1009 	mtx_lock(&Giant);
1010 
1011 	if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
1012 		goto out;
1013 	if (lookup.version != sizeof(lookup) ||
1014 	    uap->cmd != KLDSYM_LOOKUP) {
1015 		error = EINVAL;
1016 		goto out;
1017 	}
1018 	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1019 	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
1020 		goto out;
1021 	if (uap->fileid != 0) {
1022 		lf = linker_find_file_by_id(uap->fileid);
1023 		if (lf == NULL) {
1024 			error = ENOENT;
1025 			goto out;
1026 		}
1027 		if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1028 		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1029 			lookup.symvalue = (uintptr_t) symval.value;
1030 			lookup.symsize = symval.size;
1031 			error = copyout(&lookup, uap->data, sizeof(lookup));
1032 		} else
1033 			error = ENOENT;
1034 	} else {
1035 		mtx_lock(&kld_mtx);
1036 		TAILQ_FOREACH(lf, &linker_files, link) {
1037 			if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1038 			    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1039 				lookup.symvalue = (uintptr_t)symval.value;
1040 				lookup.symsize = symval.size;
1041 				error = copyout(&lookup, uap->data,
1042 				    sizeof(lookup));
1043 				break;
1044 			}
1045 		}
1046 		mtx_unlock(&kld_mtx);
1047 		if (lf == NULL)
1048 			error = ENOENT;
1049 	}
1050 out:
1051 	if (symstr)
1052 		free(symstr, M_TEMP);
1053 	mtx_unlock(&Giant);
1054 	return (error);
1055 }
1056 
1057 /*
1058  * Preloaded module support
1059  */
1060 
1061 static modlist_t
1062 modlist_lookup(const char *name, int ver)
1063 {
1064 	modlist_t mod;
1065 
1066 	TAILQ_FOREACH(mod, &found_modules, link) {
1067 		if (strcmp(mod->name, name) == 0 &&
1068 		    (ver == 0 || mod->version == ver))
1069 			return (mod);
1070 	}
1071 	return (NULL);
1072 }
1073 
1074 static modlist_t
1075 modlist_lookup2(const char *name, struct mod_depend *verinfo)
1076 {
1077 	modlist_t mod, bestmod;
1078 	int ver;
1079 
1080 	if (verinfo == NULL)
1081 		return (modlist_lookup(name, 0));
1082 	bestmod = NULL;
1083 	for (mod = TAILQ_FIRST(&found_modules); mod;
1084 	    mod = TAILQ_NEXT(mod, link)) {
1085 		if (strcmp(mod->name, name) != 0)
1086 			continue;
1087 		ver = mod->version;
1088 		if (ver == verinfo->md_ver_preferred)
1089 			return (mod);
1090 		if (ver >= verinfo->md_ver_minimum &&
1091 		    ver <= verinfo->md_ver_maximum &&
1092 		    (bestmod == NULL || ver > bestmod->version))
1093 			bestmod = mod;
1094 	}
1095 	return (bestmod);
1096 }
1097 
1098 static modlist_t
1099 modlist_newmodule(const char *modname, int version, linker_file_t container)
1100 {
1101 	modlist_t mod;
1102 
1103 	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1104 	if (mod == NULL)
1105 		panic("no memory for module list");
1106 	mod->container = container;
1107 	mod->name = modname;
1108 	mod->version = version;
1109 	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1110 	return (mod);
1111 }
1112 
1113 static void
1114 linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1115     struct mod_metadata **stop, int preload)
1116 {
1117 	struct mod_metadata *mp, **mdp;
1118 	const char *modname;
1119 	int ver;
1120 
1121 	for (mdp = start; mdp < stop; mdp++) {
1122 		mp = *mdp;
1123 		if (mp->md_type != MDT_VERSION)
1124 			continue;
1125 		modname = mp->md_cval;
1126 		ver = ((struct mod_version *)mp->md_data)->mv_version;
1127 		if (modlist_lookup(modname, ver) != NULL) {
1128 			printf("module %s already present!\n", modname);
1129 			/* XXX what can we do? this is a build error. :-( */
1130 			continue;
1131 		}
1132 		modlist_newmodule(modname, ver, lf);
1133 	}
1134 }
1135 
1136 static void
1137 linker_preload(void *arg)
1138 {
1139 	caddr_t modptr;
1140 	const char *modname, *nmodname;
1141 	char *modtype;
1142 	linker_file_t lf;
1143 	linker_class_t lc;
1144 	int error;
1145 	linker_file_list_t loaded_files;
1146 	linker_file_list_t depended_files;
1147 	struct mod_metadata *mp, *nmp;
1148 	struct mod_metadata **start, **stop, **mdp, **nmdp;
1149 	struct mod_depend *verinfo;
1150 	int nver;
1151 	int resolves;
1152 	modlist_t mod;
1153 	struct sysinit **si_start, **si_stop;
1154 
1155 	TAILQ_INIT(&loaded_files);
1156 	TAILQ_INIT(&depended_files);
1157 	TAILQ_INIT(&found_modules);
1158 	error = 0;
1159 
1160 	modptr = NULL;
1161 	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1162 		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1163 		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1164 		if (modname == NULL) {
1165 			printf("Preloaded module at %p does not have a"
1166 			    " name!\n", modptr);
1167 			continue;
1168 		}
1169 		if (modtype == NULL) {
1170 			printf("Preloaded module at %p does not have a type!\n",
1171 			    modptr);
1172 			continue;
1173 		}
1174 		printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1175 		    modptr);
1176 		lf = NULL;
1177 		TAILQ_FOREACH(lc, &classes, link) {
1178 			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1179 			if (error) {
1180 				lf = NULL;
1181 				break;
1182 			}
1183 		}
1184 		if (lf)
1185 			TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1186 	}
1187 
1188 	/*
1189 	 * First get a list of stuff in the kernel.
1190 	 */
1191 	if (linker_file_lookup_set(linker_kernel_file, MDT_SETNAME, &start,
1192 	    &stop, NULL) == 0)
1193 		linker_addmodules(linker_kernel_file, start, stop, 1);
1194 
1195 	/*
1196 	 * this is a once-off kinky bubble sort resolve relocation dependency
1197 	 * requirements
1198 	 */
1199 restart:
1200 	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1201 		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1202 		    &stop, NULL);
1203 		/*
1204 		 * First, look to see if we would successfully link with this
1205 		 * stuff.
1206 		 */
1207 		resolves = 1;	/* unless we know otherwise */
1208 		if (!error) {
1209 			for (mdp = start; mdp < stop; mdp++) {
1210 				mp = *mdp;
1211 				if (mp->md_type != MDT_DEPEND)
1212 					continue;
1213 				modname = mp->md_cval;
1214 				verinfo = mp->md_data;
1215 				for (nmdp = start; nmdp < stop; nmdp++) {
1216 					nmp = *nmdp;
1217 					if (nmp->md_type != MDT_VERSION)
1218 						continue;
1219 					nmodname = nmp->md_cval;
1220 					if (strcmp(modname, nmodname) == 0)
1221 						break;
1222 				}
1223 				if (nmdp < stop)   /* it's a self reference */
1224 					continue;
1225 
1226 				/*
1227 				 * ok, the module isn't here yet, we
1228 				 * are not finished
1229 				 */
1230 				if (modlist_lookup2(modname, verinfo) == NULL)
1231 					resolves = 0;
1232 			}
1233 		}
1234 		/*
1235 		 * OK, if we found our modules, we can link.  So, "provide"
1236 		 * the modules inside and add it to the end of the link order
1237 		 * list.
1238 		 */
1239 		if (resolves) {
1240 			if (!error) {
1241 				for (mdp = start; mdp < stop; mdp++) {
1242 					mp = *mdp;
1243 					if (mp->md_type != MDT_VERSION)
1244 						continue;
1245 					modname = mp->md_cval;
1246 					nver = ((struct mod_version *)
1247 					    mp->md_data)->mv_version;
1248 					if (modlist_lookup(modname,
1249 					    nver) != NULL) {
1250 						printf("module %s already"
1251 						    " present!\n", modname);
1252 						linker_file_unload(lf);
1253 						TAILQ_REMOVE(&loaded_files,
1254 						    lf, loaded);
1255 						/* we changed tailq next ptr */
1256 						goto restart;
1257 					}
1258 					modlist_newmodule(modname, nver, lf);
1259 				}
1260 			}
1261 			TAILQ_REMOVE(&loaded_files, lf, loaded);
1262 			TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1263 			/*
1264 			 * Since we provided modules, we need to restart the
1265 			 * sort so that the previous files that depend on us
1266 			 * have a chance. Also, we've busted the tailq next
1267 			 * pointer with the REMOVE.
1268 			 */
1269 			goto restart;
1270 		}
1271 	}
1272 
1273 	/*
1274 	 * At this point, we check to see what could not be resolved..
1275 	 */
1276 	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1277 		printf("KLD file %s is missing dependencies\n", lf->filename);
1278 		linker_file_unload(lf);
1279 		TAILQ_REMOVE(&loaded_files, lf, loaded);
1280 	}
1281 
1282 	/*
1283 	 * We made it. Finish off the linking in the order we determined.
1284 	 */
1285 	TAILQ_FOREACH(lf, &depended_files, loaded) {
1286 		if (linker_kernel_file) {
1287 			linker_kernel_file->refs++;
1288 			error = linker_file_add_dependency(lf,
1289 			    linker_kernel_file);
1290 			if (error)
1291 				panic("cannot add dependency");
1292 		}
1293 		lf->userrefs++;	/* so we can (try to) kldunload it */
1294 		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1295 		    &stop, NULL);
1296 		if (!error) {
1297 			for (mdp = start; mdp < stop; mdp++) {
1298 				mp = *mdp;
1299 				if (mp->md_type != MDT_DEPEND)
1300 					continue;
1301 				modname = mp->md_cval;
1302 				verinfo = mp->md_data;
1303 				mod = modlist_lookup2(modname, verinfo);
1304 				mod->container->refs++;
1305 				error = linker_file_add_dependency(lf,
1306 				    mod->container);
1307 				if (error)
1308 					panic("cannot add dependency");
1309 			}
1310 		}
1311 		/*
1312 		 * Now do relocation etc using the symbol search paths
1313 		 * established by the dependencies
1314 		 */
1315 		error = LINKER_LINK_PRELOAD_FINISH(lf);
1316 		if (error) {
1317 			printf("KLD file %s - could not finalize loading\n",
1318 			    lf->filename);
1319 			linker_file_unload(lf);
1320 			continue;
1321 		}
1322 		linker_file_register_modules(lf);
1323 		if (linker_file_lookup_set(lf, "sysinit_set", &si_start,
1324 		    &si_stop, NULL) == 0)
1325 			sysinit_add(si_start, si_stop);
1326 		linker_file_register_sysctls(lf);
1327 		lf->flags |= LINKER_FILE_LINKED;
1328 	}
1329 	/* woohoo! we made it! */
1330 }
1331 
1332 SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, 0)
1333 
1334 /*
1335  * Search for a not-loaded module by name.
1336  *
1337  * Modules may be found in the following locations:
1338  *
1339  * - preloaded (result is just the module name) - on disk (result is full path
1340  * to module)
1341  *
1342  * If the module name is qualified in any way (contains path, etc.) the we
1343  * simply return a copy of it.
1344  *
1345  * The search path can be manipulated via sysctl.  Note that we use the ';'
1346  * character as a separator to be consistent with the bootloader.
1347  */
1348 
1349 static char linker_hintfile[] = "linker.hints";
1350 static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules";
1351 
1352 SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RW, linker_path,
1353     sizeof(linker_path), "module load search path");
1354 
1355 TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1356 
1357 static char *linker_ext_list[] = {
1358 	"",
1359 	".ko",
1360 	NULL
1361 };
1362 
1363 /*
1364  * Check if file actually exists either with or without extension listed in
1365  * the linker_ext_list. (probably should be generic for the rest of the
1366  * kernel)
1367  */
1368 static char *
1369 linker_lookup_file(const char *path, int pathlen, const char *name,
1370     int namelen, struct vattr *vap)
1371 {
1372 	struct nameidata nd;
1373 	struct thread *td = curthread;	/* XXX */
1374 	char *result, **cpp, *sep;
1375 	int error, len, extlen, reclen, flags;
1376 	enum vtype type;
1377 
1378 	extlen = 0;
1379 	for (cpp = linker_ext_list; *cpp; cpp++) {
1380 		len = strlen(*cpp);
1381 		if (len > extlen)
1382 			extlen = len;
1383 	}
1384 	extlen++;		/* trailing '\0' */
1385 	sep = (path[pathlen - 1] != '/') ? "/" : "";
1386 
1387 	reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1388 	result = malloc(reclen, M_LINKER, M_WAITOK);
1389 	for (cpp = linker_ext_list; *cpp; cpp++) {
1390 		snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1391 		    namelen, name, *cpp);
1392 		/*
1393 		 * Attempt to open the file, and return the path if
1394 		 * we succeed and it's a regular file.
1395 		 */
1396 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, result, td);
1397 		flags = FREAD;
1398 		error = vn_open(&nd, &flags, 0, -1);
1399 		if (error == 0) {
1400 			NDFREE(&nd, NDF_ONLY_PNBUF);
1401 			type = nd.ni_vp->v_type;
1402 			if (vap)
1403 				VOP_GETATTR(nd.ni_vp, vap, td->td_ucred, td);
1404 			VOP_UNLOCK(nd.ni_vp, 0, td);
1405 			vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1406 			if (type == VREG)
1407 				return (result);
1408 		}
1409 	}
1410 	free(result, M_LINKER);
1411 	return (NULL);
1412 }
1413 
1414 #define	INT_ALIGN(base, ptr)	ptr =					\
1415 	(base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
1416 
1417 /*
1418  * Lookup KLD which contains requested module in the "linker.hints" file. If
1419  * version specification is available, then try to find the best KLD.
1420  * Otherwise just find the latest one.
1421  */
1422 static char *
1423 linker_hints_lookup(const char *path, int pathlen, const char *modname,
1424     int modnamelen, struct mod_depend *verinfo)
1425 {
1426 	struct thread *td = curthread;	/* XXX */
1427 	struct ucred *cred = td ? td->td_ucred : NULL;
1428 	struct nameidata nd;
1429 	struct vattr vattr, mattr;
1430 	u_char *hints = NULL;
1431 	u_char *cp, *recptr, *bufend, *result, *best, *pathbuf, *sep;
1432 	int error, ival, bestver, *intp, reclen, found, flags, clen, blen;
1433 
1434 	result = NULL;
1435 	bestver = found = 0;
1436 
1437 	sep = (path[pathlen - 1] != '/') ? "/" : "";
1438 	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1439 	    strlen(sep) + 1;
1440 	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1441 	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1442 	    linker_hintfile);
1443 
1444 	NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, pathbuf, td);
1445 	flags = FREAD;
1446 	error = vn_open(&nd, &flags, 0, -1);
1447 	if (error)
1448 		goto bad;
1449 	NDFREE(&nd, NDF_ONLY_PNBUF);
1450 	if (nd.ni_vp->v_type != VREG)
1451 		goto bad;
1452 	best = cp = NULL;
1453 	error = VOP_GETATTR(nd.ni_vp, &vattr, cred, td);
1454 	if (error)
1455 		goto bad;
1456 	/*
1457 	 * XXX: we need to limit this number to some reasonable value
1458 	 */
1459 	if (vattr.va_size > 100 * 1024) {
1460 		printf("hints file too large %ld\n", (long)vattr.va_size);
1461 		goto bad;
1462 	}
1463 	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
1464 	if (hints == NULL)
1465 		goto bad;
1466 	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
1467 	    UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
1468 	if (error)
1469 		goto bad;
1470 	VOP_UNLOCK(nd.ni_vp, 0, td);
1471 	vn_close(nd.ni_vp, FREAD, cred, td);
1472 	nd.ni_vp = NULL;
1473 	if (reclen != 0) {
1474 		printf("can't read %d\n", reclen);
1475 		goto bad;
1476 	}
1477 	intp = (int *)hints;
1478 	ival = *intp++;
1479 	if (ival != LINKER_HINTS_VERSION) {
1480 		printf("hints file version mismatch %d\n", ival);
1481 		goto bad;
1482 	}
1483 	bufend = hints + vattr.va_size;
1484 	recptr = (u_char *)intp;
1485 	clen = blen = 0;
1486 	while (recptr < bufend && !found) {
1487 		intp = (int *)recptr;
1488 		reclen = *intp++;
1489 		ival = *intp++;
1490 		cp = (char *)intp;
1491 		switch (ival) {
1492 		case MDT_VERSION:
1493 			clen = *cp++;
1494 			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1495 				break;
1496 			cp += clen;
1497 			INT_ALIGN(hints, cp);
1498 			ival = *(int *)cp;
1499 			cp += sizeof(int);
1500 			clen = *cp++;
1501 			if (verinfo == NULL ||
1502 			    ival == verinfo->md_ver_preferred) {
1503 				found = 1;
1504 				break;
1505 			}
1506 			if (ival >= verinfo->md_ver_minimum &&
1507 			    ival <= verinfo->md_ver_maximum &&
1508 			    ival > bestver) {
1509 				bestver = ival;
1510 				best = cp;
1511 				blen = clen;
1512 			}
1513 			break;
1514 		default:
1515 			break;
1516 		}
1517 		recptr += reclen + sizeof(int);
1518 	}
1519 	/*
1520 	 * Finally check if KLD is in the place
1521 	 */
1522 	if (found)
1523 		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
1524 	else if (best)
1525 		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
1526 
1527 	/*
1528 	 * KLD is newer than hints file. What we should do now?
1529 	 */
1530 	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
1531 		printf("warning: KLD '%s' is newer than the linker.hints"
1532 		    " file\n", result);
1533 bad:
1534 	free(pathbuf, M_LINKER);
1535 	if (hints)
1536 		free(hints, M_TEMP);
1537 	if (nd.ni_vp != NULL) {
1538 		VOP_UNLOCK(nd.ni_vp, 0, td);
1539 		vn_close(nd.ni_vp, FREAD, cred, td);
1540 	}
1541 	/*
1542 	 * If nothing found or hints is absent - fallback to the old
1543 	 * way by using "kldname[.ko]" as module name.
1544 	 */
1545 	if (!found && !bestver && result == NULL)
1546 		result = linker_lookup_file(path, pathlen, modname,
1547 		    modnamelen, NULL);
1548 	return (result);
1549 }
1550 
1551 /*
1552  * Lookup KLD which contains requested module in the all directories.
1553  */
1554 static char *
1555 linker_search_module(const char *modname, int modnamelen,
1556     struct mod_depend *verinfo)
1557 {
1558 	char *cp, *ep, *result;
1559 
1560 	/*
1561 	 * traverse the linker path
1562 	 */
1563 	for (cp = linker_path; *cp; cp = ep + 1) {
1564 		/* find the end of this component */
1565 		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
1566 		result = linker_hints_lookup(cp, ep - cp, modname,
1567 		    modnamelen, verinfo);
1568 		if (result != NULL)
1569 			return (result);
1570 		if (*ep == 0)
1571 			break;
1572 	}
1573 	return (NULL);
1574 }
1575 
1576 /*
1577  * Search for module in all directories listed in the linker_path.
1578  */
1579 static char *
1580 linker_search_kld(const char *name)
1581 {
1582 	char *cp, *ep, *result, **cpp;
1583 	int extlen, len;
1584 
1585 	/* qualified at all? */
1586 	if (index(name, '/'))
1587 		return (linker_strdup(name));
1588 
1589 	extlen = 0;
1590 	for (cpp = linker_ext_list; *cpp; cpp++) {
1591 		len = strlen(*cpp);
1592 		if (len > extlen)
1593 			extlen = len;
1594 	}
1595 	extlen++;		/* trailing '\0' */
1596 
1597 	/* traverse the linker path */
1598 	len = strlen(name);
1599 	for (ep = linker_path; *ep; ep++) {
1600 		cp = ep;
1601 		/* find the end of this component */
1602 		for (; *ep != 0 && *ep != ';'; ep++);
1603 		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
1604 		if (result != NULL)
1605 			return (result);
1606 	}
1607 	return (NULL);
1608 }
1609 
1610 static const char *
1611 linker_basename(const char *path)
1612 {
1613 	const char *filename;
1614 
1615 	filename = rindex(path, '/');
1616 	if (filename == NULL)
1617 		return path;
1618 	if (filename[1])
1619 		filename++;
1620 	return (filename);
1621 }
1622 
1623 /*
1624  * Find a file which contains given module and load it, if "parent" is not
1625  * NULL, register a reference to it.
1626  */
1627 int
1628 linker_load_module(const char *kldname, const char *modname,
1629     struct linker_file *parent, struct mod_depend *verinfo,
1630     struct linker_file **lfpp)
1631 {
1632 	linker_file_t lfdep;
1633 	const char *filename;
1634 	char *pathname;
1635 	int error;
1636 
1637 	if (modname == NULL) {
1638 		/*
1639  		 * We have to load KLD
1640  		 */
1641 		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
1642 		    " is not NULL"));
1643 		pathname = linker_search_kld(kldname);
1644 	} else {
1645 		if (modlist_lookup2(modname, verinfo) != NULL)
1646 			return (EEXIST);
1647 		if (kldname != NULL)
1648 			pathname = linker_strdup(kldname);
1649 		else if (rootvnode == NULL)
1650 			pathname = NULL;
1651 		else
1652 			/*
1653 			 * Need to find a KLD with required module
1654 			 */
1655 			pathname = linker_search_module(modname,
1656 			    strlen(modname), verinfo);
1657 	}
1658 	if (pathname == NULL)
1659 		return (ENOENT);
1660 
1661 	/*
1662 	 * Can't load more than one file with the same basename XXX:
1663 	 * Actually it should be possible to have multiple KLDs with
1664 	 * the same basename but different path because they can
1665 	 * provide different versions of the same modules.
1666 	 */
1667 	filename = linker_basename(pathname);
1668 	if (linker_find_file_by_name(filename)) {
1669 		error = EEXIST;
1670 		goto out;
1671 	}
1672 	do {
1673 		error = linker_load_file(pathname, &lfdep);
1674 		if (error)
1675 			break;
1676 		if (modname && verinfo &&
1677 		    modlist_lookup2(modname, verinfo) == NULL) {
1678 			linker_file_unload(lfdep);
1679 			error = ENOENT;
1680 			break;
1681 		}
1682 		if (parent) {
1683 			error = linker_file_add_dependency(parent, lfdep);
1684 			if (error)
1685 				break;
1686 		}
1687 		if (lfpp)
1688 			*lfpp = lfdep;
1689 	} while (0);
1690 out:
1691 	if (pathname)
1692 		free(pathname, M_LINKER);
1693 	return (error);
1694 }
1695 
1696 /*
1697  * This routine is responsible for finding dependencies of userland initiated
1698  * kldload(2)'s of files.
1699  */
1700 int
1701 linker_load_dependencies(linker_file_t lf)
1702 {
1703 	linker_file_t lfdep;
1704 	struct mod_metadata **start, **stop, **mdp, **nmdp;
1705 	struct mod_metadata *mp, *nmp;
1706 	struct mod_depend *verinfo;
1707 	modlist_t mod;
1708 	const char *modname, *nmodname;
1709 	int ver, error = 0, count;
1710 
1711 	/*
1712 	 * All files are dependant on /kernel.
1713 	 */
1714 	if (linker_kernel_file) {
1715 		linker_kernel_file->refs++;
1716 		error = linker_file_add_dependency(lf, linker_kernel_file);
1717 		if (error)
1718 			return (error);
1719 	}
1720 	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
1721 	    &count) != 0)
1722 		return (0);
1723 	for (mdp = start; mdp < stop; mdp++) {
1724 		mp = *mdp;
1725 		if (mp->md_type != MDT_VERSION)
1726 			continue;
1727 		modname = mp->md_cval;
1728 		ver = ((struct mod_version *)mp->md_data)->mv_version;
1729 		mod = modlist_lookup(modname, ver);
1730 		if (mod != NULL) {
1731 			printf("interface %s.%d already present in the KLD"
1732 			    " '%s'!\n", modname, ver,
1733 			    mod->container->filename);
1734 			return (EEXIST);
1735 		}
1736 	}
1737 
1738 	for (mdp = start; mdp < stop; mdp++) {
1739 		mp = *mdp;
1740 		if (mp->md_type != MDT_DEPEND)
1741 			continue;
1742 		modname = mp->md_cval;
1743 		verinfo = mp->md_data;
1744 		nmodname = NULL;
1745 		for (nmdp = start; nmdp < stop; nmdp++) {
1746 			nmp = *nmdp;
1747 			if (nmp->md_type != MDT_VERSION)
1748 				continue;
1749 			nmodname = nmp->md_cval;
1750 			if (strcmp(modname, nmodname) == 0)
1751 				break;
1752 		}
1753 		if (nmdp < stop)/* early exit, it's a self reference */
1754 			continue;
1755 		mod = modlist_lookup2(modname, verinfo);
1756 		if (mod) {	/* woohoo, it's loaded already */
1757 			lfdep = mod->container;
1758 			lfdep->refs++;
1759 			error = linker_file_add_dependency(lf, lfdep);
1760 			if (error)
1761 				break;
1762 			continue;
1763 		}
1764 		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
1765 		if (error) {
1766 			printf("KLD %s: depends on %s - not available\n",
1767 			    lf->filename, modname);
1768 			break;
1769 		}
1770 	}
1771 
1772 	if (error)
1773 		return (error);
1774 	linker_addmodules(lf, start, stop, 0);
1775 	return (error);
1776 }
1777 
1778 static int
1779 sysctl_kern_function_list_iterate(const char *name, void *opaque)
1780 {
1781 	struct sysctl_req *req;
1782 
1783 	req = opaque;
1784 	return (SYSCTL_OUT(req, name, strlen(name) + 1));
1785 }
1786 
1787 /*
1788  * Export a nul-separated, double-nul-terminated list of all function names
1789  * in the kernel.
1790  */
1791 static int
1792 sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
1793 {
1794 	linker_file_t lf;
1795 	int error;
1796 
1797 #ifdef MAC
1798 	error = mac_check_kld_stat(req->td->td_ucred);
1799 	if (error)
1800 		return (error);
1801 #endif
1802 	error = sysctl_wire_old_buffer(req, 0);
1803 	if (error != 0)
1804 		return (error);
1805 	mtx_lock(&kld_mtx);
1806 	TAILQ_FOREACH(lf, &linker_files, link) {
1807 		error = LINKER_EACH_FUNCTION_NAME(lf,
1808 		    sysctl_kern_function_list_iterate, req);
1809 		if (error) {
1810 			mtx_unlock(&kld_mtx);
1811 			return (error);
1812 		}
1813 	}
1814 	mtx_unlock(&kld_mtx);
1815 	return (SYSCTL_OUT(req, "", 1));
1816 }
1817 
1818 SYSCTL_PROC(_kern, OID_AUTO, function_list, CTLFLAG_RD,
1819     NULL, 0, sysctl_kern_function_list, "", "kernel function list");
1820