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