xref: /freebsd/sys/kern/kern_linker.c (revision f856af0466c076beef4ea9b15d088e1119a945b8)
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 			linker_file_register_sysctls(lf);
407 			linker_file_sysinit(lf);
408 			lf->flags |= LINKER_FILE_LINKED;
409 			*result = lf;
410 			return (0);
411 		}
412 	}
413 	/*
414 	 * Less than ideal, but tells the user whether it failed to load or
415 	 * the module was not found.
416 	 */
417 	if (foundfile) {
418 		/*
419 		 * Format not recognized or otherwise unloadable.
420 		 * When loading a module that is statically built into
421 		 * the kernel EEXIST percolates back up as the return
422 		 * value.  Preserve this so that apps like sysinstall
423 		 * can recognize this special case and not post bogus
424 		 * dialog boxes.
425 		 */
426 		if (error != EEXIST)
427 			error = ENOEXEC;
428 	} else
429 		error = ENOENT;		/* Nothing found */
430 	return (error);
431 }
432 
433 int
434 linker_reference_module(const char *modname, struct mod_depend *verinfo,
435     linker_file_t *result)
436 {
437 	modlist_t mod;
438 	int error;
439 
440 	KLD_LOCK();
441 	if ((mod = modlist_lookup2(modname, verinfo)) != NULL) {
442 		*result = mod->container;
443 		(*result)->refs++;
444 		KLD_UNLOCK();
445 		return (0);
446 	}
447 
448 	error = linker_load_module(NULL, modname, NULL, verinfo, result);
449 	KLD_UNLOCK();
450 	return (error);
451 }
452 
453 int
454 linker_release_module(const char *modname, struct mod_depend *verinfo,
455     linker_file_t lf)
456 {
457 	modlist_t mod;
458 	int error;
459 
460 	KLD_LOCK();
461 	if (lf == NULL) {
462 		KASSERT(modname != NULL,
463 		    ("linker_release_module: no file or name"));
464 		mod = modlist_lookup2(modname, verinfo);
465 		if (mod == NULL) {
466 			KLD_UNLOCK();
467 			return (ESRCH);
468 		}
469 		lf = mod->container;
470 	} else
471 		KASSERT(modname == NULL && verinfo == NULL,
472 		    ("linker_release_module: both file and name"));
473 	error =	linker_file_unload(lf, LINKER_UNLOAD_NORMAL);
474 	KLD_UNLOCK();
475 	return (error);
476 }
477 
478 static linker_file_t
479 linker_find_file_by_name(const char *filename)
480 {
481 	linker_file_t lf;
482 	char *koname;
483 
484 	koname = malloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
485 	sprintf(koname, "%s.ko", filename);
486 
487 	KLD_LOCK_ASSERT();
488 	TAILQ_FOREACH(lf, &linker_files, link) {
489 		if (strcmp(lf->filename, koname) == 0)
490 			break;
491 		if (strcmp(lf->filename, filename) == 0)
492 			break;
493 	}
494 	free(koname, M_LINKER);
495 	return (lf);
496 }
497 
498 static linker_file_t
499 linker_find_file_by_id(int fileid)
500 {
501 	linker_file_t lf;
502 
503 	KLD_LOCK_ASSERT();
504 	TAILQ_FOREACH(lf, &linker_files, link)
505 		if (lf->id == fileid)
506 			break;
507 	return (lf);
508 }
509 
510 int
511 linker_file_foreach(linker_predicate_t *predicate, void *context)
512 {
513 	linker_file_t lf;
514 	int retval = 0;
515 
516 	KLD_LOCK();
517 	TAILQ_FOREACH(lf, &linker_files, link) {
518 		retval = predicate(lf, context);
519 		if (retval != 0)
520 			break;
521 	}
522 	KLD_UNLOCK();
523 	return (retval);
524 }
525 
526 linker_file_t
527 linker_make_file(const char *pathname, linker_class_t lc)
528 {
529 	linker_file_t lf;
530 	const char *filename;
531 
532 	KLD_LOCK_ASSERT();
533 	filename = linker_basename(pathname);
534 
535 	KLD_DPF(FILE, ("linker_make_file: new file, filename=%s\n", filename));
536 	lf = (linker_file_t)kobj_create((kobj_class_t)lc, M_LINKER, M_WAITOK);
537 	if (lf == NULL)
538 		return (NULL);
539 	lf->refs = 1;
540 	lf->userrefs = 0;
541 	lf->flags = 0;
542 	lf->filename = linker_strdup(filename);
543 	LINKER_GET_NEXT_FILE_ID(lf->id);
544 	lf->ndeps = 0;
545 	lf->deps = NULL;
546 	STAILQ_INIT(&lf->common);
547 	TAILQ_INIT(&lf->modules);
548 	TAILQ_INSERT_TAIL(&linker_files, lf, link);
549 	return (lf);
550 }
551 
552 int
553 linker_file_unload(linker_file_t file, int flags)
554 {
555 	module_t mod, next;
556 	modlist_t ml, nextml;
557 	struct common_symbol *cp;
558 	int error, i;
559 
560 	/* Refuse to unload modules if securelevel raised. */
561 	if (securelevel > 0)
562 		return (EPERM);
563 #ifdef MAC
564 	error = mac_check_kld_unload(curthread->td_ucred);
565 	if (error)
566 		return (error);
567 #endif
568 
569 	KLD_LOCK_ASSERT();
570 	KLD_DPF(FILE, ("linker_file_unload: lf->refs=%d\n", file->refs));
571 
572 	/* Easy case of just dropping a reference. */
573 	if (file->refs > 1) {
574 		file->refs--;
575 		return (0);
576 	}
577 
578 	KLD_DPF(FILE, ("linker_file_unload: file is unloading,"
579 	    " informing modules\n"));
580 
581 	/*
582 	 * Inform any modules associated with this file.
583 	 */
584 	MOD_XLOCK;
585 	for (mod = TAILQ_FIRST(&file->modules); mod; mod = next) {
586 		next = module_getfnext(mod);
587 		MOD_XUNLOCK;
588 
589 		/*
590 		 * Give the module a chance to veto the unload.
591 		 */
592 		if ((error = module_unload(mod, flags)) != 0) {
593 			KLD_DPF(FILE, ("linker_file_unload: module %p"
594 			    " vetoes unload\n", mod));
595 			return (error);
596 		}
597 		MOD_XLOCK;
598 		module_release(mod);
599 	}
600 	MOD_XUNLOCK;
601 
602 	TAILQ_FOREACH_SAFE(ml, &found_modules, link, nextml) {
603 		if (ml->container == file) {
604 			TAILQ_REMOVE(&found_modules, ml, link);
605 			free(ml, M_LINKER);
606 		}
607 	}
608 
609 	/*
610 	 * Don't try to run SYSUNINITs if we are unloaded due to a
611 	 * link error.
612 	 */
613 	if (file->flags & LINKER_FILE_LINKED) {
614 		linker_file_sysuninit(file);
615 		linker_file_unregister_sysctls(file);
616 	}
617 	TAILQ_REMOVE(&linker_files, file, link);
618 
619 	if (file->deps) {
620 		for (i = 0; i < file->ndeps; i++)
621 			linker_file_unload(file->deps[i], flags);
622 		free(file->deps, M_LINKER);
623 		file->deps = NULL;
624 	}
625 	while ((cp = STAILQ_FIRST(&file->common)) != NULL) {
626 		STAILQ_REMOVE_HEAD(&file->common, link);
627 		free(cp, M_LINKER);
628 	}
629 
630 	LINKER_UNLOAD(file);
631 	if (file->filename) {
632 		free(file->filename, M_LINKER);
633 		file->filename = NULL;
634 	}
635 	kobj_delete((kobj_t) file, M_LINKER);
636 	return (0);
637 }
638 
639 static int
640 linker_file_add_dependency(linker_file_t file, linker_file_t dep)
641 {
642 	linker_file_t *newdeps;
643 
644 	KLD_LOCK_ASSERT();
645 	newdeps = malloc((file->ndeps + 1) * sizeof(linker_file_t *),
646 	    M_LINKER, M_WAITOK | M_ZERO);
647 	if (newdeps == NULL)
648 		return (ENOMEM);
649 
650 	if (file->deps) {
651 		bcopy(file->deps, newdeps,
652 		    file->ndeps * sizeof(linker_file_t *));
653 		free(file->deps, M_LINKER);
654 	}
655 	file->deps = newdeps;
656 	file->deps[file->ndeps] = dep;
657 	file->ndeps++;
658 	return (0);
659 }
660 
661 /*
662  * Locate a linker set and its contents.  This is a helper function to avoid
663  * linker_if.h exposure elsewhere.  Note: firstp and lastp are really void **.
664  * This function is used in this file so we can avoid having lots of (void **)
665  * casts.
666  */
667 int
668 linker_file_lookup_set(linker_file_t file, const char *name,
669     void *firstp, void *lastp, int *countp)
670 {
671 	int error, locked;
672 
673 	locked = KLD_LOCKED();
674 	if (!locked)
675 		KLD_LOCK();
676 	error = LINKER_LOOKUP_SET(file, name, firstp, lastp, countp);
677 	if (!locked)
678 		KLD_UNLOCK();
679 	return (error);
680 }
681 
682 caddr_t
683 linker_file_lookup_symbol(linker_file_t file, const char *name, int deps)
684 {
685 	caddr_t sym;
686 	int locked;
687 
688 	locked = KLD_LOCKED();
689 	if (!locked)
690 		KLD_LOCK();
691 	sym = linker_file_lookup_symbol_internal(file, name, deps);
692 	if (!locked)
693 		KLD_UNLOCK();
694 	return (sym);
695 }
696 
697 static caddr_t
698 linker_file_lookup_symbol_internal(linker_file_t file, const char *name,
699     int deps)
700 {
701 	c_linker_sym_t sym;
702 	linker_symval_t symval;
703 	caddr_t address;
704 	size_t common_size = 0;
705 	int i;
706 
707 	KLD_LOCK_ASSERT();
708 	KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%p, name=%s, deps=%d\n",
709 	    file, name, deps));
710 
711 	if (LINKER_LOOKUP_SYMBOL(file, name, &sym) == 0) {
712 		LINKER_SYMBOL_VALUES(file, sym, &symval);
713 		if (symval.value == 0)
714 			/*
715 			 * For commons, first look them up in the
716 			 * dependencies and only allocate space if not found
717 			 * there.
718 			 */
719 			common_size = symval.size;
720 		else {
721 			KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol"
722 			    ".value=%p\n", symval.value));
723 			return (symval.value);
724 		}
725 	}
726 	if (deps) {
727 		for (i = 0; i < file->ndeps; i++) {
728 			address = linker_file_lookup_symbol_internal(
729 			    file->deps[i], name, 0);
730 			if (address) {
731 				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
732 				    " deps value=%p\n", address));
733 				return (address);
734 			}
735 		}
736 	}
737 	if (common_size > 0) {
738 		/*
739 		 * This is a common symbol which was not found in the
740 		 * dependencies.  We maintain a simple common symbol table in
741 		 * the file object.
742 		 */
743 		struct common_symbol *cp;
744 
745 		STAILQ_FOREACH(cp, &file->common, link) {
746 			if (strcmp(cp->name, name) == 0) {
747 				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
748 				    " old common value=%p\n", cp->address));
749 				return (cp->address);
750 			}
751 		}
752 		/*
753 		 * Round the symbol size up to align.
754 		 */
755 		common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
756 		cp = malloc(sizeof(struct common_symbol)
757 		    + common_size + strlen(name) + 1, M_LINKER,
758 		    M_WAITOK | M_ZERO);
759 		cp->address = (caddr_t)(cp + 1);
760 		cp->name = cp->address + common_size;
761 		strcpy(cp->name, name);
762 		bzero(cp->address, common_size);
763 		STAILQ_INSERT_TAIL(&file->common, cp, link);
764 
765 		KLD_DPF(SYM, ("linker_file_lookup_symbol: new common"
766 		    " value=%p\n", cp->address));
767 		return (cp->address);
768 	}
769 	KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
770 	return (0);
771 }
772 
773 #ifdef DDB
774 /*
775  * DDB Helpers.  DDB has to look across multiple files with their own symbol
776  * tables and string tables.
777  *
778  * Note that we do not obey list locking protocols here.  We really don't need
779  * DDB to hang because somebody's got the lock held.  We'll take the chance
780  * that the files list is inconsistant instead.
781  */
782 
783 int
784 linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
785 {
786 	linker_file_t lf;
787 
788 	TAILQ_FOREACH(lf, &linker_files, link) {
789 		if (LINKER_LOOKUP_SYMBOL(lf, symstr, sym) == 0)
790 			return (0);
791 	}
792 	return (ENOENT);
793 }
794 
795 int
796 linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
797 {
798 	linker_file_t lf;
799 	c_linker_sym_t best, es;
800 	u_long diff, bestdiff, off;
801 
802 	best = 0;
803 	off = (uintptr_t)value;
804 	bestdiff = off;
805 	TAILQ_FOREACH(lf, &linker_files, link) {
806 		if (LINKER_SEARCH_SYMBOL(lf, value, &es, &diff) != 0)
807 			continue;
808 		if (es != 0 && diff < bestdiff) {
809 			best = es;
810 			bestdiff = diff;
811 		}
812 		if (bestdiff == 0)
813 			break;
814 	}
815 	if (best) {
816 		*sym = best;
817 		*diffp = bestdiff;
818 		return (0);
819 	} else {
820 		*sym = 0;
821 		*diffp = off;
822 		return (ENOENT);
823 	}
824 }
825 
826 int
827 linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
828 {
829 	linker_file_t lf;
830 
831 	TAILQ_FOREACH(lf, &linker_files, link) {
832 		if (LINKER_SYMBOL_VALUES(lf, sym, symval) == 0)
833 			return (0);
834 	}
835 	return (ENOENT);
836 }
837 #endif
838 
839 /*
840  * Syscalls.
841  */
842 /*
843  * MPSAFE
844  */
845 int
846 kern_kldload(struct thread *td, const char *file, int *fileid)
847 {
848 #ifdef HWPMC_HOOKS
849 	struct pmckern_map_in pkm;
850 #endif
851 	const char *kldname, *modname;
852 	linker_file_t lf;
853 	int error;
854 
855 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
856 		return (error);
857 
858 	if ((error = priv_check(td, PRIV_KLD_LOAD)) != 0)
859 		return (error);
860 
861 	/*
862 	 * If file does not contain a qualified name or any dot in it
863 	 * (kldname.ko, or kldname.ver.ko) treat it as an interface
864 	 * name.
865 	 */
866 	if (index(file, '/') || index(file, '.')) {
867 		kldname = file;
868 		modname = NULL;
869 	} else {
870 		kldname = NULL;
871 		modname = file;
872 	}
873 
874 	KLD_LOCK();
875 	error = linker_load_module(kldname, modname, NULL, NULL, &lf);
876 	if (error)
877 		goto unlock;
878 #ifdef HWPMC_HOOKS
879 	pkm.pm_file = lf->filename;
880 	pkm.pm_address = (uintptr_t) lf->address;
881 	PMC_CALL_HOOK(td, PMC_FN_KLD_LOAD, (void *) &pkm);
882 #endif
883 	lf->userrefs++;
884 	if (fileid != NULL)
885 		*fileid = lf->id;
886 unlock:
887 	KLD_UNLOCK();
888 	return (error);
889 }
890 
891 int
892 kldload(struct thread *td, struct kldload_args *uap)
893 {
894 	char *pathname = NULL;
895 	int error, fileid;
896 
897 	td->td_retval[0] = -1;
898 
899 	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
900 	error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL);
901 	if (error == 0) {
902 		error = kern_kldload(td, pathname, &fileid);
903 		if (error == 0)
904 			td->td_retval[0] = fileid;
905 	}
906 	free(pathname, M_TEMP);
907 	return (error);
908 }
909 
910 /*
911  * MPSAFE
912  */
913 int
914 kern_kldunload(struct thread *td, int fileid, int flags)
915 {
916 #ifdef HWPMC_HOOKS
917 	struct pmckern_map_out pkm;
918 #endif
919 	linker_file_t lf;
920 	int error = 0;
921 
922 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
923 		return (error);
924 
925 	if ((error = priv_check(td, PRIV_KLD_UNLOAD)) != 0)
926 		return (error);
927 
928 	KLD_LOCK();
929 	lf = linker_find_file_by_id(fileid);
930 	if (lf) {
931 		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
932 		if (lf->userrefs == 0) {
933 			/*
934 			 * XXX: maybe LINKER_UNLOAD_FORCE should override ?
935 			 */
936 			printf("kldunload: attempt to unload file that was"
937 			    " loaded by the kernel\n");
938 			error = EBUSY;
939 		} else {
940 #ifdef HWPMC_HOOKS
941 			/* Save data needed by hwpmc(4) before unloading. */
942 			pkm.pm_address = (uintptr_t) lf->address;
943 			pkm.pm_size = lf->size;
944 #endif
945 			lf->userrefs--;
946 			error = linker_file_unload(lf, flags);
947 			if (error)
948 				lf->userrefs++;
949 		}
950 	} else
951 		error = ENOENT;
952 
953 #ifdef HWPMC_HOOKS
954 	if (error == 0)
955 		PMC_CALL_HOOK(td, PMC_FN_KLD_UNLOAD, (void *) &pkm);
956 #endif
957 	KLD_UNLOCK();
958 	return (error);
959 }
960 
961 /*
962  * MPSAFE
963  */
964 int
965 kldunload(struct thread *td, struct kldunload_args *uap)
966 {
967 
968 	return (kern_kldunload(td, uap->fileid, LINKER_UNLOAD_NORMAL));
969 }
970 
971 /*
972  * MPSAFE
973  */
974 int
975 kldunloadf(struct thread *td, struct kldunloadf_args *uap)
976 {
977 
978 	if (uap->flags != LINKER_UNLOAD_NORMAL &&
979 	    uap->flags != LINKER_UNLOAD_FORCE)
980 		return (EINVAL);
981 	return (kern_kldunload(td, uap->fileid, uap->flags));
982 }
983 
984 /*
985  * MPSAFE
986  */
987 int
988 kldfind(struct thread *td, struct kldfind_args *uap)
989 {
990 	char *pathname;
991 	const char *filename;
992 	linker_file_t lf;
993 	int error;
994 
995 #ifdef MAC
996 	error = mac_check_kld_stat(td->td_ucred);
997 	if (error)
998 		return (error);
999 #endif
1000 
1001 	td->td_retval[0] = -1;
1002 
1003 	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1004 	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
1005 		goto out;
1006 
1007 	filename = linker_basename(pathname);
1008 	KLD_LOCK();
1009 	lf = linker_find_file_by_name(filename);
1010 	if (lf)
1011 		td->td_retval[0] = lf->id;
1012 	else
1013 		error = ENOENT;
1014 	KLD_UNLOCK();
1015 out:
1016 	free(pathname, M_TEMP);
1017 	return (error);
1018 }
1019 
1020 /*
1021  * MPSAFE
1022  */
1023 int
1024 kldnext(struct thread *td, struct kldnext_args *uap)
1025 {
1026 	linker_file_t lf;
1027 	int error = 0;
1028 
1029 #ifdef MAC
1030 	error = mac_check_kld_stat(td->td_ucred);
1031 	if (error)
1032 		return (error);
1033 #endif
1034 
1035 	KLD_LOCK();
1036 	if (uap->fileid == 0) {
1037 		if (TAILQ_FIRST(&linker_files))
1038 			td->td_retval[0] = TAILQ_FIRST(&linker_files)->id;
1039 		else
1040 			td->td_retval[0] = 0;
1041 		goto out;
1042 	}
1043 	lf = linker_find_file_by_id(uap->fileid);
1044 	if (lf) {
1045 		if (TAILQ_NEXT(lf, link))
1046 			td->td_retval[0] = TAILQ_NEXT(lf, link)->id;
1047 		else
1048 			td->td_retval[0] = 0;
1049 	} else
1050 		error = ENOENT;
1051 out:
1052 	KLD_UNLOCK();
1053 	return (error);
1054 }
1055 
1056 /*
1057  * MPSAFE
1058  */
1059 int
1060 kldstat(struct thread *td, struct kldstat_args *uap)
1061 {
1062 	struct kld_file_stat stat;
1063 	linker_file_t lf;
1064 	int error, namelen;
1065 
1066 	/*
1067 	 * Check the version of the user's structure.
1068 	 */
1069 	error = copyin(uap->stat, &stat, sizeof(struct kld_file_stat));
1070 	if (error)
1071 		return (error);
1072 	if (stat.version != sizeof(struct kld_file_stat))
1073 		return (EINVAL);
1074 
1075 #ifdef MAC
1076 	error = mac_check_kld_stat(td->td_ucred);
1077 	if (error)
1078 		return (error);
1079 #endif
1080 
1081 	KLD_LOCK();
1082 	lf = linker_find_file_by_id(uap->fileid);
1083 	if (lf == NULL) {
1084 		KLD_UNLOCK();
1085 		return (ENOENT);
1086 	}
1087 
1088 	namelen = strlen(lf->filename) + 1;
1089 	if (namelen > MAXPATHLEN)
1090 		namelen = MAXPATHLEN;
1091 	bcopy(lf->filename, &stat.name[0], namelen);
1092 	stat.refs = lf->refs;
1093 	stat.id = lf->id;
1094 	stat.address = lf->address;
1095 	stat.size = lf->size;
1096 	KLD_UNLOCK();
1097 
1098 	td->td_retval[0] = 0;
1099 
1100 	return (copyout(&stat, uap->stat, sizeof(struct kld_file_stat)));
1101 }
1102 
1103 /*
1104  * MPSAFE
1105  */
1106 int
1107 kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
1108 {
1109 	linker_file_t lf;
1110 	module_t mp;
1111 	int error = 0;
1112 
1113 #ifdef MAC
1114 	error = mac_check_kld_stat(td->td_ucred);
1115 	if (error)
1116 		return (error);
1117 #endif
1118 
1119 	KLD_LOCK();
1120 	lf = linker_find_file_by_id(uap->fileid);
1121 	if (lf) {
1122 		MOD_SLOCK;
1123 		mp = TAILQ_FIRST(&lf->modules);
1124 		if (mp != NULL)
1125 			td->td_retval[0] = module_getid(mp);
1126 		else
1127 			td->td_retval[0] = 0;
1128 		MOD_SUNLOCK;
1129 	} else
1130 		error = ENOENT;
1131 	KLD_UNLOCK();
1132 	return (error);
1133 }
1134 
1135 /*
1136  * MPSAFE
1137  */
1138 int
1139 kldsym(struct thread *td, struct kldsym_args *uap)
1140 {
1141 	char *symstr = NULL;
1142 	c_linker_sym_t sym;
1143 	linker_symval_t symval;
1144 	linker_file_t lf;
1145 	struct kld_sym_lookup lookup;
1146 	int error = 0;
1147 
1148 #ifdef MAC
1149 	error = mac_check_kld_stat(td->td_ucred);
1150 	if (error)
1151 		return (error);
1152 #endif
1153 
1154 	if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
1155 		return (error);
1156 	if (lookup.version != sizeof(lookup) ||
1157 	    uap->cmd != KLDSYM_LOOKUP)
1158 		return (EINVAL);
1159 	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1160 	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
1161 		goto out;
1162 	KLD_LOCK();
1163 	if (uap->fileid != 0) {
1164 		lf = linker_find_file_by_id(uap->fileid);
1165 		if (lf == NULL)
1166 			error = ENOENT;
1167 		else if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1168 		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1169 			lookup.symvalue = (uintptr_t) symval.value;
1170 			lookup.symsize = symval.size;
1171 			error = copyout(&lookup, uap->data, sizeof(lookup));
1172 		} else
1173 			error = ENOENT;
1174 	} else {
1175 		TAILQ_FOREACH(lf, &linker_files, link) {
1176 			if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1177 			    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1178 				lookup.symvalue = (uintptr_t)symval.value;
1179 				lookup.symsize = symval.size;
1180 				error = copyout(&lookup, uap->data,
1181 				    sizeof(lookup));
1182 				break;
1183 			}
1184 		}
1185 		if (lf == NULL)
1186 			error = ENOENT;
1187 	}
1188 	KLD_UNLOCK();
1189 out:
1190 	free(symstr, M_TEMP);
1191 	return (error);
1192 }
1193 
1194 /*
1195  * Preloaded module support
1196  */
1197 
1198 static modlist_t
1199 modlist_lookup(const char *name, int ver)
1200 {
1201 	modlist_t mod;
1202 
1203 	TAILQ_FOREACH(mod, &found_modules, link) {
1204 		if (strcmp(mod->name, name) == 0 &&
1205 		    (ver == 0 || mod->version == ver))
1206 			return (mod);
1207 	}
1208 	return (NULL);
1209 }
1210 
1211 static modlist_t
1212 modlist_lookup2(const char *name, struct mod_depend *verinfo)
1213 {
1214 	modlist_t mod, bestmod;
1215 	int ver;
1216 
1217 	if (verinfo == NULL)
1218 		return (modlist_lookup(name, 0));
1219 	bestmod = NULL;
1220 	TAILQ_FOREACH(mod, &found_modules, link) {
1221 		if (strcmp(mod->name, name) != 0)
1222 			continue;
1223 		ver = mod->version;
1224 		if (ver == verinfo->md_ver_preferred)
1225 			return (mod);
1226 		if (ver >= verinfo->md_ver_minimum &&
1227 		    ver <= verinfo->md_ver_maximum &&
1228 		    (bestmod == NULL || ver > bestmod->version))
1229 			bestmod = mod;
1230 	}
1231 	return (bestmod);
1232 }
1233 
1234 static modlist_t
1235 modlist_newmodule(const char *modname, int version, linker_file_t container)
1236 {
1237 	modlist_t mod;
1238 
1239 	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1240 	if (mod == NULL)
1241 		panic("no memory for module list");
1242 	mod->container = container;
1243 	mod->name = modname;
1244 	mod->version = version;
1245 	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1246 	return (mod);
1247 }
1248 
1249 static void
1250 linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1251     struct mod_metadata **stop, int preload)
1252 {
1253 	struct mod_metadata *mp, **mdp;
1254 	const char *modname;
1255 	int ver;
1256 
1257 	for (mdp = start; mdp < stop; mdp++) {
1258 		mp = *mdp;
1259 		if (mp->md_type != MDT_VERSION)
1260 			continue;
1261 		modname = mp->md_cval;
1262 		ver = ((struct mod_version *)mp->md_data)->mv_version;
1263 		if (modlist_lookup(modname, ver) != NULL) {
1264 			printf("module %s already present!\n", modname);
1265 			/* XXX what can we do? this is a build error. :-( */
1266 			continue;
1267 		}
1268 		modlist_newmodule(modname, ver, lf);
1269 	}
1270 }
1271 
1272 static void
1273 linker_preload(void *arg)
1274 {
1275 	caddr_t modptr;
1276 	const char *modname, *nmodname;
1277 	char *modtype;
1278 	linker_file_t lf, nlf;
1279 	linker_class_t lc;
1280 	int error;
1281 	linker_file_list_t loaded_files;
1282 	linker_file_list_t depended_files;
1283 	struct mod_metadata *mp, *nmp;
1284 	struct mod_metadata **start, **stop, **mdp, **nmdp;
1285 	struct mod_depend *verinfo;
1286 	int nver;
1287 	int resolves;
1288 	modlist_t mod;
1289 	struct sysinit **si_start, **si_stop;
1290 
1291 	TAILQ_INIT(&loaded_files);
1292 	TAILQ_INIT(&depended_files);
1293 	TAILQ_INIT(&found_modules);
1294 	error = 0;
1295 
1296 	modptr = NULL;
1297 	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1298 		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1299 		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1300 		if (modname == NULL) {
1301 			printf("Preloaded module at %p does not have a"
1302 			    " name!\n", modptr);
1303 			continue;
1304 		}
1305 		if (modtype == NULL) {
1306 			printf("Preloaded module at %p does not have a type!\n",
1307 			    modptr);
1308 			continue;
1309 		}
1310 		if (bootverbose)
1311 			printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1312 			    modptr);
1313 		lf = NULL;
1314 		TAILQ_FOREACH(lc, &classes, link) {
1315 			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1316 			if (!error)
1317 				break;
1318 			lf = NULL;
1319 		}
1320 		if (lf)
1321 			TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1322 	}
1323 
1324 	/*
1325 	 * First get a list of stuff in the kernel.
1326 	 */
1327 	if (linker_file_lookup_set(linker_kernel_file, MDT_SETNAME, &start,
1328 	    &stop, NULL) == 0)
1329 		linker_addmodules(linker_kernel_file, start, stop, 1);
1330 
1331 	/*
1332 	 * this is a once-off kinky bubble sort resolve relocation dependency
1333 	 * requirements
1334 	 */
1335 restart:
1336 	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1337 		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1338 		    &stop, NULL);
1339 		/*
1340 		 * First, look to see if we would successfully link with this
1341 		 * stuff.
1342 		 */
1343 		resolves = 1;	/* unless we know otherwise */
1344 		if (!error) {
1345 			for (mdp = start; mdp < stop; mdp++) {
1346 				mp = *mdp;
1347 				if (mp->md_type != MDT_DEPEND)
1348 					continue;
1349 				modname = mp->md_cval;
1350 				verinfo = mp->md_data;
1351 				for (nmdp = start; nmdp < stop; nmdp++) {
1352 					nmp = *nmdp;
1353 					if (nmp->md_type != MDT_VERSION)
1354 						continue;
1355 					nmodname = nmp->md_cval;
1356 					if (strcmp(modname, nmodname) == 0)
1357 						break;
1358 				}
1359 				if (nmdp < stop)   /* it's a self reference */
1360 					continue;
1361 
1362 				/*
1363 				 * ok, the module isn't here yet, we
1364 				 * are not finished
1365 				 */
1366 				if (modlist_lookup2(modname, verinfo) == NULL)
1367 					resolves = 0;
1368 			}
1369 		}
1370 		/*
1371 		 * OK, if we found our modules, we can link.  So, "provide"
1372 		 * the modules inside and add it to the end of the link order
1373 		 * list.
1374 		 */
1375 		if (resolves) {
1376 			if (!error) {
1377 				for (mdp = start; mdp < stop; mdp++) {
1378 					mp = *mdp;
1379 					if (mp->md_type != MDT_VERSION)
1380 						continue;
1381 					modname = mp->md_cval;
1382 					nver = ((struct mod_version *)
1383 					    mp->md_data)->mv_version;
1384 					if (modlist_lookup(modname,
1385 					    nver) != NULL) {
1386 						printf("module %s already"
1387 						    " present!\n", modname);
1388 						TAILQ_REMOVE(&loaded_files,
1389 						    lf, loaded);
1390 						linker_file_unload(lf,
1391 						    LINKER_UNLOAD_FORCE);
1392 						/* we changed tailq next ptr */
1393 						goto restart;
1394 					}
1395 					modlist_newmodule(modname, nver, lf);
1396 				}
1397 			}
1398 			TAILQ_REMOVE(&loaded_files, lf, loaded);
1399 			TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1400 			/*
1401 			 * Since we provided modules, we need to restart the
1402 			 * sort so that the previous files that depend on us
1403 			 * have a chance. Also, we've busted the tailq next
1404 			 * pointer with the REMOVE.
1405 			 */
1406 			goto restart;
1407 		}
1408 	}
1409 
1410 	/*
1411 	 * At this point, we check to see what could not be resolved..
1412 	 */
1413 	while ((lf = TAILQ_FIRST(&loaded_files)) != NULL) {
1414 		TAILQ_REMOVE(&loaded_files, lf, loaded);
1415 		printf("KLD file %s is missing dependencies\n", lf->filename);
1416 		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1417 	}
1418 
1419 	/*
1420 	 * We made it. Finish off the linking in the order we determined.
1421 	 */
1422 	TAILQ_FOREACH_SAFE(lf, &depended_files, loaded, nlf) {
1423 		if (linker_kernel_file) {
1424 			linker_kernel_file->refs++;
1425 			error = linker_file_add_dependency(lf,
1426 			    linker_kernel_file);
1427 			if (error)
1428 				panic("cannot add dependency");
1429 		}
1430 		lf->userrefs++;	/* so we can (try to) kldunload it */
1431 		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1432 		    &stop, NULL);
1433 		if (!error) {
1434 			for (mdp = start; mdp < stop; mdp++) {
1435 				mp = *mdp;
1436 				if (mp->md_type != MDT_DEPEND)
1437 					continue;
1438 				modname = mp->md_cval;
1439 				verinfo = mp->md_data;
1440 				mod = modlist_lookup2(modname, verinfo);
1441 				/* Don't count self-dependencies */
1442 				if (lf == mod->container)
1443 					continue;
1444 				mod->container->refs++;
1445 				error = linker_file_add_dependency(lf,
1446 				    mod->container);
1447 				if (error)
1448 					panic("cannot add dependency");
1449 			}
1450 		}
1451 		/*
1452 		 * Now do relocation etc using the symbol search paths
1453 		 * established by the dependencies
1454 		 */
1455 		error = LINKER_LINK_PRELOAD_FINISH(lf);
1456 		if (error) {
1457 			TAILQ_REMOVE(&depended_files, lf, loaded);
1458 			printf("KLD file %s - could not finalize loading\n",
1459 			    lf->filename);
1460 			linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1461 			continue;
1462 		}
1463 		linker_file_register_modules(lf);
1464 		if (linker_file_lookup_set(lf, "sysinit_set", &si_start,
1465 		    &si_stop, NULL) == 0)
1466 			sysinit_add(si_start, si_stop);
1467 		linker_file_register_sysctls(lf);
1468 		lf->flags |= LINKER_FILE_LINKED;
1469 	}
1470 	/* woohoo! we made it! */
1471 }
1472 
1473 SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, 0)
1474 
1475 /*
1476  * Search for a not-loaded module by name.
1477  *
1478  * Modules may be found in the following locations:
1479  *
1480  * - preloaded (result is just the module name) - on disk (result is full path
1481  * to module)
1482  *
1483  * If the module name is qualified in any way (contains path, etc.) the we
1484  * simply return a copy of it.
1485  *
1486  * The search path can be manipulated via sysctl.  Note that we use the ';'
1487  * character as a separator to be consistent with the bootloader.
1488  */
1489 
1490 static char linker_hintfile[] = "linker.hints";
1491 static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules";
1492 
1493 SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RW, linker_path,
1494     sizeof(linker_path), "module load search path");
1495 
1496 TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1497 
1498 static char *linker_ext_list[] = {
1499 	"",
1500 	".ko",
1501 	NULL
1502 };
1503 
1504 /*
1505  * Check if file actually exists either with or without extension listed in
1506  * the linker_ext_list. (probably should be generic for the rest of the
1507  * kernel)
1508  */
1509 static char *
1510 linker_lookup_file(const char *path, int pathlen, const char *name,
1511     int namelen, struct vattr *vap)
1512 {
1513 	struct nameidata nd;
1514 	struct thread *td = curthread;	/* XXX */
1515 	char *result, **cpp, *sep;
1516 	int error, len, extlen, reclen, flags, vfslocked;
1517 	enum vtype type;
1518 
1519 	extlen = 0;
1520 	for (cpp = linker_ext_list; *cpp; cpp++) {
1521 		len = strlen(*cpp);
1522 		if (len > extlen)
1523 			extlen = len;
1524 	}
1525 	extlen++;		/* trailing '\0' */
1526 	sep = (path[pathlen - 1] != '/') ? "/" : "";
1527 
1528 	reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1529 	result = malloc(reclen, M_LINKER, M_WAITOK);
1530 	for (cpp = linker_ext_list; *cpp; cpp++) {
1531 		snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1532 		    namelen, name, *cpp);
1533 		/*
1534 		 * Attempt to open the file, and return the path if
1535 		 * we succeed and it's a regular file.
1536 		 */
1537 		NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, result, td);
1538 		flags = FREAD;
1539 		error = vn_open(&nd, &flags, 0, -1);
1540 		if (error == 0) {
1541 			vfslocked = NDHASGIANT(&nd);
1542 			NDFREE(&nd, NDF_ONLY_PNBUF);
1543 			type = nd.ni_vp->v_type;
1544 			if (vap)
1545 				VOP_GETATTR(nd.ni_vp, vap, td->td_ucred, td);
1546 			VOP_UNLOCK(nd.ni_vp, 0, td);
1547 			vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1548 			VFS_UNLOCK_GIANT(vfslocked);
1549 			if (type == VREG)
1550 				return (result);
1551 		}
1552 	}
1553 	free(result, M_LINKER);
1554 	return (NULL);
1555 }
1556 
1557 #define	INT_ALIGN(base, ptr)	ptr =					\
1558 	(base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
1559 
1560 /*
1561  * Lookup KLD which contains requested module in the "linker.hints" file. If
1562  * version specification is available, then try to find the best KLD.
1563  * Otherwise just find the latest one.
1564  */
1565 static char *
1566 linker_hints_lookup(const char *path, int pathlen, const char *modname,
1567     int modnamelen, struct mod_depend *verinfo)
1568 {
1569 	struct thread *td = curthread;	/* XXX */
1570 	struct ucred *cred = td ? td->td_ucred : NULL;
1571 	struct nameidata nd;
1572 	struct vattr vattr, mattr;
1573 	u_char *hints = NULL;
1574 	u_char *cp, *recptr, *bufend, *result, *best, *pathbuf, *sep;
1575 	int error, ival, bestver, *intp, reclen, found, flags, clen, blen;
1576 	int vfslocked = 0;
1577 
1578 	result = NULL;
1579 	bestver = found = 0;
1580 
1581 	sep = (path[pathlen - 1] != '/') ? "/" : "";
1582 	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1583 	    strlen(sep) + 1;
1584 	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1585 	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1586 	    linker_hintfile);
1587 
1588 	NDINIT(&nd, LOOKUP, NOFOLLOW | MPSAFE, UIO_SYSSPACE, pathbuf, td);
1589 	flags = FREAD;
1590 	error = vn_open(&nd, &flags, 0, -1);
1591 	if (error)
1592 		goto bad;
1593 	vfslocked = NDHASGIANT(&nd);
1594 	NDFREE(&nd, NDF_ONLY_PNBUF);
1595 	if (nd.ni_vp->v_type != VREG)
1596 		goto bad;
1597 	best = cp = NULL;
1598 	error = VOP_GETATTR(nd.ni_vp, &vattr, cred, td);
1599 	if (error)
1600 		goto bad;
1601 	/*
1602 	 * XXX: we need to limit this number to some reasonable value
1603 	 */
1604 	if (vattr.va_size > 100 * 1024) {
1605 		printf("hints file too large %ld\n", (long)vattr.va_size);
1606 		goto bad;
1607 	}
1608 	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
1609 	if (hints == NULL)
1610 		goto bad;
1611 	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
1612 	    UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
1613 	if (error)
1614 		goto bad;
1615 	VOP_UNLOCK(nd.ni_vp, 0, td);
1616 	vn_close(nd.ni_vp, FREAD, cred, td);
1617 	VFS_UNLOCK_GIANT(vfslocked);
1618 	nd.ni_vp = NULL;
1619 	if (reclen != 0) {
1620 		printf("can't read %d\n", reclen);
1621 		goto bad;
1622 	}
1623 	intp = (int *)hints;
1624 	ival = *intp++;
1625 	if (ival != LINKER_HINTS_VERSION) {
1626 		printf("hints file version mismatch %d\n", ival);
1627 		goto bad;
1628 	}
1629 	bufend = hints + vattr.va_size;
1630 	recptr = (u_char *)intp;
1631 	clen = blen = 0;
1632 	while (recptr < bufend && !found) {
1633 		intp = (int *)recptr;
1634 		reclen = *intp++;
1635 		ival = *intp++;
1636 		cp = (char *)intp;
1637 		switch (ival) {
1638 		case MDT_VERSION:
1639 			clen = *cp++;
1640 			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1641 				break;
1642 			cp += clen;
1643 			INT_ALIGN(hints, cp);
1644 			ival = *(int *)cp;
1645 			cp += sizeof(int);
1646 			clen = *cp++;
1647 			if (verinfo == NULL ||
1648 			    ival == verinfo->md_ver_preferred) {
1649 				found = 1;
1650 				break;
1651 			}
1652 			if (ival >= verinfo->md_ver_minimum &&
1653 			    ival <= verinfo->md_ver_maximum &&
1654 			    ival > bestver) {
1655 				bestver = ival;
1656 				best = cp;
1657 				blen = clen;
1658 			}
1659 			break;
1660 		default:
1661 			break;
1662 		}
1663 		recptr += reclen + sizeof(int);
1664 	}
1665 	/*
1666 	 * Finally check if KLD is in the place
1667 	 */
1668 	if (found)
1669 		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
1670 	else if (best)
1671 		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
1672 
1673 	/*
1674 	 * KLD is newer than hints file. What we should do now?
1675 	 */
1676 	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
1677 		printf("warning: KLD '%s' is newer than the linker.hints"
1678 		    " file\n", result);
1679 bad:
1680 	free(pathbuf, M_LINKER);
1681 	if (hints)
1682 		free(hints, M_TEMP);
1683 	if (nd.ni_vp != NULL) {
1684 		VOP_UNLOCK(nd.ni_vp, 0, td);
1685 		vn_close(nd.ni_vp, FREAD, cred, td);
1686 		VFS_UNLOCK_GIANT(vfslocked);
1687 	}
1688 	/*
1689 	 * If nothing found or hints is absent - fallback to the old
1690 	 * way by using "kldname[.ko]" as module name.
1691 	 */
1692 	if (!found && !bestver && result == NULL)
1693 		result = linker_lookup_file(path, pathlen, modname,
1694 		    modnamelen, NULL);
1695 	return (result);
1696 }
1697 
1698 /*
1699  * Lookup KLD which contains requested module in the all directories.
1700  */
1701 static char *
1702 linker_search_module(const char *modname, int modnamelen,
1703     struct mod_depend *verinfo)
1704 {
1705 	char *cp, *ep, *result;
1706 
1707 	/*
1708 	 * traverse the linker path
1709 	 */
1710 	for (cp = linker_path; *cp; cp = ep + 1) {
1711 		/* find the end of this component */
1712 		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
1713 		result = linker_hints_lookup(cp, ep - cp, modname,
1714 		    modnamelen, verinfo);
1715 		if (result != NULL)
1716 			return (result);
1717 		if (*ep == 0)
1718 			break;
1719 	}
1720 	return (NULL);
1721 }
1722 
1723 /*
1724  * Search for module in all directories listed in the linker_path.
1725  */
1726 static char *
1727 linker_search_kld(const char *name)
1728 {
1729 	char *cp, *ep, *result;
1730 	int len;
1731 
1732 	/* qualified at all? */
1733 	if (index(name, '/'))
1734 		return (linker_strdup(name));
1735 
1736 	/* traverse the linker path */
1737 	len = strlen(name);
1738 	for (ep = linker_path; *ep; ep++) {
1739 		cp = ep;
1740 		/* find the end of this component */
1741 		for (; *ep != 0 && *ep != ';'; ep++);
1742 		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
1743 		if (result != NULL)
1744 			return (result);
1745 	}
1746 	return (NULL);
1747 }
1748 
1749 static const char *
1750 linker_basename(const char *path)
1751 {
1752 	const char *filename;
1753 
1754 	filename = rindex(path, '/');
1755 	if (filename == NULL)
1756 		return path;
1757 	if (filename[1])
1758 		filename++;
1759 	return (filename);
1760 }
1761 
1762 #ifdef HWPMC_HOOKS
1763 
1764 struct hwpmc_context {
1765 	int	nobjects;
1766 	int	nmappings;
1767 	struct pmckern_map_in *kobase;
1768 };
1769 
1770 static int
1771 linker_hwpmc_list_object(linker_file_t lf, void *arg)
1772 {
1773 	struct hwpmc_context *hc;
1774 
1775 	hc = arg;
1776 
1777 	/* If we run out of mappings, fail. */
1778 	if (hc->nobjects >= hc->nmappings)
1779 		return (1);
1780 
1781 	/* Save the info for this linker file. */
1782 	hc->kobase[hc->nobjects].pm_file = lf->filename;
1783 	hc->kobase[hc->nobjects].pm_address = (uintptr_t)lf->address;
1784 	hc->nobjects++;
1785 	return (0);
1786 }
1787 
1788 /*
1789  * Inform hwpmc about the set of kernel modules currently loaded.
1790  */
1791 void *
1792 linker_hwpmc_list_objects(void)
1793 {
1794 	struct hwpmc_context hc;
1795 
1796 	hc.nmappings = 15;	/* a reasonable default */
1797 
1798  retry:
1799 	/* allocate nmappings+1 entries */
1800 	MALLOC(hc.kobase, struct pmckern_map_in *,
1801 	    (hc.nmappings + 1) * sizeof(struct pmckern_map_in), M_LINKER,
1802 	    M_WAITOK | M_ZERO);
1803 
1804 	hc.nobjects = 0;
1805 	if (linker_file_foreach(linker_hwpmc_list_object, &hc) != 0) {
1806 		hc.nmappings = hc.nobjects;
1807 		FREE(hc.kobase, M_LINKER);
1808 		goto retry;
1809 	}
1810 
1811 	KASSERT(hc.nobjects > 0, ("linker_hpwmc_list_objects: no kernel "
1812 		"objects?"));
1813 
1814 	/* The last entry of the malloced area comprises of all zeros. */
1815 	KASSERT(hc.kobase[hc.nobjects].pm_file == NULL,
1816 	    ("linker_hwpmc_list_objects: last object not NULL"));
1817 
1818 	return ((void *)hc.kobase);
1819 }
1820 #endif
1821 
1822 /*
1823  * Find a file which contains given module and load it, if "parent" is not
1824  * NULL, register a reference to it.
1825  */
1826 static int
1827 linker_load_module(const char *kldname, const char *modname,
1828     struct linker_file *parent, struct mod_depend *verinfo,
1829     struct linker_file **lfpp)
1830 {
1831 	linker_file_t lfdep;
1832 	const char *filename;
1833 	char *pathname;
1834 	int error;
1835 
1836 	KLD_LOCK_ASSERT();
1837 	if (modname == NULL) {
1838 		/*
1839  		 * We have to load KLD
1840  		 */
1841 		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
1842 		    " is not NULL"));
1843 		pathname = linker_search_kld(kldname);
1844 	} else {
1845 		if (modlist_lookup2(modname, verinfo) != NULL)
1846 			return (EEXIST);
1847 		if (kldname != NULL)
1848 			pathname = linker_strdup(kldname);
1849 		else if (rootvnode == NULL)
1850 			pathname = NULL;
1851 		else
1852 			/*
1853 			 * Need to find a KLD with required module
1854 			 */
1855 			pathname = linker_search_module(modname,
1856 			    strlen(modname), verinfo);
1857 	}
1858 	if (pathname == NULL)
1859 		return (ENOENT);
1860 
1861 	/*
1862 	 * Can't load more than one file with the same basename XXX:
1863 	 * Actually it should be possible to have multiple KLDs with
1864 	 * the same basename but different path because they can
1865 	 * provide different versions of the same modules.
1866 	 */
1867 	filename = linker_basename(pathname);
1868 	if (linker_find_file_by_name(filename))
1869 		error = EEXIST;
1870 	else do {
1871 		error = linker_load_file(pathname, &lfdep);
1872 		if (error)
1873 			break;
1874 		if (modname && verinfo &&
1875 		    modlist_lookup2(modname, verinfo) == NULL) {
1876 			linker_file_unload(lfdep, LINKER_UNLOAD_FORCE);
1877 			error = ENOENT;
1878 			break;
1879 		}
1880 		if (parent) {
1881 			error = linker_file_add_dependency(parent, lfdep);
1882 			if (error)
1883 				break;
1884 		}
1885 		if (lfpp)
1886 			*lfpp = lfdep;
1887 	} while (0);
1888 	free(pathname, M_LINKER);
1889 	return (error);
1890 }
1891 
1892 /*
1893  * This routine is responsible for finding dependencies of userland initiated
1894  * kldload(2)'s of files.
1895  */
1896 int
1897 linker_load_dependencies(linker_file_t lf)
1898 {
1899 	linker_file_t lfdep;
1900 	struct mod_metadata **start, **stop, **mdp, **nmdp;
1901 	struct mod_metadata *mp, *nmp;
1902 	struct mod_depend *verinfo;
1903 	modlist_t mod;
1904 	const char *modname, *nmodname;
1905 	int ver, error = 0, count;
1906 
1907 	/*
1908 	 * All files are dependant on /kernel.
1909 	 */
1910 	KLD_LOCK_ASSERT();
1911 	if (linker_kernel_file) {
1912 		linker_kernel_file->refs++;
1913 		error = linker_file_add_dependency(lf, linker_kernel_file);
1914 		if (error)
1915 			return (error);
1916 	}
1917 	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
1918 	    &count) != 0)
1919 		return (0);
1920 	for (mdp = start; mdp < stop; mdp++) {
1921 		mp = *mdp;
1922 		if (mp->md_type != MDT_VERSION)
1923 			continue;
1924 		modname = mp->md_cval;
1925 		ver = ((struct mod_version *)mp->md_data)->mv_version;
1926 		mod = modlist_lookup(modname, ver);
1927 		if (mod != NULL) {
1928 			printf("interface %s.%d already present in the KLD"
1929 			    " '%s'!\n", modname, ver,
1930 			    mod->container->filename);
1931 			return (EEXIST);
1932 		}
1933 	}
1934 
1935 	for (mdp = start; mdp < stop; mdp++) {
1936 		mp = *mdp;
1937 		if (mp->md_type != MDT_DEPEND)
1938 			continue;
1939 		modname = mp->md_cval;
1940 		verinfo = mp->md_data;
1941 		nmodname = NULL;
1942 		for (nmdp = start; nmdp < stop; nmdp++) {
1943 			nmp = *nmdp;
1944 			if (nmp->md_type != MDT_VERSION)
1945 				continue;
1946 			nmodname = nmp->md_cval;
1947 			if (strcmp(modname, nmodname) == 0)
1948 				break;
1949 		}
1950 		if (nmdp < stop)/* early exit, it's a self reference */
1951 			continue;
1952 		mod = modlist_lookup2(modname, verinfo);
1953 		if (mod) {	/* woohoo, it's loaded already */
1954 			lfdep = mod->container;
1955 			lfdep->refs++;
1956 			error = linker_file_add_dependency(lf, lfdep);
1957 			if (error)
1958 				break;
1959 			continue;
1960 		}
1961 		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
1962 		if (error) {
1963 			printf("KLD %s: depends on %s - not available\n",
1964 			    lf->filename, modname);
1965 			break;
1966 		}
1967 	}
1968 
1969 	if (error)
1970 		return (error);
1971 	linker_addmodules(lf, start, stop, 0);
1972 	return (error);
1973 }
1974 
1975 static int
1976 sysctl_kern_function_list_iterate(const char *name, void *opaque)
1977 {
1978 	struct sysctl_req *req;
1979 
1980 	req = opaque;
1981 	return (SYSCTL_OUT(req, name, strlen(name) + 1));
1982 }
1983 
1984 /*
1985  * Export a nul-separated, double-nul-terminated list of all function names
1986  * in the kernel.
1987  */
1988 static int
1989 sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
1990 {
1991 	linker_file_t lf;
1992 	int error;
1993 
1994 #ifdef MAC
1995 	error = mac_check_kld_stat(req->td->td_ucred);
1996 	if (error)
1997 		return (error);
1998 #endif
1999 	error = sysctl_wire_old_buffer(req, 0);
2000 	if (error != 0)
2001 		return (error);
2002 	KLD_LOCK();
2003 	TAILQ_FOREACH(lf, &linker_files, link) {
2004 		error = LINKER_EACH_FUNCTION_NAME(lf,
2005 		    sysctl_kern_function_list_iterate, req);
2006 		if (error) {
2007 			KLD_UNLOCK();
2008 			return (error);
2009 		}
2010 	}
2011 	KLD_UNLOCK();
2012 	return (SYSCTL_OUT(req, "", 1));
2013 }
2014 
2015 SYSCTL_PROC(_kern, OID_AUTO, function_list, CTLFLAG_RD,
2016     NULL, 0, sysctl_kern_function_list, "", "kernel function list");
2017