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