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